@sockethub/data-layer 1.0.0-alpha.3

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.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,31 @@
1
+ import { IActivityStream } from "@sockethub/schemas";
2
+ import { RedisConfigProps, RedisConfigUrl } from "./types";
3
+ /**
4
+ * Encapsulates the storing and fetching of credential objects.
5
+ */
6
+ export default class CredentialsStore {
7
+ readonly uid: string;
8
+ private readonly store;
9
+ private readonly log;
10
+ protected initialized: boolean;
11
+ /**
12
+ * @param parentId - The ID of the parent instance (eg. sockethub itself)
13
+ * @param sessionId - The ID of the session (socket.io connection)
14
+ * @param secret - The encryption secret (parent + session secrets)
15
+ * @param redisConfig - Connect info for redis
16
+ */
17
+ constructor(parentId: string, sessionId: string, secret: string, redisConfig: RedisConfigProps | RedisConfigUrl);
18
+ init(): Promise<void>;
19
+ /**
20
+ * Gets the credentials for a given actor ID
21
+ * @param actor
22
+ * @param credentialHash
23
+ */
24
+ get(actor: string, credentialHash?: string): Promise<IActivityStream>;
25
+ /**
26
+ * Saves the credentials for a given actor ID
27
+ * @param actor
28
+ * @param creds
29
+ */
30
+ save(actor: string, creds: IActivityStream): Promise<void>;
31
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const secure_store_redis_1 = __importDefault(require("secure-store-redis"));
7
+ const debug_1 = __importDefault(require("debug"));
8
+ const crypto_1 = __importDefault(require("@sockethub/crypto"));
9
+ /**
10
+ * Encapsulates the storing and fetching of credential objects.
11
+ */
12
+ class CredentialsStore {
13
+ /**
14
+ * @param parentId - The ID of the parent instance (eg. sockethub itself)
15
+ * @param sessionId - The ID of the session (socket.io connection)
16
+ * @param secret - The encryption secret (parent + session secrets)
17
+ * @param redisConfig - Connect info for redis
18
+ */
19
+ constructor(parentId, sessionId, secret, redisConfig) {
20
+ this.initialized = false;
21
+ this.uid = `sockethub:data-layer:credentials-store:${parentId}:${sessionId}`;
22
+ this.store = new secure_store_redis_1.default(this.uid, secret, { redis: redisConfig });
23
+ this.log = (0, debug_1.default)(this.uid);
24
+ }
25
+ async init() {
26
+ this.initialized = true;
27
+ await this.store.init();
28
+ }
29
+ /**
30
+ * Gets the credentials for a given actor ID
31
+ * @param actor
32
+ * @param credentialHash
33
+ */
34
+ async get(actor, credentialHash = undefined) {
35
+ this.log(`get credentials for ${actor}`);
36
+ if (!this.initialized) {
37
+ throw new Error('CredentialsStore not initialized');
38
+ }
39
+ const credentials = await this.store.get(actor);
40
+ if (!credentials) {
41
+ return undefined;
42
+ }
43
+ if (credentialHash) {
44
+ if (credentialHash !== crypto_1.default.objectHash(credentials.object)) {
45
+ throw new Error(`provided credentials do not match existing platform instance for actor ${actor}`);
46
+ }
47
+ }
48
+ return credentials;
49
+ }
50
+ /**
51
+ * Saves the credentials for a given actor ID
52
+ * @param actor
53
+ * @param creds
54
+ */
55
+ async save(actor, creds) {
56
+ if (!this.initialized) {
57
+ throw new Error('CredentialsStore not initialized');
58
+ }
59
+ await this.store.save(actor, creds);
60
+ this.log(`credentials encrypted and saved`);
61
+ }
62
+ }
63
+ exports.default = CredentialsStore;
64
+ //# sourceMappingURL=/credentials-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials-store.js","sourceRoot":"/","sources":["credentials-store.ts"],"names":[],"mappings":";;;;;AAAA,4EAA6C;AAC7C,kDAAsC;AAEtC,+DAAuC;AAGvC;;GAEG;AACH,MAAqB,gBAAgB;IAMnC;;;;;OAKG;IACH,YACE,QAAgB,EAChB,SAAiB,EACjB,MAAc,EACd,WAA8C;QAZtC,gBAAW,GAAG,KAAK,CAAC;QAc5B,IAAI,CAAC,GAAG,GAAG,0CAA0C,QAAQ,IAAI,SAAS,EAAE,CAAC;QAC7E,IAAI,CAAC,KAAK,GAAG,IAAI,4BAAW,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;QACvE,IAAI,CAAC,GAAG,GAAG,IAAA,eAAK,EAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,IAAI;QACR,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QACxB,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,GAAG,CAAC,KAAa,EAAE,iBAAyB,SAAS;QACzD,IAAI,CAAC,GAAG,CAAC,uBAAuB,KAAK,EAAE,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;SAAE;QAC/E,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAAE,OAAO,SAAS,CAAC;SAAE;QAEvC,IAAI,cAAc,EAAE;YAClB,IAAI,cAAc,KAAK,gBAAM,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE;gBAC5D,MAAM,IAAI,KAAK,CACb,0EAA0E,KAAK,EAAE,CAClF,CAAC;aACH;SACF;QACD,OAAO,WAAW,CAAC;IACrB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,IAAI,CAAC,KAAa,EAAE,KAAsB;QAC9C,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;SAAE;QAC/E,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC9C,CAAC;CACF;AA3DD,mCA2DC"}
@@ -0,0 +1,3 @@
1
+ export { default as CredentialsStore } from "./credentials-store";
2
+ export { default as JobQueue } from "./job-queue";
3
+ export * from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.JobQueue = exports.CredentialsStore = void 0;
21
+ var credentials_store_1 = require("./credentials-store");
22
+ Object.defineProperty(exports, "CredentialsStore", { enumerable: true, get: function () { return __importDefault(credentials_store_1).default; } });
23
+ var job_queue_1 = require("./job-queue");
24
+ Object.defineProperty(exports, "JobQueue", { enumerable: true, get: function () { return __importDefault(job_queue_1).default; } });
25
+ __exportStar(require("./types"), exports);
26
+ // export default class DataLayer {
27
+ // readonly uid: string;
28
+ // readonly jobQueue: JobQueue;
29
+ // readonly credentialStore: CredentialsStore;
30
+ //
31
+ // constructor(instanceId: string, sessionId: string, secret: string, redisConfig: RedisConfig) {
32
+ // this.uid = `sockethub:data-layer:job-queue:${instanceId}:${sessionId}`;
33
+ // this.jobQueue = new JobQueue(
34
+ // instanceId, sessionId, secret, redisConfig
35
+ // ),
36
+ // this.credentialStore = new CredentialsStore(
37
+ // instanceId, sessionId, secret, redisConfig
38
+ // );
39
+ // }
40
+ // }
41
+ //# sourceMappingURL=/index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,yDAAgE;AAAxD,sIAAA,OAAO,OAAoB;AACnC,yCAAgD;AAAxC,sHAAA,OAAO,OAAY;AAC3B,0CAAwB;AAExB,mCAAmC;AACnC,0BAA0B;AAC1B,iCAAiC;AACjC,gDAAgD;AAChD,EAAE;AACF,mGAAmG;AACnG,8EAA8E;AAC9E,oCAAoC;AACpC,mDAAmD;AACnD,SAAS;AACT,mDAAmD;AACnD,mDAAmD;AACnD,SAAS;AACT,MAAM;AACN,IAAI"}
@@ -0,0 +1,32 @@
1
+ /// <reference types="node" />
2
+ import { JobDataDecrypted, JobDataEncrypted, JobDecrypted, RedisConfig } from "./types";
3
+ import EventEmitter from "events";
4
+ import { IActivityStream } from "@sockethub/schemas";
5
+ interface JobHandler {
6
+ (job: JobDataDecrypted, done: CallableFunction): any;
7
+ }
8
+ export default class JobQueue extends EventEmitter {
9
+ readonly uid: string;
10
+ private readonly bull;
11
+ private readonly debug;
12
+ private readonly secret;
13
+ private handler;
14
+ private counter;
15
+ constructor(instanceId: string, sessionId: string, secret: string, redisConfig: RedisConfig);
16
+ add(socketId: string, msg: IActivityStream): Promise<JobDataEncrypted>;
17
+ initResultEvents(): void;
18
+ getJob(jobId: string): Promise<JobDecrypted>;
19
+ onJob(handler: JobHandler): void;
20
+ pause(): Promise<void>;
21
+ resume(): Promise<void>;
22
+ shutdown(): Promise<void>;
23
+ private createJob;
24
+ private jobHandler;
25
+ /**
26
+ * @param job
27
+ * @private
28
+ */
29
+ private decryptJobData;
30
+ private decryptActivityStream;
31
+ }
32
+ export {};
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const bull_1 = __importDefault(require("bull"));
7
+ const crypto_1 = __importDefault(require("@sockethub/crypto"));
8
+ const debug_1 = __importDefault(require("debug"));
9
+ const events_1 = __importDefault(require("events"));
10
+ class JobQueue extends events_1.default {
11
+ constructor(instanceId, sessionId, secret, redisConfig) {
12
+ super();
13
+ this.counter = 0;
14
+ this.bull = new bull_1.default(instanceId + sessionId, { redis: redisConfig });
15
+ this.uid = `sockethub:data-layer:job-queue:${instanceId}:${sessionId}`;
16
+ this.secret = secret;
17
+ this.debug = (0, debug_1.default)(this.uid);
18
+ this.debug('initialized');
19
+ }
20
+ async add(socketId, msg) {
21
+ const job = this.createJob(socketId, msg);
22
+ const isPaused = await this.bull.isPaused();
23
+ if (isPaused) {
24
+ this.bull.emit('failed', job, 'queue closed');
25
+ return undefined;
26
+ }
27
+ this.debug(`adding ${job.title} ${msg.type}`);
28
+ this.bull.add(job);
29
+ return job;
30
+ }
31
+ initResultEvents() {
32
+ this.bull.on('global:completed', async (jobId, result) => {
33
+ const r = result ? JSON.parse(result) : "";
34
+ const job = await this.getJob(jobId);
35
+ if (job) {
36
+ this.debug(`completed ${job.data.title} ${job.data.msg.type}`);
37
+ this.emit('global:completed', job.data, r);
38
+ await job.remove();
39
+ }
40
+ });
41
+ this.bull.on('global:error', async (jobId, result) => {
42
+ this.debug("unknown queue error", jobId, result);
43
+ });
44
+ this.bull.on('global:failed', async (jobId, result) => {
45
+ const job = await this.getJob(jobId);
46
+ if (job) {
47
+ this.debug(`failed ${job.data.title} ${job.data.msg.type}`);
48
+ this.emit('global:failed', job.data, result);
49
+ await job.remove();
50
+ }
51
+ });
52
+ this.bull.on('failed', (job, result) => {
53
+ // locally failed jobs (eg. due to paused queue)
54
+ const unencryptedJobData = {
55
+ title: job.title,
56
+ msg: this.decryptActivityStream(job.msg),
57
+ sessionId: job.sessionId
58
+ };
59
+ this.debug(`failed ${unencryptedJobData.title} ${unencryptedJobData.msg.type}`);
60
+ this.emit('global:failed', unencryptedJobData, result);
61
+ });
62
+ this.bull.on('completed', (job) => {
63
+ console.log("completed ", job);
64
+ });
65
+ }
66
+ async getJob(jobId) {
67
+ const job = await this.bull.getJob(jobId);
68
+ if (job) {
69
+ job.data = this.decryptJobData(job);
70
+ try {
71
+ delete job.data.msg.sessionSecret;
72
+ }
73
+ catch (e) {
74
+ // this property should never be exposed externally
75
+ }
76
+ }
77
+ return job;
78
+ }
79
+ onJob(handler) {
80
+ this.handler = handler;
81
+ this.bull.process(this.jobHandler.bind(this));
82
+ }
83
+ async pause() {
84
+ await this.bull.pause();
85
+ this.debug('paused');
86
+ }
87
+ async resume() {
88
+ await this.bull.resume();
89
+ this.debug('resumed');
90
+ }
91
+ async shutdown() {
92
+ this.debug('shutdown');
93
+ const isPaused = await this.bull.isPaused(true);
94
+ if (!isPaused) {
95
+ await this.bull.pause();
96
+ }
97
+ await this.bull.obliterate({ force: true });
98
+ await this.bull.removeAllListeners();
99
+ }
100
+ createJob(socketId, msg) {
101
+ const title = `${msg.context}-${(msg.id) ? msg.id : this.counter++}`;
102
+ return {
103
+ title: title,
104
+ sessionId: socketId,
105
+ msg: crypto_1.default.encrypt(msg, this.secret)
106
+ };
107
+ }
108
+ jobHandler(encryptedJob, done) {
109
+ const job = this.decryptJobData(encryptedJob);
110
+ this.debug(`handling ${job.title} ${job.msg.type}`);
111
+ this.handler(job, done);
112
+ }
113
+ /**
114
+ * @param job
115
+ * @private
116
+ */
117
+ decryptJobData(job) {
118
+ return {
119
+ title: job.data.title,
120
+ msg: this.decryptActivityStream(job.data.msg),
121
+ sessionId: job.data.sessionId
122
+ };
123
+ }
124
+ decryptActivityStream(msg) {
125
+ return crypto_1.default.decrypt(msg, this.secret);
126
+ }
127
+ }
128
+ exports.default = JobQueue;
129
+ //# sourceMappingURL=/job-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-queue.js","sourceRoot":"/","sources":["job-queue.ts"],"names":[],"mappings":";;;;;AAAA,gDAAyB;AACzB,+DAAuC;AAOvC,kDAAsC;AACtC,oDAAkC;AAOlC,MAAqB,QAAS,SAAQ,gBAAY;IAQhD,YAAY,UAAkB,EAAE,SAAiB,EAAE,MAAc,EAAE,WAAwB;QACzF,KAAK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G,EAAE,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;YAC7C,SAAS,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS;SAC9B,CAAC;IACJ,CAAC;IAEO,qBAAqB,CAAC,GAAW;QACvC,OAAO,gBAAM,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF;AAtID,2BAsIC"}
@@ -0,0 +1,3 @@
1
+ import SecureStore from 'secure-store-redis';
2
+ export declare type SessionStore = SecureStore;
3
+ export declare function getSessionStore(parentId: string, parentSecret: string, sessionId: string, sessionSecret: string): SessionStore;
package/dist/store.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getSessionStore = void 0;
7
+ const secure_store_redis_1 = __importDefault(require("secure-store-redis"));
8
+ const config_1 = __importDefault(require("../../server/src/config"));
9
+ function getSessionStore(parentId, parentSecret, sessionId, sessionSecret) {
10
+ return new secure_store_redis_1.default({
11
+ namespace: 'sockethub:' + parentId + ':session:' + sessionId + ':store',
12
+ secret: parentSecret + sessionSecret,
13
+ redis: config_1.default.get('redis')
14
+ });
15
+ }
16
+ exports.getSessionStore = getSessionStore;
17
+ //# sourceMappingURL=/store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"/","sources":["store.ts"],"names":[],"mappings":";;;;;;AAAA,4EAA6C;AAC7C,qEAA6C;AAI7C,SAAgB,eAAe,CAAC,QAAgB,EAAE,YAAoB,EACtC,SAAiB,EAAE,aAAqB;IACtE,OAAO,IAAI,4BAAW,CAAC;QACrB,SAAS,EAAE,YAAY,GAAG,QAAQ,GAAG,WAAW,GAAG,SAAS,GAAG,QAAQ;QACvE,MAAM,EAAE,YAAY,GAAG,aAAa;QACpC,KAAK,EAAE,gBAAM,CAAC,GAAG,CAAC,OAAO,CAAC;KAC3B,CAAC,CAAC;AACL,CAAC;AAPD,0CAOC"}
@@ -0,0 +1,29 @@
1
+ import { IActivityStream } from "@sockethub/schemas";
2
+ export declare type RedisConfigUrl = string;
3
+ export interface RedisConfigProps {
4
+ host: string;
5
+ port: string;
6
+ }
7
+ export declare type RedisConfig = RedisConfigProps | RedisConfigUrl;
8
+ export interface JobDataEncrypted {
9
+ title?: string;
10
+ msg: string;
11
+ sessionId: string;
12
+ }
13
+ export interface JobDataDecrypted {
14
+ title?: string;
15
+ msg: IActivityStream;
16
+ sessionId: string;
17
+ }
18
+ export interface JobEncrypted {
19
+ data: JobDataEncrypted;
20
+ remove?: {
21
+ (): void;
22
+ };
23
+ }
24
+ export interface JobDecrypted {
25
+ data: JobDataDecrypted;
26
+ remove?: {
27
+ (): void;
28
+ };
29
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=/types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@sockethub/data-layer",
3
+ "description": "Storing and RPC of data for Sockethub",
4
+ "version": "1.0.0-alpha.3",
5
+ "private": false,
6
+ "author": "Nick Jennings <nick@silverbucket.net>",
7
+ "license": "MIT",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "dist/",
12
+ "src/"
13
+ ],
14
+ "keywords": [
15
+ "sockethub",
16
+ "messaging",
17
+ "redis",
18
+ "data lyer",
19
+ "rpc",
20
+ "data store"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/sockethub/sockethub.git",
25
+ "directory": "packages/data-layer"
26
+ },
27
+ "homepage": "https://github.com/sockethub/sockethub/tree/master/packages/data-layer",
28
+ "dependencies": {
29
+ "@sockethub/crypto": "^1.0.0-alpha.3",
30
+ "@sockethub/schemas": "^3.0.0-alpha.3",
31
+ "bull": "^4.0.0",
32
+ "debug": "^4.3.1",
33
+ "secure-store-redis": "^1.4.7"
34
+ },
35
+ "scripts": {
36
+ "clean": "npx rimraf dist coverage",
37
+ "clean:deps": "npx rimraf node_modules",
38
+ "compliance": "yarn run lint && yarn run test && yarn run coverage",
39
+ "test": "c8 -x \"src/**/*.test.*\" mocha -r ts-node/register src/*.test.ts",
40
+ "coverage": "c8 check-coverage --statements 85 --branches 90 --functions 100 --lines 85",
41
+ "lint": "eslint \"**/*.ts\"",
42
+ "lint:fix": "eslint --fix \"**/*.ts\"",
43
+ "build": "tsc"
44
+ },
45
+ "engines": {
46
+ "node": ">= 14"
47
+ },
48
+ "devDependencies": {
49
+ "@types/chai": "4.3.3",
50
+ "@types/debug": "4.1.7",
51
+ "@types/eslint": "8.4.6",
52
+ "@types/mocha": "9.1.1",
53
+ "@types/node": "17.0.13",
54
+ "@types/proxyquire": "1.3.28",
55
+ "@types/sinon": "10.0.13",
56
+ "@typescript-eslint/parser": "5.37.0",
57
+ "c8": "7.12.0",
58
+ "chai": "4.3.6",
59
+ "eslint": "8.23.1",
60
+ "eslint-cli": "1.1.1",
61
+ "mocha": "10.0.0",
62
+ "proxyquire": "2.1.3",
63
+ "sinon": "14.0.0",
64
+ "ts-node": "10.9.1",
65
+ "typescript": "4.8.3"
66
+ },
67
+ "gitHead": "1fa39894aafb49dfea7a7425bdaf196325e81e5d"
68
+ }
@@ -0,0 +1,138 @@
1
+ import proxyquire from 'proxyquire';
2
+ import { expect } from 'chai';
3
+ import * as sinon from 'sinon';
4
+
5
+ proxyquire.noPreserveCache();
6
+ proxyquire.noCallThru();
7
+
8
+ describe('CredentialsStore', () => {
9
+ let credentialsStore, MockSecureStore, MockStoreGet, MockStoreSave, MockObjectHash;
10
+ beforeEach(() => {
11
+ MockStoreGet = sinon.stub().callsArgWith(1, undefined, 'credential foo');
12
+ MockStoreSave = sinon.stub().callsArgWith(2, undefined);
13
+ MockObjectHash = sinon.stub();
14
+ MockSecureStore = sinon.stub().returns({
15
+ get: MockStoreGet,
16
+ save: MockStoreSave,
17
+ });
18
+ const StoreMod = proxyquire('./credentials-store', {
19
+ 'secure-store-redis': MockSecureStore,
20
+ '@sockethub/crypto': {
21
+ objectHash: MockObjectHash
22
+ }
23
+ });
24
+ const CredentialsStore = StoreMod.default;
25
+ credentialsStore = new CredentialsStore('a parent id', 'a session id', 'a secret', 'redis config');
26
+ });
27
+
28
+ it('returns a valid CredentialsStore object', () => {
29
+ sinon.assert.calledOnce(MockSecureStore);
30
+ sinon.assert.calledWith(MockSecureStore, {
31
+ namespace: 'sockethub:data-layer:credentials-store:a parent id:a session id',
32
+ secret: 'a secret',
33
+ redis: 'redis config'
34
+ });
35
+ expect(typeof credentialsStore).to.equal('object');
36
+ expect(credentialsStore.uid).to.equal(`sockethub:data-layer:credentials-store:a parent id:a session id`);
37
+ expect(typeof credentialsStore.get).to.equal('function');
38
+ expect(typeof credentialsStore.save).to.equal('function');
39
+ });
40
+
41
+ describe('get', () => {
42
+ it('handles correct params', async () => {
43
+ let res = await credentialsStore.get('an actor');
44
+ sinon.assert.calledOnce(MockStoreGet);
45
+ sinon.assert.calledWith(MockStoreGet, 'an actor');
46
+ sinon.assert.notCalled(MockObjectHash);
47
+ sinon.assert.notCalled(MockStoreSave);
48
+ expect(res).to.equal('credential foo');
49
+ });
50
+
51
+ it('handles no credentials found', async () => {
52
+ MockStoreGet.callsArgWith(1, undefined, undefined);
53
+ let res = await credentialsStore.get('an non-existent actor');
54
+ sinon.assert.calledOnce(MockStoreGet);
55
+ sinon.assert.calledWith(MockStoreGet, 'an non-existent actor');
56
+ sinon.assert.notCalled(MockObjectHash);
57
+ sinon.assert.notCalled(MockStoreSave);
58
+ expect(res).to.be.undefined;
59
+ });
60
+
61
+ it('handles an unexpected error', async () => {
62
+ MockStoreGet.callsArgWith(1, 'sumting bad happen', undefined);
63
+ let res;
64
+ try {
65
+ res = await credentialsStore.get('a problem actor');
66
+ throw new Error('should not reach this spot');
67
+ } catch (err) {
68
+ expect(err).to.equal('sumting bad happen');
69
+ }
70
+ sinon.assert.calledOnce(MockStoreGet);
71
+ sinon.assert.calledWith(MockStoreGet, 'a problem actor');
72
+ sinon.assert.notCalled(MockObjectHash);
73
+ sinon.assert.notCalled(MockStoreSave);
74
+ expect(res).to.be.undefined;
75
+ });
76
+
77
+ it('validates credentialsHash when provided', async () => {
78
+ MockObjectHash.returns('a credentialHash string');
79
+ MockStoreGet.callsArgWith(1, undefined, {
80
+ object: 'a credential'
81
+ });
82
+ let res = await credentialsStore.get('an actor', 'a credentialHash string');
83
+ sinon.assert.calledOnce(MockStoreGet);
84
+ sinon.assert.calledWith(MockStoreGet, 'an actor');
85
+ sinon.assert.calledOnce(MockObjectHash);
86
+ sinon.assert.calledWith(MockObjectHash, 'a credential');
87
+ sinon.assert.notCalled(MockStoreSave);
88
+ expect(res).to.eql({object: 'a credential'});
89
+ });
90
+
91
+ it('invalidates credentialsHash when provided', async () => {
92
+ MockObjectHash.returns('the original credentialHash string');
93
+ MockStoreGet.callsArgWith(1, undefined, {
94
+ object: 'a credential'
95
+ });
96
+ let res;
97
+ try {
98
+ res = await credentialsStore.get('an actor', 'a different credentialHash string');
99
+ throw new Error('should not reach this spot');
100
+ } catch (err) {
101
+ expect(err).to.equal('provided credentials do not match existing platform instance for actor an actor');
102
+ }
103
+ sinon.assert.calledOnce(MockStoreGet);
104
+ sinon.assert.calledWith(MockStoreGet, 'an actor');
105
+ sinon.assert.calledOnce(MockObjectHash);
106
+ sinon.assert.calledWith(MockObjectHash, 'a credential');
107
+ sinon.assert.notCalled(MockStoreSave);
108
+ expect(res).to.be.undefined;
109
+ });
110
+ });
111
+
112
+ describe('save', () => {
113
+ it('handles success', (done) => {
114
+ const creds = {foo:'bar'};
115
+ credentialsStore.save('an actor', creds, (err) => {
116
+ sinon.assert.calledOnce(MockStoreSave);
117
+ sinon.assert.calledWith(MockStoreSave, 'an actor', creds);
118
+ sinon.assert.notCalled(MockObjectHash);
119
+ sinon.assert.notCalled(MockStoreGet);
120
+ expect(err).to.be.undefined;
121
+ done();
122
+ });
123
+ });
124
+
125
+ it('handles failure', (done) => {
126
+ const creds = {foo:'bar'};
127
+ MockStoreSave.callsArgWith(2, 'an error');
128
+ credentialsStore.save('an actor', creds, (err) => {
129
+ sinon.assert.calledOnce(MockStoreSave);
130
+ sinon.assert.calledWith(MockStoreSave, 'an actor', creds);
131
+ sinon.assert.notCalled(MockObjectHash);
132
+ sinon.assert.notCalled(MockStoreGet);
133
+ expect(err).to.equal('an error');
134
+ done();
135
+ });
136
+ });
137
+ });
138
+ });
@@ -0,0 +1,76 @@
1
+ import SecureStore from 'secure-store-redis';
2
+ import debug, {Debugger} from 'debug';
3
+ import {IActivityStream, CallbackInterface} from "@sockethub/schemas";
4
+ import crypto from "@sockethub/crypto";
5
+ import {RedisConfigProps, RedisConfigUrl} from "./types";
6
+
7
+ /**
8
+ * Encapsulates the storing and fetching of credential objects.
9
+ */
10
+ export default class CredentialsStore {
11
+ readonly uid: string;
12
+ private readonly store: SecureStore;
13
+ private readonly log: Debugger;
14
+
15
+ /**
16
+ * @param parentId - The ID of the parent instance (eg. sockethub itself)
17
+ * @param sessionId - The ID of the session (socket.io connection)
18
+ * @param secret - The encryption secret (parent + session secrets)
19
+ * @param redisConfig - Connect info for redis
20
+ */
21
+ constructor(
22
+ parentId: string,
23
+ sessionId: string,
24
+ secret: string,
25
+ redisConfig: RedisConfigProps | RedisConfigUrl
26
+ ) {
27
+ this.uid = `sockethub:data-layer:credentials-store:${parentId}:${sessionId}`;
28
+ this.store = new SecureStore({
29
+ namespace: this.uid,
30
+ secret: secret,
31
+ redis: redisConfig
32
+ });
33
+ this.log = debug(this.uid);
34
+ }
35
+
36
+ /**
37
+ * Gets the credentials for a given actor ID
38
+ * @param actor
39
+ * @param credentialHash
40
+ */
41
+ async get(actor: string, credentialHash: string): Promise<IActivityStream> {
42
+ this.log(`get credentials for ${actor}`);
43
+ return new Promise((resolve, reject) => {
44
+ this.store.get(actor, (err, credentials) => {
45
+ if (err) { return reject(err.toString()); }
46
+ if (!credentials) { return resolve(undefined); }
47
+
48
+ if (credentialHash) {
49
+ if (credentialHash !== crypto.objectHash(credentials.object)) {
50
+ return reject(
51
+ `provided credentials do not match existing platform instance for actor ${actor}`);
52
+ }
53
+ }
54
+ return resolve(credentials);
55
+ });
56
+ });
57
+ }
58
+
59
+ /**
60
+ * Saves the credentials for a given actor ID
61
+ * @param actor
62
+ * @param creds
63
+ * @param done
64
+ */
65
+ save(actor: string, creds: IActivityStream, done: CallbackInterface): void {
66
+ this.store.save(actor, creds, (err) => {
67
+ if (err) {
68
+ this.log('error saving credentials to store ' + err);
69
+ return done(err);
70
+ } else {
71
+ this.log(`credentials encrypted and saved`);
72
+ return done();
73
+ }
74
+ });
75
+ }
76
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export {default as CredentialsStore} from "./credentials-store";
2
+ export {default as JobQueue} from "./job-queue";
3
+ export * from "./types";
@@ -0,0 +1,252 @@
1
+ import proxyquire from 'proxyquire';
2
+ import { expect } from 'chai';
3
+ import * as sinon from 'sinon';
4
+
5
+ proxyquire.noPreserveCache();
6
+ proxyquire.noCallThru();
7
+
8
+ describe('JobQueue', () => {
9
+ let jobQueue, MockBull, bullMocks, cryptoMocks, sandbox;
10
+
11
+ beforeEach(() => {
12
+ sandbox = sinon.createSandbox();
13
+ cryptoMocks = {
14
+ objectHash: sandbox.stub(),
15
+ decrypt: sandbox.stub(),
16
+ encrypt: sandbox.stub(),
17
+ hash: sandbox.stub(),
18
+ };
19
+ bullMocks = {
20
+ add: sandbox.stub(),
21
+ getJob: sandbox.stub(),
22
+ process: sandbox.stub(),
23
+ removeAllListeners: sandbox.stub(),
24
+ pause: sandbox.stub(),
25
+ resume: sandbox.stub(),
26
+ isPaused: sandbox.stub(),
27
+ obliterate: sandbox.stub(),
28
+ emit: sandbox.stub(),
29
+ on: sandbox.stub().callsArgWith(1, 'a job id', 'a result string')
30
+ };
31
+ MockBull = sandbox.stub().returns(bullMocks);
32
+ const JobQueueMod = proxyquire('./job-queue', {
33
+ 'bull': MockBull,
34
+ '@sockethub/crypto': cryptoMocks
35
+ });
36
+ const JobQueue = JobQueueMod.default;
37
+ jobQueue = new JobQueue('a parent id', 'a session id', 'a secret', 'redis config');
38
+ jobQueue.emit = sandbox.stub();
39
+ });
40
+
41
+ afterEach(() => {
42
+ sinon.restore();
43
+ sandbox.reset();
44
+ });
45
+
46
+ it('returns a valid JobQueue object', () => {
47
+ sinon.assert.calledOnce(MockBull);
48
+ sinon.assert.calledWith(MockBull,
49
+ 'a parent ida session id', { redis: 'redis config' }
50
+ );
51
+ expect(typeof jobQueue).to.equal('object');
52
+ expect(jobQueue.uid).to.equal(`sockethub:data-layer:job-queue:a parent id:a session id`);
53
+ expect(typeof jobQueue.add).to.equal('function');
54
+ expect(typeof jobQueue.getJob).to.equal('function');
55
+ expect(typeof jobQueue.onJob).to.equal('function');
56
+ expect(typeof jobQueue.shutdown).to.equal('function');
57
+ });
58
+
59
+ describe('initResultEvents', () => {
60
+ it('registers handlers when called', () => {
61
+ bullMocks.on.reset();
62
+ jobQueue.initResultEvents();
63
+ expect(bullMocks.on.callCount).to.eql(4);
64
+ sinon.assert.calledWith(bullMocks.on, 'global:completed');
65
+ sinon.assert.calledWith(bullMocks.on, 'global:error');
66
+ sinon.assert.calledWith(bullMocks.on, 'global:failed');
67
+ sinon.assert.calledWith(bullMocks.on, 'failed');
68
+ });
69
+ });
70
+
71
+ describe('createJob', () => {
72
+ it('returns expected job format', () => {
73
+ cryptoMocks.encrypt.returns('an encrypted message');
74
+ const job = jobQueue.createJob('a socket id', {
75
+ context: 'some context',
76
+ id: 'an identifier'
77
+ });
78
+ expect(job).to.eql({
79
+ title: 'some context-an identifier',
80
+ msg: 'an encrypted message',
81
+ sessionId: 'a socket id'
82
+ })
83
+ });
84
+
85
+ it('uses counter when no id provided', () => {
86
+ cryptoMocks.encrypt.returns('an encrypted message');
87
+ let job = jobQueue.createJob('a socket id', {
88
+ context: 'some context'
89
+ });
90
+ expect(job).to.eql({
91
+ title: 'some context-0',
92
+ msg: 'an encrypted message',
93
+ sessionId: 'a socket id'
94
+ });
95
+ job = jobQueue.createJob('a socket id', {
96
+ context: 'some context'
97
+ });
98
+ expect(job).to.eql({
99
+ title: 'some context-1',
100
+ msg: 'an encrypted message',
101
+ sessionId: 'a socket id'
102
+ });
103
+ })
104
+ });
105
+
106
+ describe('add', () => {
107
+ it('stores encrypted job', async () => {
108
+ cryptoMocks.encrypt.returns('encrypted foo')
109
+ bullMocks.isPaused.returns(false);
110
+ const resultJob = {title: 'a platform-an identifier', sessionId: 'a socket id', msg: 'encrypted foo'}
111
+ const res = await jobQueue.add(
112
+ 'a socket id', {context: 'a platform', id: 'an identifier'}
113
+ );
114
+ sinon.assert.calledOnce(bullMocks.isPaused);
115
+ sinon.assert.notCalled(bullMocks.emit);
116
+ sinon.assert.calledOnceWithExactly(bullMocks.add,
117
+ resultJob);
118
+ expect(res).to.eql(resultJob);
119
+ });
120
+ it('fails job if queue paused', async () => {
121
+ cryptoMocks.encrypt.returns('encrypted foo')
122
+ bullMocks.isPaused.returns(true);
123
+ const resultJob = {title: 'a platform-an identifier', sessionId: 'a socket id', msg: 'encrypted foo'}
124
+ const res = await jobQueue.add(
125
+ 'a socket id', {context: 'a platform', id: 'an identifier'}
126
+ );
127
+ sinon.assert.calledOnce(bullMocks.isPaused);
128
+ sinon.assert.calledOnceWithExactly(bullMocks.emit, 'failed', resultJob, 'queue closed');
129
+ sinon.assert.notCalled(bullMocks.add);
130
+ expect(res).to.be.undefined;
131
+ });
132
+ });
133
+
134
+ describe('getJob', () => {
135
+ const encryptedJob = {
136
+ data: {
137
+ title: 'a title',
138
+ msg: 'an encrypted msg',
139
+ sessionId: 'a socket id'
140
+ }
141
+ };
142
+
143
+ it('handles fetching a valid job', async () => {
144
+ bullMocks.getJob.returns(encryptedJob);
145
+ cryptoMocks.decrypt.returns('an unencrypted message')
146
+ const job = await jobQueue.getJob('a valid job');
147
+ sinon.assert.calledOnceWithExactly(bullMocks.getJob, 'a valid job');
148
+ encryptedJob.data.msg = 'an unencrypted message';
149
+ expect(job).to.eql(encryptedJob);
150
+ });
151
+
152
+ it('handles fetching an invalid job', async () => {
153
+ bullMocks.getJob.returns(undefined);
154
+ const job = await jobQueue.getJob('an invalid job');
155
+ expect(job).to.eql(undefined);
156
+ sinon.assert.calledOnceWithExactly(bullMocks.getJob, 'an invalid job');
157
+ sinon.assert.notCalled(cryptoMocks.decrypt)
158
+ });
159
+
160
+ it('removes sessionSecret', async () => {
161
+ bullMocks.getJob.returns(encryptedJob);
162
+ cryptoMocks.decrypt.returns({
163
+ foo:'bar',
164
+ sessionSecret: 'yarg'
165
+ })
166
+ const job = await jobQueue.getJob('a valid job');
167
+ sinon.assert.calledOnceWithExactly(bullMocks.getJob, 'a valid job');
168
+ // @ts-ignore
169
+ encryptedJob.data.msg = {
170
+ foo:'bar'
171
+ }
172
+ expect(job).to.eql(encryptedJob);
173
+ });
174
+ });
175
+
176
+ describe('onJob', () => {
177
+ it('queues the handler', () => {
178
+ jobQueue.onJob((job, done) => {
179
+ throw new Error('This handler should never be called');
180
+ });
181
+ sinon.assert.calledOnce(bullMocks.process);
182
+ });
183
+ });
184
+
185
+ it('pause', async () => {
186
+ await jobQueue.pause();
187
+ sinon.assert.calledOnce(bullMocks.pause)
188
+ });
189
+
190
+ it('resume', async () => {
191
+ await jobQueue.resume();
192
+ sinon.assert.calledOnce(bullMocks.resume)
193
+ });
194
+
195
+ describe('shutdown', () => {
196
+ it('is sure to pause when not already paused', async () => {
197
+ bullMocks.isPaused.returns(false)
198
+ await jobQueue.shutdown()
199
+ sinon.assert.calledOnce(bullMocks.isPaused);
200
+ sinon.assert.calledOnce(bullMocks.pause);
201
+ sinon.assert.calledOnce(bullMocks.removeAllListeners);
202
+ sinon.assert.calledOnce(bullMocks.obliterate);
203
+ });
204
+ it('skips pausing when already paused', async () => {
205
+ bullMocks.isPaused.returns(true)
206
+ await jobQueue.shutdown()
207
+ sinon.assert.calledOnce(bullMocks.isPaused);
208
+ sinon.assert.notCalled(bullMocks.pause);
209
+ sinon.assert.calledOnce(bullMocks.removeAllListeners);
210
+ sinon.assert.calledOnce(bullMocks.obliterate);
211
+ });
212
+ });
213
+
214
+ describe('jobHandler', () => {
215
+ it('calls handler as expected', (done) => {
216
+ cryptoMocks.decrypt.returns('an unencrypted message');
217
+ const encryptedJob = {
218
+ data: {
219
+ title: 'a title',
220
+ msg: 'an encrypted message',
221
+ sessionId: 'a socket id'
222
+ }
223
+ };
224
+ jobQueue.onJob((job, cb) => {
225
+ const decryptedData = encryptedJob.data;
226
+ decryptedData.msg = 'an unencrypted message'
227
+ expect(job).to.eql(decryptedData);
228
+ cb();
229
+ });
230
+ sinon.assert.calledOnce(bullMocks.process);
231
+ jobQueue.jobHandler(encryptedJob, done);
232
+ });
233
+ });
234
+
235
+ describe("decryptJobData", () => {
236
+ it("decrypts and returns expected object", () => {
237
+ cryptoMocks.decrypt.returnsArg(0);
238
+ const jobData = {data:{title:"foo", msg:'encryptedjobdata', sessionId:'foobar'}};
239
+ const secret = 'secretstring';
240
+ expect(jobQueue.decryptJobData(jobData, secret)).to.be.eql(jobData.data);
241
+ });
242
+ });
243
+
244
+ describe("decryptActivityStream", () => {
245
+ it("decrypts and returns expected object", () => {
246
+ cryptoMocks.decrypt.returnsArg(0);
247
+ const jobData = 'encryptedjobdata';
248
+ const secret = 'secretstring';
249
+ expect(jobQueue.decryptActivityStream(jobData, secret)).to.be.eql(jobData);
250
+ });
251
+ });
252
+ });
@@ -0,0 +1,148 @@
1
+ import Queue from 'bull';
2
+ import crypto from '@sockethub/crypto';
3
+ import {
4
+ JobDataDecrypted,
5
+ JobDataEncrypted, JobDecrypted,
6
+ JobEncrypted,
7
+ RedisConfig
8
+ } from "./types";
9
+ import debug, {Debugger} from 'debug';
10
+ import EventEmitter from "events";
11
+ import {IActivityStream} from "@sockethub/schemas";
12
+
13
+ interface JobHandler {
14
+ (job: JobDataDecrypted, done: CallableFunction)
15
+ }
16
+
17
+ export default class JobQueue extends EventEmitter {
18
+ readonly uid: string;
19
+ private readonly bull: Queue;
20
+ private readonly debug: Debugger;
21
+ private readonly secret: string;
22
+ private handler: JobHandler;
23
+ private counter = 0;
24
+
25
+ constructor(instanceId: string, sessionId: string, secret: string, redisConfig: RedisConfig) {
26
+ super();
27
+ this.bull = new Queue(instanceId + sessionId, { redis: redisConfig });
28
+ this.uid = `sockethub:data-layer:job-queue:${instanceId}:${sessionId}`;
29
+ this.secret = secret;
30
+ this.debug = debug(this.uid);
31
+
32
+ this.debug('initialized');
33
+ }
34
+
35
+ async add(socketId: string, msg: IActivityStream): Promise<JobDataEncrypted> {
36
+ const job = this.createJob(socketId, msg);
37
+ const isPaused = await this.bull.isPaused();
38
+ if (isPaused) {
39
+ this.bull.emit('failed', job, 'queue closed');
40
+ return undefined;
41
+ }
42
+ this.debug(`adding ${job.title} ${msg.type}`);
43
+ this.bull.add(job);
44
+ return job;
45
+ }
46
+
47
+ initResultEvents() {
48
+ this.bull.on('global:completed', async (jobId: string, result: string) => {
49
+ const r = result ? JSON.parse(result) : "";
50
+ const job = await this.getJob(jobId);
51
+ if (job) {
52
+ this.debug(`completed ${job.data.title} ${job.data.msg.type}`);
53
+ this.emit('global:completed', job.data, r);
54
+ await job.remove();
55
+ }
56
+ });
57
+ this.bull.on('global:error', async (jobId: string, result: string) => {
58
+ this.debug("unknown queue error", jobId, result);
59
+ });
60
+ this.bull.on('global:failed', async (jobId, result: string) => {
61
+ const job = await this.getJob(jobId);
62
+ if (job) {
63
+ this.debug(`failed ${job.data.title} ${job.data.msg.type}`);
64
+ this.emit('global:failed', job.data, result);
65
+ await job.remove();
66
+ }
67
+ });
68
+ this.bull.on('failed', (job: JobDataEncrypted, result: string) => {
69
+ // locally failed jobs (eg. due to paused queue)
70
+ const unencryptedJobData: JobDataDecrypted = {
71
+ title: job.title,
72
+ msg: this.decryptActivityStream(job.msg),
73
+ sessionId: job.sessionId
74
+ };
75
+ this.debug(`failed ${unencryptedJobData.title} ${unencryptedJobData.msg.type}`);
76
+ this.emit('global:failed', unencryptedJobData, result);
77
+ });
78
+ }
79
+
80
+ async getJob(jobId: string): Promise<JobDecrypted> {
81
+ const job = await this.bull.getJob(jobId);
82
+ if (job) {
83
+ job.data = this.decryptJobData(job);
84
+ try {
85
+ delete job.data.msg.sessionSecret;
86
+ } catch (e) {
87
+ // this property should never be exposed externally
88
+ }
89
+ }
90
+ return job;
91
+ }
92
+
93
+ onJob(handler: JobHandler): void {
94
+ this.handler = handler;
95
+ this.bull.process(this.jobHandler.bind(this));
96
+ }
97
+
98
+ async pause() {
99
+ await this.bull.pause();
100
+ this.debug('paused');
101
+ }
102
+
103
+ async resume() {
104
+ await this.bull.resume();
105
+ this.debug('resumed');
106
+ }
107
+
108
+ async shutdown() {
109
+ this.debug('shutdown');
110
+ const isPaused = await this.bull.isPaused(true);
111
+ if (!isPaused) {
112
+ await this.bull.pause();
113
+ }
114
+ await this.bull.obliterate({ force: true });
115
+ await this.bull.removeAllListeners();
116
+ }
117
+
118
+ private createJob(socketId: string, msg): JobDataEncrypted {
119
+ const title = `${msg.context}-${(msg.id) ? msg.id : this.counter++}`;
120
+ return {
121
+ title: title,
122
+ sessionId: socketId,
123
+ msg: crypto.encrypt(msg, this.secret)
124
+ };
125
+ }
126
+
127
+ private jobHandler(encryptedJob: JobEncrypted, done: CallableFunction): void {
128
+ const job = this.decryptJobData(encryptedJob);
129
+ this.debug(`handling ${job.title} ${job.msg.type}`);
130
+ this.handler(job, done);
131
+ }
132
+
133
+ /**
134
+ * @param job
135
+ * @private
136
+ */
137
+ private decryptJobData(job: JobEncrypted): JobDataDecrypted {
138
+ return {
139
+ title: job.data.title,
140
+ msg: this.decryptActivityStream(job.data.msg),
141
+ sessionId: job.data.sessionId
142
+ };
143
+ }
144
+
145
+ private decryptActivityStream(msg: string): IActivityStream {
146
+ return crypto.decrypt(msg, this.secret);
147
+ }
148
+ }
package/src/types.ts ADDED
@@ -0,0 +1,37 @@
1
+ import {IActivityStream} from "@sockethub/schemas";
2
+
3
+ export type RedisConfigUrl = string;
4
+
5
+ export interface RedisConfigProps {
6
+ host: string,
7
+ port: string
8
+ }
9
+
10
+ export type RedisConfig = RedisConfigProps | RedisConfigUrl;
11
+
12
+ export interface JobDataEncrypted {
13
+ title?: string;
14
+ msg: string;
15
+ sessionId: string;
16
+ }
17
+
18
+ export interface JobDataDecrypted {
19
+ title?: string;
20
+ msg: IActivityStream;
21
+ sessionId: string;
22
+ }
23
+
24
+ export interface JobEncrypted {
25
+ data: JobDataEncrypted,
26
+ remove?: {
27
+ (): void;
28
+ };
29
+ }
30
+
31
+ export interface JobDecrypted {
32
+ data: JobDataDecrypted,
33
+ remove?: {
34
+ (): void;
35
+ };
36
+ }
37
+