prostgles-server 4.0.57 → 4.0.59

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 (221) hide show
  1. package/dist/DboBuilder/getColumns.d.ts.map +1 -1
  2. package/dist/DboBuilder/getColumns.js +1 -13
  3. package/dist/DboBuilder/getColumns.js.map +1 -1
  4. package/dist/DboBuilder/runSQL.js +2 -2
  5. package/dist/DboBuilder/runSQL.js.map +1 -1
  6. package/dist/Prostgles.d.ts.map +1 -1
  7. package/dist/PubSubManager/PubSubManager.d.ts +1 -1
  8. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -1
  9. package/dist/PubSubManager/PubSubManager.js +14 -1
  10. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  11. package/lib/DboBuilder/getColumns.ts +1 -18
  12. package/lib/DboBuilder/runSQL.ts +2 -2
  13. package/lib/Prostgles.ts +3 -3
  14. package/lib/PubSubManager/PubSubManager.ts +14 -1
  15. package/package.json +2 -2
  16. package/tests/client/PID.txt +1 -1
  17. package/tests/client/package.json +2 -2
  18. package/tests/client/tsconfig.json +2 -1
  19. package/tests/isomorphic_queries.ts +11 -9
  20. package/tests/server/DBoGenerated.d.ts +1 -1
  21. package/tests/server/dboTypeCheck.ts +3 -3
  22. package/tests/server/index.ts +7 -6
  23. package/tests/server/package-lock.json +1 -1
  24. package/tests/server/package.json +3 -3
  25. package/tests/server/publishTypeCheck.ts +1 -1
  26. package/tests/server/tsconfig.json +3 -2
  27. package/tests/test.sh +2 -0
  28. package/dist/FileManager.d.ts +0 -143
  29. package/dist/FileManager.d.ts.map +0 -1
  30. package/dist/FileManager.js +0 -646
  31. package/dist/FileManager.js.map +0 -1
  32. package/dist/TableConfig.d.ts +0 -267
  33. package/dist/TableConfig.d.ts.map +0 -1
  34. package/dist/TableConfig.js +0 -463
  35. package/dist/TableConfig.js.map +0 -1
  36. package/dist/validation.d.ts +0 -126
  37. package/dist/validation.d.ts.map +0 -1
  38. package/dist/validation.js +0 -405
  39. package/dist/validation.js.map +0 -1
  40. package/lib/AuthHandler.d.ts +0 -187
  41. package/lib/AuthHandler.d.ts.map +0 -1
  42. package/lib/AuthHandler.js +0 -478
  43. package/lib/DBEventsManager.d.ts +0 -38
  44. package/lib/DBEventsManager.d.ts.map +0 -1
  45. package/lib/DBEventsManager.js +0 -140
  46. package/lib/DBSchemaBuilder.d.ts +0 -13
  47. package/lib/DBSchemaBuilder.d.ts.map +0 -1
  48. package/lib/DBSchemaBuilder.js +0 -145
  49. package/lib/DboBuilder/QueryBuilder/Functions.d.ts +0 -64
  50. package/lib/DboBuilder/QueryBuilder/Functions.d.ts.map +0 -1
  51. package/lib/DboBuilder/QueryBuilder/Functions.js +0 -984
  52. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts +0 -73
  53. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +0 -1
  54. package/lib/DboBuilder/QueryBuilder/QueryBuilder.js +0 -335
  55. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts +0 -8
  56. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts.map +0 -1
  57. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.js +0 -227
  58. package/lib/DboBuilder/TableHandler.d.ts +0 -37
  59. package/lib/DboBuilder/TableHandler.d.ts.map +0 -1
  60. package/lib/DboBuilder/TableHandler.js +0 -213
  61. package/lib/DboBuilder/ViewHandler.d.ts +0 -119
  62. package/lib/DboBuilder/ViewHandler.d.ts.map +0 -1
  63. package/lib/DboBuilder/ViewHandler.js +0 -1023
  64. package/lib/DboBuilder/delete.d.ts +0 -6
  65. package/lib/DboBuilder/delete.d.ts.map +0 -1
  66. package/lib/DboBuilder/delete.js +0 -128
  67. package/lib/DboBuilder/find.d.ts +0 -8
  68. package/lib/DboBuilder/find.d.ts.map +0 -1
  69. package/lib/DboBuilder/find.js +0 -91
  70. package/lib/DboBuilder/getColumns.d.ts +0 -12
  71. package/lib/DboBuilder/getColumns.d.ts.map +0 -1
  72. package/lib/DboBuilder/getColumns.js +0 -92
  73. package/lib/DboBuilder/getCondition.d.ts +0 -22
  74. package/lib/DboBuilder/getCondition.d.ts.map +0 -1
  75. package/lib/DboBuilder/getCondition.js +0 -236
  76. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts +0 -20
  77. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts.map +0 -1
  78. package/lib/DboBuilder/getSubscribeRelatedTables.js +0 -152
  79. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts +0 -3
  80. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts.map +0 -1
  81. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.js +0 -207
  82. package/lib/DboBuilder/insert.d.ts +0 -6
  83. package/lib/DboBuilder/insert.d.ts.map +0 -1
  84. package/lib/DboBuilder/insert.js +0 -180
  85. package/lib/DboBuilder/insertDataParse.d.ts +0 -12
  86. package/lib/DboBuilder/insertDataParse.d.ts.map +0 -1
  87. package/lib/DboBuilder/insertDataParse.js +0 -253
  88. package/lib/DboBuilder/parseUpdateRules.d.ts +0 -18
  89. package/lib/DboBuilder/parseUpdateRules.d.ts.map +0 -1
  90. package/lib/DboBuilder/parseUpdateRules.js +0 -123
  91. package/lib/DboBuilder/runSQL.d.ts +0 -7
  92. package/lib/DboBuilder/runSQL.d.ts.map +0 -1
  93. package/lib/DboBuilder/runSQL.js +0 -135
  94. package/lib/DboBuilder/subscribe.d.ts +0 -20
  95. package/lib/DboBuilder/subscribe.d.ts.map +0 -1
  96. package/lib/DboBuilder/subscribe.js +0 -90
  97. package/lib/DboBuilder/update.d.ts +0 -6
  98. package/lib/DboBuilder/update.d.ts.map +0 -1
  99. package/lib/DboBuilder/update.js +0 -151
  100. package/lib/DboBuilder/uploadFile.d.ts +0 -7
  101. package/lib/DboBuilder/uploadFile.d.ts.map +0 -1
  102. package/lib/DboBuilder/uploadFile.js +0 -53
  103. package/lib/DboBuilder.d.ts +0 -306
  104. package/lib/DboBuilder.d.ts.map +0 -1
  105. package/lib/DboBuilder.js +0 -745
  106. package/lib/Event_Trigger_Tags.d.ts +0 -4
  107. package/lib/Event_Trigger_Tags.d.ts.map +0 -1
  108. package/lib/Event_Trigger_Tags.js +0 -116
  109. package/lib/FileManager/FileManager.d.ts +0 -135
  110. package/lib/FileManager/FileManager.d.ts.map +0 -1
  111. package/lib/FileManager/FileManager.js +0 -303
  112. package/lib/FileManager/initFileManager.d.ts +0 -4
  113. package/lib/FileManager/initFileManager.d.ts.map +0 -1
  114. package/lib/FileManager/initFileManager.js +0 -231
  115. package/lib/FileManager/parseFile.d.ts +0 -15
  116. package/lib/FileManager/parseFile.d.ts.map +0 -1
  117. package/lib/FileManager/parseFile.js +0 -58
  118. package/lib/FileManager/upload.d.ts +0 -6
  119. package/lib/FileManager/upload.d.ts.map +0 -1
  120. package/lib/FileManager/upload.js +0 -98
  121. package/lib/FileManager/uploadStream.d.ts +0 -5
  122. package/lib/FileManager/uploadStream.d.ts.map +0 -1
  123. package/lib/FileManager/uploadStream.js +0 -92
  124. package/lib/Filtering.d.ts +0 -15
  125. package/lib/Filtering.d.ts.map +0 -1
  126. package/lib/Filtering.js +0 -336
  127. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts +0 -4
  128. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts.map +0 -1
  129. package/lib/JSONBValidation/validate_jsonb_schema_sql.js +0 -500
  130. package/lib/JSONBValidation/validation.d.ts +0 -9
  131. package/lib/JSONBValidation/validation.d.ts.map +0 -1
  132. package/lib/JSONBValidation/validation.js +0 -131
  133. package/lib/PostgresNotifListenManager.d.ts +0 -28
  134. package/lib/PostgresNotifListenManager.d.ts.map +0 -1
  135. package/lib/PostgresNotifListenManager.js +0 -134
  136. package/lib/Prostgles.d.ts +0 -289
  137. package/lib/Prostgles.d.ts.map +0 -1
  138. package/lib/Prostgles.js +0 -685
  139. package/lib/PubSubManager/PubSubManager.d.ts +0 -175
  140. package/lib/PubSubManager/PubSubManager.d.ts.map +0 -1
  141. package/lib/PubSubManager/PubSubManager.js +0 -452
  142. package/lib/PubSubManager/addSub.d.ts +0 -8
  143. package/lib/PubSubManager/addSub.d.ts.map +0 -1
  144. package/lib/PubSubManager/addSub.js +0 -166
  145. package/lib/PubSubManager/addSync.d.ts +0 -8
  146. package/lib/PubSubManager/addSync.d.ts.map +0 -1
  147. package/lib/PubSubManager/addSync.js +0 -109
  148. package/lib/PubSubManager/getInitQuery.d.ts +0 -9
  149. package/lib/PubSubManager/getInitQuery.d.ts.map +0 -1
  150. package/lib/PubSubManager/getInitQuery.js +0 -552
  151. package/lib/PubSubManager/initPubSubManager.d.ts +0 -3
  152. package/lib/PubSubManager/initPubSubManager.d.ts.map +0 -1
  153. package/lib/PubSubManager/initPubSubManager.js +0 -116
  154. package/lib/PubSubManager/notifListener.d.ts +0 -5
  155. package/lib/PubSubManager/notifListener.d.ts.map +0 -1
  156. package/lib/PubSubManager/notifListener.js +0 -100
  157. package/lib/PubSubManager/pushSubData.d.ts +0 -3
  158. package/lib/PubSubManager/pushSubData.d.ts.map +0 -1
  159. package/lib/PubSubManager/pushSubData.js +0 -51
  160. package/lib/PublishParser.d.ts +0 -284
  161. package/lib/PublishParser.d.ts.map +0 -1
  162. package/lib/PublishParser.js +0 -421
  163. package/lib/SchemaWatch.d.ts +0 -13
  164. package/lib/SchemaWatch.d.ts.map +0 -1
  165. package/lib/SchemaWatch.js +0 -35
  166. package/lib/SyncReplication.d.ts +0 -34
  167. package/lib/SyncReplication.d.ts.map +0 -1
  168. package/lib/SyncReplication.js +0 -412
  169. package/lib/TableConfig/TableConfig.d.ts +0 -284
  170. package/lib/TableConfig/TableConfig.d.ts.map +0 -1
  171. package/lib/TableConfig/TableConfig.js +0 -437
  172. package/lib/TableConfig/getColumnDefinitionQuery.d.ts +0 -27
  173. package/lib/TableConfig/getColumnDefinitionQuery.d.ts.map +0 -1
  174. package/lib/TableConfig/getColumnDefinitionQuery.js +0 -87
  175. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts +0 -34
  176. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts.map +0 -1
  177. package/lib/TableConfig/getConstraintDefinitionQueries.js +0 -65
  178. package/lib/TableConfig/getFutureTableSchema.d.ts +0 -15
  179. package/lib/TableConfig/getFutureTableSchema.d.ts.map +0 -1
  180. package/lib/TableConfig/getFutureTableSchema.js +0 -43
  181. package/lib/TableConfig/getTableColumnQueries.d.ts +0 -16
  182. package/lib/TableConfig/getTableColumnQueries.d.ts.map +0 -1
  183. package/lib/TableConfig/getTableColumnQueries.js +0 -107
  184. package/lib/index.d.ts +0 -5
  185. package/lib/index.d.ts.map +0 -1
  186. package/lib/index.js +0 -7
  187. package/lib/shortestPath.d.ts +0 -10
  188. package/lib/shortestPath.d.ts.map +0 -1
  189. package/lib/shortestPath.js +0 -111
  190. package/lib/utils.d.ts +0 -3
  191. package/lib/utils.d.ts.map +0 -1
  192. package/lib/utils.js +0 -12
  193. package/tests/client/index.d.ts +0 -2
  194. package/tests/client/index.d.ts.map +0 -1
  195. package/tests/client/index.js +0 -80
  196. package/tests/client/index.js.map +0 -1
  197. package/tests/client_only_queries.d.ts +0 -4
  198. package/tests/client_only_queries.d.ts.map +0 -1
  199. package/tests/client_only_queries.js +0 -282
  200. package/tests/config_test/DBoGenerated.d.ts +0 -388
  201. package/tests/config_test/index.js +0 -174
  202. package/tests/config_test/index.js.map +0 -1
  203. package/tests/isomorphic_queries.d.ts +0 -9
  204. package/tests/isomorphic_queries.d.ts.map +0 -1
  205. package/tests/isomorphic_queries.js +0 -773
  206. package/tests/manual_test/DBoGenerated.d.ts +0 -398
  207. package/tests/manual_test/index.d.ts +0 -2
  208. package/tests/manual_test/index.d.ts.map +0 -1
  209. package/tests/manual_test/index.js +0 -65
  210. package/tests/server/dboTypeCheck.d.ts +0 -2
  211. package/tests/server/dboTypeCheck.d.ts.map +0 -1
  212. package/tests/server/dboTypeCheck.js +0 -27
  213. package/tests/server/index.d.ts +0 -2
  214. package/tests/server/index.d.ts.map +0 -1
  215. package/tests/server/index.js +0 -507
  216. package/tests/server/publishTypeCheck.d.ts +0 -2
  217. package/tests/server/publishTypeCheck.d.ts.map +0 -1
  218. package/tests/server/publishTypeCheck.js +0 -130
  219. package/tests/server_only_queries.d.ts +0 -2
  220. package/tests/server_only_queries.d.ts.map +0 -1
  221. package/tests/server_only_queries.js +0 -19
@@ -1,478 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const prostgles_types_1 = require("prostgles-types");
4
- const FileManager_1 = require("./FileManager/FileManager");
5
- class AuthHandler {
6
- opts;
7
- dbo;
8
- db;
9
- sidKeyName;
10
- routes = {
11
- catchAll: "*"
12
- };
13
- constructor(prostgles) {
14
- this.opts = prostgles.opts.auth;
15
- if (prostgles.opts.auth?.expressConfig) {
16
- const { magicLinks, returnURL, loginRoute, logoutGetPath } = prostgles.opts.auth.expressConfig;
17
- const magicLinksRoute = magicLinks?.route || "/magic-link";
18
- this.routes = {
19
- magicLinks: magicLinks ? {
20
- expressRoute: `${magicLinksRoute}/:id`,
21
- route: magicLinksRoute
22
- } : undefined,
23
- returnURL: returnURL || "returnURL",
24
- login: loginRoute || "/login",
25
- logoutGetPath: logoutGetPath || "/logout",
26
- catchAll: "*"
27
- };
28
- }
29
- if (!prostgles.dbo || !prostgles.db)
30
- throw "dbo or db missing";
31
- this.dbo = prostgles.dbo;
32
- this.db = prostgles.db;
33
- }
34
- validateSid = (sid) => {
35
- if (!sid)
36
- return undefined;
37
- if (typeof sid !== "string")
38
- throw "sid missing or not a string";
39
- return sid;
40
- };
41
- matchesRoute = (route, clientFullRoute) => {
42
- return route && clientFullRoute && (route === clientFullRoute ||
43
- clientFullRoute.startsWith(route) && ["/", "?", "#"].includes(clientFullRoute[route.length] ?? ""));
44
- };
45
- isUserRoute = (pathname) => {
46
- const pubRoutes = [
47
- ...this.opts?.expressConfig?.publicRoutes || [],
48
- ];
49
- if (this.routes?.login)
50
- pubRoutes.push(this.routes.login);
51
- if (this.routes?.logoutGetPath)
52
- pubRoutes.push(this.routes.logoutGetPath);
53
- if (this.routes?.magicLinks?.route)
54
- pubRoutes.push(this.routes.magicLinks.route);
55
- return !pubRoutes.some(publicRoute => {
56
- return this.matchesRoute(publicRoute, pathname); // publicRoute === pathname || pathname.startsWith(publicRoute) && ["/", "?", "#"].includes(pathname.slice(-1));
57
- });
58
- };
59
- setCookieAndGoToReturnURLIFSet = (cookie, r) => {
60
- const { sid, expires } = cookie;
61
- const { res, req } = r;
62
- if (sid) {
63
- const maxAgeOneDay = 60 * 60 * 24; // 24 hours;
64
- let cookieDuration = {
65
- maxAge: maxAgeOneDay
66
- };
67
- if (expires && Number.isFinite(expires) && !isNaN(+new Date(expires))) {
68
- // const maxAge = (+new Date(expires)) - Date.now();
69
- cookieDuration = { expires: new Date(expires) };
70
- const days = (+cookieDuration.expires - Date.now()) / (24 * 60 * 60e3);
71
- if (days >= 400) {
72
- console.warn(`Cookie expiration is higher than the Chrome 400 day limit: ${days}days`);
73
- }
74
- }
75
- const cookieOpts = {
76
- ...cookieDuration,
77
- httpOnly: true,
78
- //signed: true // Indicates if the cookie should be signed
79
- secure: true,
80
- sameSite: "strict",
81
- ...(this.opts?.expressConfig?.cookieOptions || {})
82
- };
83
- const cookieData = sid;
84
- if (!this.sidKeyName || !this.routes?.returnURL)
85
- throw "sidKeyName or returnURL missing";
86
- res.cookie(this.sidKeyName, cookieData, cookieOpts);
87
- const successURL = getReturnUrl(req, this.routes.returnURL) || "/";
88
- res.redirect(successURL);
89
- }
90
- else {
91
- throw ("no user or session");
92
- }
93
- };
94
- getUser = async (clientReq) => {
95
- if (!this.sidKeyName || !this.opts?.getUser)
96
- throw "sidKeyName or this.opts.getUser missing";
97
- const sid = clientReq.httpReq?.cookies?.[this.sidKeyName];
98
- if (!sid)
99
- return undefined;
100
- try {
101
- return this.throttledFunc(async () => {
102
- return this.opts.getUser(this.validateSid(sid), this.dbo, this.db, clientReq);
103
- }, 50);
104
- }
105
- catch (err) {
106
- console.error(err);
107
- }
108
- return undefined;
109
- };
110
- async init() {
111
- if (!this.opts)
112
- return;
113
- this.opts.sidKeyName = this.opts.sidKeyName || "session_id";
114
- const { sidKeyName, login, getUser, expressConfig } = this.opts;
115
- this.sidKeyName = this.opts.sidKeyName;
116
- if (typeof sidKeyName !== "string" && !login) {
117
- throw "Invalid auth: Provide { sidKeyName: string } ";
118
- }
119
- /**
120
- * Why ??? Collision with socket.io ???
121
- */
122
- if (this.sidKeyName === "sid")
123
- throw "sidKeyName cannot be 'sid' please provide another name.";
124
- if (!getUser)
125
- throw "getUser missing from auth config";
126
- if (expressConfig) {
127
- const { app, publicRoutes = [], onGetRequestOK, magicLinks, use } = expressConfig;
128
- if (publicRoutes.find(r => typeof r !== "string" || !r)) {
129
- throw "Invalid or empty string provided within publicRoutes ";
130
- }
131
- if (use) {
132
- app.use((req, res, next) => {
133
- use({
134
- req,
135
- res,
136
- next,
137
- getUser: () => this.getUser({ httpReq: req }),
138
- dbo: this.dbo,
139
- db: this.db,
140
- });
141
- });
142
- }
143
- if (magicLinks && this.routes.magicLinks) {
144
- const { check } = magicLinks;
145
- if (!check)
146
- throw "Check must be defined for magicLinks";
147
- app.get(this.routes.magicLinks?.expressRoute, async (req, res) => {
148
- const { id } = req.params ?? {};
149
- if (typeof id !== "string" || !id) {
150
- res.status(404).json({ msg: "Invalid magic-link id. Expecting a string" });
151
- }
152
- else {
153
- try {
154
- const session = await this.throttledFunc(async () => {
155
- const ip_address = req.ip;
156
- const user_agent = req.headers["user-agent"];
157
- return check(id, this.dbo, this.db, { ip_address, user_agent });
158
- });
159
- if (!session) {
160
- res.status(404).json({ msg: "Invalid magic-link" });
161
- }
162
- else {
163
- this.setCookieAndGoToReturnURLIFSet(session, { req, res });
164
- }
165
- }
166
- catch (e) {
167
- res.status(404).json({ msg: e });
168
- }
169
- }
170
- });
171
- }
172
- const loginRoute = this.routes?.login;
173
- if (loginRoute) {
174
- app.post(loginRoute, async (req, res) => {
175
- try {
176
- const ip_address = req.ip;
177
- const user_agent = req.headers["user-agent"];
178
- const { sid, expires } = await this.loginThrottled(req.body || {}, { ip_address, user_agent }) || {};
179
- if (sid) {
180
- this.setCookieAndGoToReturnURLIFSet({ sid, expires }, { req, res });
181
- }
182
- else {
183
- throw ("Internal error: no user or session");
184
- }
185
- }
186
- catch (err) {
187
- console.log(err);
188
- res.status(404).json({ err });
189
- }
190
- });
191
- if (this.routes.logoutGetPath && this.opts.logout) {
192
- app.get(this.routes.logoutGetPath, async (req, res) => {
193
- const sid = this.validateSid(req?.cookies?.[sidKeyName]);
194
- if (sid) {
195
- try {
196
- await this.throttledFunc(() => {
197
- return this.opts.logout(req?.cookies?.[sidKeyName], this.dbo, this.db);
198
- });
199
- }
200
- catch (err) {
201
- console.error(err);
202
- }
203
- }
204
- res.redirect("/");
205
- });
206
- }
207
- if (Array.isArray(publicRoutes)) {
208
- /* Redirect if not logged in and requesting non public content */
209
- app.get(this.routes.catchAll, async (req, res) => {
210
- const clientReq = { httpReq: req };
211
- const getUser = this.getUser;
212
- try {
213
- const returnURL = getReturnUrl(req, this.routes.returnURL);
214
- /**
215
- * Requesting a User route
216
- */
217
- if (this.isUserRoute(req.path)) {
218
- /* Check auth. Redirect to login if unauthorized */
219
- const u = await getUser(clientReq);
220
- if (!u) {
221
- res.redirect(`${loginRoute}?returnURL=${encodeURIComponent(req.originalUrl)}`);
222
- return;
223
- }
224
- /* If authorized and going to returnUrl then redirect. Otherwise serve file */
225
- }
226
- else if (returnURL && (await getUser(clientReq))) {
227
- res.redirect(returnURL);
228
- return;
229
- /** If Logged in and requesting login then redirect to main page */
230
- }
231
- else if (this.matchesRoute(loginRoute, req.path) && (await getUser(clientReq))) {
232
- res.redirect("/");
233
- return;
234
- }
235
- onGetRequestOK?.(req, res, { getUser: () => getUser(clientReq), dbo: this.dbo, db: this.db });
236
- }
237
- catch (error) {
238
- console.error(error);
239
- res.status(404).json({ msg: "Something went wrong when processing your request" });
240
- }
241
- });
242
- }
243
- }
244
- }
245
- }
246
- destroy = () => {
247
- const app = this.opts?.expressConfig?.app;
248
- const { login, logoutGetPath, magicLinks } = this.routes;
249
- (0, FileManager_1.removeExpressRoute)(app, [login, logoutGetPath, magicLinks?.expressRoute]);
250
- };
251
- throttledFunc = (func, throttle = 500) => {
252
- return new Promise(async (resolve, reject) => {
253
- let result, error, finished = false;
254
- /**
255
- * Throttle response times to prevent timing attacks
256
- */
257
- const interval = setInterval(() => {
258
- if (finished) {
259
- clearInterval(interval);
260
- if (error) {
261
- reject(error);
262
- }
263
- else {
264
- resolve(result);
265
- }
266
- }
267
- }, throttle);
268
- try {
269
- result = await func();
270
- }
271
- catch (err) {
272
- console.log(err);
273
- error = err;
274
- }
275
- finished = true;
276
- });
277
- };
278
- loginThrottled = async (params, client) => {
279
- if (!this.opts?.login)
280
- throw "Auth login config missing";
281
- const { responseThrottle = 500 } = this.opts;
282
- return this.throttledFunc(async () => {
283
- const result = await this.opts?.login?.(params, this.dbo, this.db, client);
284
- const err = {
285
- msg: "Bad login result type. \nExpecting: undefined | null | { sid: string; expires: number } but got: " + JSON.stringify(result)
286
- };
287
- if (!result)
288
- throw err;
289
- if (result && (typeof result.sid !== "string" || typeof result.expires !== "number") || !result && ![undefined, null].includes(result)) {
290
- throw err;
291
- }
292
- if (result && result.expires < Date.now()) {
293
- throw { msg: "auth.login() is returning an expired session. Can only login with a session.expires greater than Date.now()" };
294
- }
295
- return result;
296
- }, responseThrottle);
297
- };
298
- /**
299
- * Will return first sid value found in : http cookie or query params
300
- * Based on sid names in auth
301
- * @param localParams
302
- * @returns string
303
- */
304
- getSID(localParams) {
305
- if (!this.opts)
306
- return undefined;
307
- const { sidKeyName } = this.opts;
308
- if (!sidKeyName || !localParams)
309
- return undefined;
310
- if (localParams.socket) {
311
- const { handshake } = localParams.socket;
312
- const querySid = handshake?.auth?.[sidKeyName] || handshake?.query?.[sidKeyName];
313
- let rawSid = querySid;
314
- if (!rawSid) {
315
- const cookie_str = localParams.socket?.handshake?.headers?.cookie;
316
- const cookie = parseCookieStr(cookie_str);
317
- rawSid = cookie[sidKeyName];
318
- }
319
- return this.validateSid(rawSid);
320
- }
321
- else if (localParams.httpReq) {
322
- return this.validateSid(localParams.httpReq?.cookies?.[sidKeyName]);
323
- }
324
- else
325
- throw "socket OR httpReq missing from localParams";
326
- function parseCookieStr(cookie_str) {
327
- if (!cookie_str || typeof cookie_str !== "string") {
328
- return {};
329
- }
330
- return cookie_str.replace(/\s/g, '')
331
- .split(";")
332
- .reduce((prev, current) => {
333
- const [name, value] = current.split('=');
334
- prev[name] = value;
335
- return prev;
336
- }, {});
337
- }
338
- }
339
- async getClientInfo(localParams) {
340
- if (!this.opts)
341
- return {};
342
- const getSession = this.opts.cacheSession?.getSession;
343
- const isSocket = "socket" in localParams;
344
- if (isSocket) {
345
- if (getSession && localParams.socket?.__prglCache) {
346
- const { session, user, clientUser } = localParams.socket.__prglCache;
347
- const isValid = this.isValidSocketSession(localParams.socket, session);
348
- if (isValid) {
349
- return {
350
- sid: session.sid,
351
- user,
352
- clientUser,
353
- };
354
- }
355
- else
356
- return {
357
- sid: session.sid
358
- };
359
- }
360
- }
361
- const res = await this.throttledFunc(async () => {
362
- const { getUser } = this.opts ?? {};
363
- if (getUser && localParams && (localParams.httpReq || localParams.socket)) {
364
- const sid = this.getSID(localParams);
365
- const clientReq = localParams.httpReq ? { httpReq: localParams.httpReq } : { socket: localParams.socket };
366
- let user, clientUser;
367
- if (sid) {
368
- const res = await getUser(sid, this.dbo, this.db, clientReq);
369
- user = res?.user;
370
- clientUser = res?.clientUser;
371
- }
372
- if (getSession && isSocket) {
373
- const session = await getSession(sid, this.dbo, this.db);
374
- if (session?.expires && user && clientUser && localParams.socket) {
375
- localParams.socket.__prglCache = {
376
- session,
377
- user,
378
- clientUser,
379
- };
380
- }
381
- }
382
- if (sid) {
383
- return { sid, user, clientUser };
384
- }
385
- }
386
- return {};
387
- }, 5);
388
- return res;
389
- }
390
- isValidSocketSession = (socket, session) => {
391
- const hasExpired = Boolean(session && session.expires <= Date.now());
392
- if (this.opts?.expressConfig?.publicRoutes && !this.opts.expressConfig?.disableSocketAuthGuard) {
393
- const error = "Session has expired";
394
- if (hasExpired) {
395
- if (session.onExpiration === "redirect")
396
- socket.emit(prostgles_types_1.CHANNELS.AUTHGUARD, {
397
- shouldReload: session.onExpiration === "redirect",
398
- error
399
- });
400
- throw error;
401
- }
402
- }
403
- return Boolean(session && !hasExpired);
404
- };
405
- makeSocketAuth = async (socket) => {
406
- if (!this.opts)
407
- return {};
408
- const auth = {};
409
- if (this.opts.expressConfig?.publicRoutes && !this.opts.expressConfig?.disableSocketAuthGuard) {
410
- auth.pathGuard = true;
411
- socket.removeAllListeners(prostgles_types_1.CHANNELS.AUTHGUARD);
412
- socket.on(prostgles_types_1.CHANNELS.AUTHGUARD, async (params, cb = (_err, _res) => { }) => {
413
- try {
414
- const { pathname, origin } = typeof params === "string" ? JSON.parse(params) : (params || {});
415
- if (pathname && typeof pathname !== "string") {
416
- console.warn("Invalid pathname provided for AuthGuardLocation: ", pathname);
417
- }
418
- /** These origins */
419
- const IGNORED_API_ORIGINS = ["file://"];
420
- if (!IGNORED_API_ORIGINS.includes(origin) && pathname && typeof pathname === "string" && this.isUserRoute(pathname) && !(await this.getClientInfo({ socket }))?.user) {
421
- cb(null, { shouldReload: true });
422
- }
423
- else {
424
- cb(null, { shouldReload: false });
425
- }
426
- }
427
- catch (err) {
428
- console.error("AUTHGUARD err: ", err);
429
- cb(err);
430
- }
431
- });
432
- }
433
- const { register, logout } = this.opts;
434
- const login = this.loginThrottled;
435
- let handlers = [
436
- { func: (params, dbo, db, client) => register?.(params, dbo, db), ch: prostgles_types_1.CHANNELS.REGISTER, name: "register" },
437
- { func: (params, dbo, db, client) => login(params, client), ch: prostgles_types_1.CHANNELS.LOGIN, name: "login" },
438
- { func: (params, dbo, db, client) => logout?.(this.getSID({ socket }), dbo, db), ch: prostgles_types_1.CHANNELS.LOGOUT, name: "logout" }
439
- ].filter(h => h.func);
440
- const userData = await this.getClientInfo({ socket });
441
- if (userData) {
442
- auth.user = userData.clientUser;
443
- handlers = handlers.filter(h => h.name === "logout");
444
- }
445
- handlers.map(({ func, ch, name }) => {
446
- auth[name] = true;
447
- socket.removeAllListeners(ch);
448
- socket.on(ch, async (params, cb = (..._callback) => { }) => {
449
- try {
450
- if (!socket)
451
- throw "socket missing??!!";
452
- const id_address = socket?.conn?.remoteAddress;
453
- const user_agent = socket.handshake?.headers?.["user-agent"];
454
- const res = await func(params, this.dbo, this.db, { user_agent, id_address });
455
- if (name === "login" && res && res.sid) {
456
- /* TODO: Re-send schema to client */
457
- }
458
- cb(null, true);
459
- }
460
- catch (err) {
461
- console.error(name + " err", err);
462
- cb(err);
463
- }
464
- });
465
- });
466
- return { auth, userData };
467
- };
468
- }
469
- exports.default = AuthHandler;
470
- /**
471
- * AUTH
472
- */
473
- function getReturnUrl(req, name) {
474
- if (req?.query?.returnURL && name) {
475
- return decodeURIComponent(req?.query?.[name]);
476
- }
477
- return null;
478
- }
@@ -1,38 +0,0 @@
1
- import { PostgresNotifListenManager } from "./PostgresNotifListenManager";
2
- import { DB, PGP } from "./Prostgles";
3
- import { PRGLIOSocket } from "./DboBuilder";
4
- export declare class DBEventsManager {
5
- notifies: {
6
- [key: string]: {
7
- socketChannel: string;
8
- sockets: any[];
9
- localFuncs: ((payload: string) => void)[];
10
- notifMgr: PostgresNotifListenManager;
11
- };
12
- };
13
- notice: {
14
- socketChannel: string;
15
- socketUnsubChannel: string;
16
- sockets: any[];
17
- };
18
- notifManager?: PostgresNotifListenManager;
19
- db_pg: DB;
20
- pgp: PGP;
21
- constructor(db_pg: DB, pgp: PGP);
22
- private onNotif;
23
- onNotice: (notice: any) => void;
24
- getNotifChannelName: (channel: string) => Promise<any>;
25
- addNotify(query: string, socket?: PRGLIOSocket, func?: any): Promise<{
26
- socketChannel: string;
27
- socketUnsubChannel: string;
28
- notifChannel: string;
29
- unsubscribe?: () => void;
30
- }>;
31
- removeNotify(channel?: string, socket?: PRGLIOSocket, func?: any): void;
32
- addNotice(socket: PRGLIOSocket): {
33
- socketChannel: string;
34
- socketUnsubChannel: string;
35
- };
36
- removeNotice(socket: PRGLIOSocket): void;
37
- }
38
- //# sourceMappingURL=DBEventsManager.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DBEventsManager.d.ts","sourceRoot":"","sources":["DBEventsManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAqB,MAAM,8BAA8B,CAAC;AAC7F,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,qBAAa,eAAe;IAE1B,QAAQ,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG;YACb,aAAa,EAAE,MAAM,CAAC;YACtB,OAAO,EAAE,GAAG,EAAE,CAAC;YACf,UAAU,EAAE,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC,EAAE,CAAC;YAC1C,QAAQ,EAAE,0BAA0B,CAAC;SACtC,CAAA;KACF,CAAM;IAEP,MAAM,EAAE;QACN,aAAa,EAAE,MAAM,CAAC;QACtB,kBAAkB,EAAE,MAAM,CAAC;QAC3B,OAAO,EAAE,GAAG,EAAE,CAAC;KAChB,CAIC;IAEF,YAAY,CAAC,EAAE,0BAA0B,CAAC;IAE1C,KAAK,EAAE,EAAE,CAAC;IACV,GAAG,EAAE,GAAG,CAAA;gBACI,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG;IAK/B,OAAO,CAAC,OAAO,CAgBd;IAED,QAAQ,WAAY,GAAG,UAMtB;IAED,mBAAmB,YAAmB,MAAM,kBAG3C;IAEK,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC;QACzE,aAAa,EAAE,MAAM,CAAC;QACtB,kBAAkB,EAAE,MAAM,CAAC;QAC3B,YAAY,EAAE,MAAM,CAAC;QACrB,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;KAC1B,CAAC;IAmEF,YAAY,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,GAAG;IAmBhE,SAAS,CAAC,MAAM,EAAE,YAAY;;;;IAiB9B,YAAY,CAAC,MAAM,EAAE,YAAY;CAIlC"}
@@ -1,140 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DBEventsManager = void 0;
4
- const PostgresNotifListenManager_1 = require("./PostgresNotifListenManager");
5
- const prostgles_types_1 = require("prostgles-types");
6
- class DBEventsManager {
7
- notifies = {};
8
- notice = {
9
- socketChannel: prostgles_types_1.CHANNELS.NOTICE_EV,
10
- socketUnsubChannel: prostgles_types_1.CHANNELS.NOTICE_EV + "unsubscribe",
11
- sockets: []
12
- };
13
- notifManager;
14
- db_pg;
15
- pgp;
16
- constructor(db_pg, pgp) {
17
- this.db_pg = db_pg;
18
- this.pgp = pgp;
19
- }
20
- onNotif = ({ channel, payload }) => {
21
- // console.log(36, { channel, payload }, Object.keys(this.notifies));
22
- (0, prostgles_types_1.getKeys)(this.notifies)
23
- .filter(ch => ch === channel)
24
- .map(ch => {
25
- const sub = this.notifies[ch];
26
- sub.sockets.map(s => {
27
- s.emit(sub.socketChannel, payload);
28
- });
29
- sub.localFuncs.map(lf => {
30
- lf(payload);
31
- });
32
- });
33
- };
34
- onNotice = (notice) => {
35
- if (this.notice && this.notice.sockets.length) {
36
- this.notice.sockets.map(s => {
37
- s.emit(this.notice.socketChannel, notice);
38
- });
39
- }
40
- };
41
- getNotifChannelName = async (channel) => {
42
- const c = await this.db_pg.one("SELECT quote_ident($1) as c", channel);
43
- return c.c;
44
- };
45
- async addNotify(query, socket, func) {
46
- if (typeof query !== "string" || (!socket && !func)) {
47
- throw "Expecting (query: string, socket?, localFunc?) But received: " + JSON.stringify({ query, socket, func });
48
- }
49
- /* Remove comments */
50
- let q = query.trim()
51
- .replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '\n')
52
- .split("\n").map(v => v.trim()).filter(v => v && !v.startsWith("--"))
53
- .join("\n");
54
- /* Find the notify channel name */
55
- if (!q.toLowerCase().startsWith("listen")) {
56
- throw "Expecting a LISTEN query but got: " + query;
57
- }
58
- q = q.slice(7).trim(); // Remove listen
59
- if (q.endsWith(";"))
60
- q = q.slice(0, -1);
61
- if (q.startsWith('"') && q.endsWith('"')) {
62
- q = q.slice(1, -1);
63
- }
64
- else {
65
- /* Replicate PG by lowercasing identifier if not quoted */
66
- q = q.toLowerCase();
67
- }
68
- q = q.replace(/""/g, `"`);
69
- const channel = q;
70
- let notifChannel = await this.getNotifChannelName(channel);
71
- notifChannel = notifChannel.replace(/""/g, `"`);
72
- if (notifChannel.startsWith('"'))
73
- notifChannel = notifChannel.slice(1, -1);
74
- const socketChannel = prostgles_types_1.CHANNELS.LISTEN_EV + notifChannel, socketUnsubChannel = socketChannel + "unsubscribe";
75
- if (!this.notifies[notifChannel]) {
76
- this.notifies[notifChannel] = {
77
- socketChannel,
78
- sockets: socket ? [socket] : [],
79
- localFuncs: func ? [func] : [],
80
- notifMgr: await PostgresNotifListenManager_1.PostgresNotifListenManager.create(this.db_pg, this.onNotif, channel)
81
- };
82
- }
83
- else {
84
- if (socket && !this.notifies[notifChannel].sockets.find(s => s.id === socket.id)) {
85
- this.notifies[notifChannel].sockets.push(socket);
86
- }
87
- else if (func) {
88
- this.notifies[notifChannel].localFuncs.push(func);
89
- }
90
- }
91
- if (socket) {
92
- socket.removeAllListeners(socketUnsubChannel);
93
- socket.on(socketUnsubChannel, () => {
94
- this.removeNotify(notifChannel, socket);
95
- });
96
- }
97
- return {
98
- // unsubscribe: () => this.removeNotify(notifChannel, socket, func),
99
- socketChannel,
100
- socketUnsubChannel,
101
- notifChannel,
102
- };
103
- }
104
- removeNotify(channel, socket, func) {
105
- const notifChannel = channel && this.notifies[channel];
106
- if (notifChannel) {
107
- if (socket) {
108
- notifChannel.sockets = notifChannel.sockets.filter(s => s.id !== socket.id);
109
- }
110
- else if (func) {
111
- notifChannel.localFuncs = notifChannel.localFuncs.filter(f => f !== func);
112
- }
113
- /* UNLISTEN if no listeners ?? */
114
- }
115
- if (socket) {
116
- (0, prostgles_types_1.getKeys)(this.notifies).forEach(channel => {
117
- this.notifies[channel].sockets = this.notifies[channel].sockets.filter(s => s.id !== socket.id);
118
- });
119
- }
120
- }
121
- addNotice(socket) {
122
- if (!socket || !socket.id)
123
- throw "Expecting a socket obj with id";
124
- if (!this.notice.sockets.find(s => s.id === socket.id)) {
125
- this.notice.sockets.push(socket);
126
- }
127
- const { socketChannel, socketUnsubChannel } = this.notice;
128
- socket.removeAllListeners(socketUnsubChannel);
129
- socket.on(socketUnsubChannel, () => {
130
- this.removeNotice(socket);
131
- });
132
- return { socketChannel, socketUnsubChannel, };
133
- }
134
- removeNotice(socket) {
135
- if (!socket || !socket.id)
136
- throw "Expecting a socket obj with id";
137
- this.notice.sockets = this.notice.sockets.filter(s => s.id !== socket.id);
138
- }
139
- }
140
- exports.DBEventsManager = DBEventsManager;
@@ -1,13 +0,0 @@
1
- import { DBSchema, TableHandler, ViewHandler } from "prostgles-types";
2
- import { DBHandlerServer, DboBuilder } from "./DboBuilder";
3
- import { PublishAllOrNothing, PublishTableRule, PublishViewRule } from "./PublishParser";
4
- export declare const getDBSchema: (dboBuilder: DboBuilder) => string;
5
- type DBTableHandlersFromSchema<Schema = void> = Schema extends DBSchema ? {
6
- [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true ? ViewHandler<Schema[tov_name]["columns"]> : TableHandler<Schema[tov_name]["columns"]>;
7
- } : Record<string, TableHandler>;
8
- export type DBOFullyTyped<Schema = void> = Schema extends DBSchema ? (DBTableHandlersFromSchema<Schema> & Pick<DBHandlerServer<DBTableHandlersFromSchema<Schema>>, "tx" | "sql">) : DBHandlerServer;
9
- export type PublishFullyTyped<Schema = void> = Schema extends DBSchema ? (PublishAllOrNothing | {
10
- [tov_name in keyof Partial<Schema>]: PublishAllOrNothing | (Schema[tov_name]["is_view"] extends true ? PublishViewRule<Schema[tov_name]["columns"], Schema> : PublishTableRule<Schema[tov_name]["columns"], Schema>);
11
- }) : (PublishAllOrNothing | Record<string, PublishViewRule | PublishTableRule | PublishAllOrNothing>);
12
- export {};
13
- //# sourceMappingURL=DBSchemaBuilder.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DBSchemaBuilder.d.ts","sourceRoot":"","sources":["DBSchemaBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAmB,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGvF,OAAO,EAAE,eAAe,EAAE,UAAU,EAAsD,MAAM,cAAc,CAAC;AAC/G,OAAO,EAAE,mBAAmB,EAAiB,gBAAgB,EAAE,eAAe,EAAI,MAAM,iBAAiB,CAAC;AAI1G,eAAO,MAAM,WAAW,eAAgB,UAAU,KAAG,MAoDpD,CAAA;AAED,KAAK,yBAAyB,CAAC,MAAM,GAAG,IAAI,IAAI,MAAM,SAAS,QAAQ,GAAE;KACtE,QAAQ,IAAI,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,SAAS,IAAI,GAClE,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,GACxC,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC;CAC5C,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAEjC,MAAM,MAAM,aAAa,CAAC,MAAM,GAAG,IAAI,IAAI,MAAM,SAAS,QAAQ,GAAE,CAChE,yBAAyB,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,eAAe,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,GAAG,KAAK,CAAC,CAC3G,GACD,eAAe,CAAC;AAElB,MAAM,MAAM,iBAAiB,CAAC,MAAM,GAAG,IAAI,IAAI,MAAM,SAAS,QAAQ,GAAE,CACpE,mBAAmB,GACnB;KACC,QAAQ,IAAI,MAAM,OAAO,CAAC,MAAM,CAAC,GAC9B,mBAAmB,GACnB,CACA,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,SAAS,IAAI,GACtC,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,GACpD,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,CACxD;CACJ,CACF,GAAG,CACA,mBAAmB,GACnB,MAAM,CAAC,MAAM,EAAE,eAAe,GAAG,gBAAgB,GAAG,mBAAmB,CAAC,CAC3E,CAAC"}