@miqro/core 5.0.10 → 5.0.11

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.
@@ -3,16 +3,17 @@ import { RequestOptions, RequestResponse, request } from "@miqro/request";
3
3
  import { Schema } from "@miqro/parser";
4
4
  import { parse as cookieParse } from "cookie";
5
5
  import { BadRequestError, checkEnvVariables, ForbiddenError, UnAuthorizedError } from "../common.js";
6
- import { GroupPolicy, GroupPolicySchema, Handler, NoTokenSession, Request, Response, Session, SessionHandlerOptions } from "../types.js";
6
+ import { GroupPolicy, GroupPolicySchema, Handler, NoTokenSession, Request, Response, Session, SessionHandlerOptions, SessionHandlerOptionsOptionsSchema, SessionHandlerOptionsSchema } from "../types.js";
7
7
 
8
- const DEFAULT_TOKEN_LOCATION = "header";
8
+ //const DEFAULT_TOKEN_LOCATION = "header";
9
+ const DEFAULT_TOKEN_LOCATION = "free";
9
10
  const DEFAULT_TOKEN_HEADER = "Authorization";
10
11
  const DEFAULT_TOKEN_QUERY = "token";
11
12
  const DEFAULT_TOKEN_COOKIE = "Authorization";
12
- const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
13
- const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
14
- const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
15
- const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
13
+ export const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
14
+ export const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
15
+ export const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
16
+ export const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
16
17
 
17
18
  export interface VerifyTokenService {
18
19
  verify(args: { token: string; req: Request }): Promise<Session | null>;
@@ -191,6 +192,8 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
191
192
  }
192
193
  };
193
194
  switch (tokenLocation) {
195
+ case "free":
196
+ break;
194
197
  case "header":
195
198
  config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
196
199
  break;
@@ -213,44 +216,15 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
213
216
  throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
214
217
  }
215
218
  } else {
216
- config.options = assertNotUndefined(DEFAULT_PARSER.parse(config.options as any, {
217
- type: "object",
218
- properties: {
219
- tokenLocation: {
220
- required: true,
221
- type: "enum",
222
- enumValues: ["header", "query", "cookie"]
223
- },
224
- tokenLocationName: {
225
- required: true,
226
- type: "any"
227
- },
228
- setCookieOptions: {
229
- required: false,
230
- type: "object",
231
- defaultValue: {
232
- httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
233
- secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
234
- path: DEFAULT_TOKEN_SET_COOKIE_PATH,
235
- sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
236
- },
237
- properties: {
238
- httpOnly: "boolean",
239
- secure: "boolean",
240
- path: "any",
241
- sameSite: {
242
- required: true, type: "enum", enumValues: ["lax", "strict", "none"]
243
- }
244
- }
245
- }
246
- }
247
- }, "options"), "bad options");
219
+ config.options = assertNotUndefined(DEFAULT_PARSER.parse(config.options as any, SessionHandlerOptionsOptionsSchema, "options"), "bad options");
248
220
  }
249
221
 
250
222
  if (!config.authService) {
251
223
  throw new Error("authService must be provided!");
252
224
  }
253
225
  if (!config.options || !config.options.setCookieOptions) {
226
+ console.dir(config);
227
+ process.exit(1);
254
228
  throw new Error("config.options not populated!");
255
229
  }
256
230
  const tokenLocation = config.options.tokenLocation;
@@ -258,12 +232,15 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
258
232
  const setCookieOptions = config.options.setCookieOptions;
259
233
  return async function SessionHandler(req, res): Promise<void> {
260
234
  try {
261
- const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(req);
235
+ const tlN = typeof tokenLocationName === "string" ? tokenLocationName : tokenLocationName ? await tokenLocationName(req) : "";
262
236
  let token = null;
263
237
  switch (tokenLocation) {
264
238
  case "header":
265
239
  token = req.headers[(tlN).toLowerCase()] as string;
266
240
  break;
241
+ case "free":
242
+ token = null;
243
+ break;
267
244
  case "query":
268
245
  token = req.query[tlN] as string;
269
246
  break;
@@ -273,7 +250,7 @@ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
273
250
  default:
274
251
  throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
275
252
  }
276
- if (!token) {
253
+ if (!token && tokenLocation !== "free") {
277
254
  req.logger.warn("No token provided!");
278
255
  throw new ForbiddenError("NO TOKEN");
279
256
  } else {
package/src/types.ts CHANGED
@@ -5,6 +5,7 @@ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
5
5
  import { Socket } from "net";
6
6
  import { Duplex } from "stream";
7
7
  import { Logger } from "./common.js";
8
+ import { DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE, DEFAULT_TOKEN_SET_COOKIE_SECURE } from "./middleware/session.js";
8
9
 
9
10
  /**
10
11
  * Types
@@ -31,6 +32,7 @@ export type LogLevel = "error" | "warn" | "info" | "debug" | "trace" | "none";
31
32
  export interface WriteArgs {
32
33
  level: LogLevel;
33
34
  message?: any;
35
+ identifier: string;
34
36
  optionalParams: any[]
35
37
  }
36
38
 
@@ -87,16 +89,48 @@ export const GroupPolicySchema: Schema<GroupPolicy> = {
87
89
 
88
90
  export interface SessionHandlerOptions {
89
91
  authService: {
90
- verify(args: { token: string; req: Request; res: Response }): Promise<Session | null>;
92
+ verify(args: { token?: string | null; req: Request; res: Response }): Promise<Session | null>;
91
93
  };
92
- options?: {
93
- tokenLocation: "header" | "query" | "cookie";
94
- tokenLocationName: string | ((req: Request) => Promise<string>);
95
- setCookieOptions?: {
96
- httpOnly: boolean;
97
- secure: boolean;
98
- path: string | ((req: Request) => Promise<string>);
99
- sameSite: "lax" | "strict" | "none";
94
+ options?: SessionHandlerOptionsOptions;
95
+ }
96
+
97
+ export interface SessionHandlerOptionsOptions {
98
+ tokenLocation: "header" | "query" | "cookie" | "free";
99
+ tokenLocationName?: string | ((req: Request) => Promise<string>);
100
+ setCookieOptions?: {
101
+ httpOnly: boolean;
102
+ secure: boolean;
103
+ path: string | ((req: Request) => Promise<string>);
104
+ sameSite: "lax" | "strict" | "none";
105
+ }
106
+ }
107
+
108
+ export const SessionHandlerOptionsOptionsSchema: Schema<SessionHandlerOptionsOptions> = {
109
+ type: "object",
110
+ properties: {
111
+ tokenLocation: {
112
+ type: "enum",
113
+ defaultValue: "free",
114
+ enumValues: ["header", "query", "cookie", "free"]
115
+ },
116
+ tokenLocationName: "string?|function?",
117
+ setCookieOptions: {
118
+ type: "object?",
119
+ defaultValue: Object.freeze({
120
+ httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
121
+ secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
122
+ path: DEFAULT_TOKEN_SET_COOKIE_PATH,
123
+ sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE
124
+ }),
125
+ properties: {
126
+ httpOnly: "boolean",
127
+ secure: "boolean",
128
+ path: "string|function",
129
+ sameSite: {
130
+ type: "enum",
131
+ enumValues: ["lax", "strict", "none"]
132
+ }
133
+ }
100
134
  }
101
135
  }
102
136
  }
@@ -112,25 +146,7 @@ export const SessionHandlerOptionsSchema: Schema<SessionHandlerOptions> = {
112
146
  },
113
147
  options: {
114
148
  type: "object?",
115
- properties: {
116
- tokenLocation: {
117
- type: "enum",
118
- enumValues: ["header", "query", "cookie"]
119
- },
120
- tokenLocationName: "string|function",
121
- setCookieOptions: {
122
- type: "object?",
123
- properties: {
124
- httpOnly: "boolean",
125
- secure: "boolean",
126
- path: "string|function",
127
- sameSite: {
128
- type: "enum",
129
- enumValues: ["lax", "strict", "none"]
130
- }
131
- }
132
- }
133
- }
149
+ properties: SessionHandlerOptionsOptionsSchema.properties
134
150
  }
135
151
  }
136
152
  };
@@ -348,11 +364,13 @@ export function isMinimalRouter(obj: any) {
348
364
  * ```
349
365
  */
350
366
  export interface APIRoute extends RouterHandlerOptions {
351
- postFolder?: boolean,
352
- method?: Method | "use" | "USE";
353
- path?: string | null;
367
+ postFolder?: boolean;
368
+ basePath?: string;
369
+ method?: Method[] | Method | "use" | "USE";
370
+ path?: string[] | string | null;
354
371
  ignore?: boolean;
355
372
  handler: Handler | Array<Handler> | MinimalRouter;
373
+ init?: (route: APIRoute) => Promise<void>;
356
374
  }
357
375
 
358
376
  export interface APIRouterOptions {
@@ -360,6 +378,8 @@ export interface APIRouterOptions {
360
378
  apiName?: string;
361
379
  path?: string;
362
380
  ignore?: Array<string | RegExp>;
381
+ loader?: (path: string) => Promise<any>;
382
+ extensions?: string[];
363
383
  }
364
384
 
365
385
  export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
@@ -371,7 +391,9 @@ export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
371
391
  ignore: {
372
392
  type: "array?",
373
393
  arrayType: "string|RegExp"
374
- }
394
+ },
395
+ loader: "function?",
396
+ extensions: "string[]?",
375
397
  }
376
398
  };
377
399
 
@@ -380,9 +402,10 @@ export const APIRouteSchema: Schema<APIRoute> = {
380
402
  properties: {
381
403
  ...RouterHandlerOptionsSchema.properties,
382
404
  postFolder: "boolean?",
383
- method: "string?",
405
+ basePath: "string?",
406
+ method: "string?|string[]?",
384
407
  path: {
385
- type: "string?",
408
+ type: "string?|string[]?",
386
409
  allowNull: true
387
410
  },
388
411
  ignore: "boolean?",
@@ -390,7 +413,8 @@ export const APIRouteSchema: Schema<APIRoute> = {
390
413
  type: "function[]!|object",
391
414
  properties: MinimalRouterSchema.properties,
392
415
  mode: MinimalRouterSchema.mode
393
- }
416
+ },
417
+ init: "function?"
394
418
  }
395
419
  };
396
420
 
@@ -492,6 +516,8 @@ export interface Response<Request extends IncomingMessage = IncomingMessage> ext
492
516
  addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse;
493
517
  setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse;
494
518
  html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
519
+ css(css: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
520
+ js(js: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
495
521
  text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
496
522
  redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
497
523
  }
@@ -523,6 +549,26 @@ export class Response<Request extends IncomingMessage = IncomingMessage> extends
523
549
  body: html
524
550
  })
525
551
  }
552
+ async css(css: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
553
+ return this.asyncEnd({
554
+ status: status !== undefined ? status : 200,
555
+ headers: {
556
+ ['Content-Type']: 'text/css; charset=utf-8',
557
+ ...headers
558
+ },
559
+ body: css
560
+ })
561
+ }
562
+ async js(js: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
563
+ return this.asyncEnd({
564
+ status: status !== undefined ? status : 200,
565
+ headers: {
566
+ ['Content-Type']: 'text/javascript; charset=utf-8',
567
+ ...headers
568
+ },
569
+ body: js
570
+ })
571
+ }
526
572
  async text(text: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
527
573
  return this.asyncEnd({
528
574
  status: status !== undefined ? status : 200,
@@ -813,6 +859,7 @@ export interface WebSocketServerOptions {
813
859
  onConnection?: (req: WebSocketClient) => void;
814
860
  onMessage?: (req: WebSocketClient, data: string | undefined | null) => void;
815
861
  onDisconnect?: (req: WebSocketClient) => void;
862
+ onError?: (req: WebSocketClient, error: Error) => void;
816
863
  }
817
864
 
818
865
  export interface WebSocketClient {
package/src/websocket.ts CHANGED
@@ -26,10 +26,17 @@ export class WebSocketServer implements ConnectionUpgrader {
26
26
  const clients = this.clients.values();
27
27
  for (const client of clients) {
28
28
  if (fromUUID === undefined || client.uuid !== fromUUID) {
29
- tR.push(this.writeTo(client.uuid, data));
29
+ tR.push(new Promise<void>(async (resolve, reject) => {
30
+ try {
31
+ await this.writeTo(client.uuid, data);
32
+ resolve();
33
+ } catch (e) {
34
+ reject(e);
35
+ }
36
+ }));
30
37
  }
31
38
  }
32
- await Promise.all(tR);
39
+ await Promise.allSettled(tR);
33
40
  }
34
41
 
35
42
  public async writeTo(clientUUID: string, data: string) {
@@ -39,14 +46,26 @@ export class WebSocketServer implements ConnectionUpgrader {
39
46
  }
40
47
  return new Promise<void>((resolve, reject) => {
41
48
  try {
42
- client.req.socket.write(createFrame(data), function SocketWriteCallback(err?: Error) {
49
+ client.req.socket.write(createFrame(data), (err?: Error) => {
43
50
  if (err) {
51
+ try {
52
+ client.req.socket.destroy(err);
53
+ } catch (e) {
54
+ console.error(e);
55
+ }
56
+ this.clients.delete(clientUUID);
44
57
  reject(err);
45
58
  } else {
46
59
  resolve();
47
60
  }
48
61
  })
49
62
  } catch (e) {
63
+ try {
64
+ client.req.socket.destroy();
65
+ } catch (e) {
66
+ console.error(e);
67
+ }
68
+ this.clients.delete(clientUUID);
50
69
  reject(e);
51
70
  }
52
71
  });
@@ -118,6 +137,18 @@ export class WebSocketServer implements ConnectionUpgrader {
118
137
  }
119
138
  });
120
139
 
140
+ socket.on("error", (error) => {
141
+ req.logger.debug("upgraded connection error!");
142
+ req.logger.error(error);
143
+ if (this.options.onError) {
144
+ try {
145
+ this.options.onError(client, error);
146
+ } catch (e) {
147
+ req.logger.error(e);
148
+ }
149
+ }
150
+ });
151
+
121
152
  socket.on("end", () => {
122
153
  req.logger.debug("upgraded connection disconnected!");
123
154
  this.clients.delete(uuid);
@@ -130,6 +161,8 @@ export class WebSocketServer implements ConnectionUpgrader {
130
161
  }
131
162
  });
132
163
 
164
+
165
+
133
166
  req.logger.debug("connection upgraded");
134
167
  this.clients.set(uuid, client);
135
168
  if (this.options.onConnection) {
@@ -149,8 +182,9 @@ const ClusterWebSocketServerMessageType = "ClusterWebSocketServerMessage";
149
182
 
150
183
  export interface ClusterWebSocketServerMessage {
151
184
  type: typeof ClusterWebSocketServerMessageType;
152
- action: "connection" | "disconnection" | "sendMessage";
185
+ action: "connection" | "disconnection" | "sendMessage" | "error";
153
186
  clientUUID?: string;
187
+ errorMessage?: string;
154
188
  fromUUID?: string;
155
189
  payload?: Serializable;
156
190
  }
@@ -171,6 +205,19 @@ export class ClusterWebSocketServer extends WebSocketServer {
171
205
  return options.validate ? options.validate(req) : true;
172
206
  }
173
207
  },
208
+ onError: (req, error) => {
209
+ if (process.send) {
210
+ process.send({
211
+ type: ClusterWebSocketServerMessageType,
212
+ action: "error",
213
+ clientUUID: req.uuid,
214
+ errorMessage: error.message
215
+ } as ClusterWebSocketServerMessage);
216
+ }
217
+ if (options.onError) {
218
+ options.onError(req, error);
219
+ }
220
+ },
174
221
  onConnection: (req) => {
175
222
  if (process.send) {
176
223
  process.send({
@@ -201,40 +248,44 @@ export class ClusterWebSocketServer extends WebSocketServer {
201
248
  }
202
249
  ClusterWebSocketServer.instance = this;
203
250
  if (process.send) {
204
- process.on("message", (data) => {
205
- const msg = (data as ClusterWebSocketServerMessage);
206
- if (
207
- msg &&
208
- msg.type === ClusterWebSocketServerMessageType &&
209
- msg.action) {
210
- // receive message from cluster workers
211
- switch (msg.action) {
212
- case "connection":
213
- if (!msg.clientUUID) {
214
- throw new Error(`action [${msg.action}] without clientUUID`);
215
- }
216
- this.remoteClients.add(msg.clientUUID);
217
- break;
218
- case "disconnection":
219
- if (!msg.clientUUID) {
220
- throw new Error(`action [${msg.action}] without clientUUID`);
221
- }
222
- this.remoteClients.delete(msg.clientUUID);
223
- break;
224
- case "sendMessage": {
225
- const payload = String(msg.payload);
226
- if (!msg.clientUUID) {
227
- // broadcast to local clients
228
- super.broadcast(payload, msg.fromUUID);
229
- } else if (this.isConnected(msg.clientUUID)) {
230
- // write if local client
231
- super.writeTo(msg.clientUUID, payload);
251
+ process.on("message", async (data) => {
252
+ try {
253
+ const msg = (data as ClusterWebSocketServerMessage);
254
+ if (
255
+ msg &&
256
+ msg.type === ClusterWebSocketServerMessageType &&
257
+ msg.action) {
258
+ // receive message from cluster workers
259
+ switch (msg.action) {
260
+ case "connection":
261
+ if (!msg.clientUUID) {
262
+ throw new Error(`action [${msg.action}] without clientUUID`);
263
+ }
264
+ this.remoteClients.add(msg.clientUUID);
265
+ break;
266
+ case "disconnection":
267
+ if (!msg.clientUUID) {
268
+ throw new Error(`action [${msg.action}] without clientUUID`);
269
+ }
270
+ this.remoteClients.delete(msg.clientUUID);
271
+ break;
272
+ case "sendMessage": {
273
+ const payload = String(msg.payload);
274
+ if (!msg.clientUUID) {
275
+ // broadcast to local clients
276
+ await super.broadcast(payload, msg.fromUUID);
277
+ } else if (this.isConnected(msg.clientUUID)) {
278
+ // write if local client
279
+ await super.writeTo(msg.clientUUID, payload);
280
+ }
281
+ break;
232
282
  }
233
- break;
283
+ default:
284
+ throw new Error(`action [${msg.action}] not supported`);
234
285
  }
235
- default:
236
- throw new Error(`action [${msg.action}] not supported`);
237
286
  }
287
+ } catch (e) {
288
+ console.error(e);
238
289
  }
239
290
  });
240
291
  }
@@ -249,7 +300,7 @@ export class ClusterWebSocketServer extends WebSocketServer {
249
300
  fromUUID
250
301
  } as ClusterWebSocketServerMessage);
251
302
  }
252
- super.broadcast(payload, fromUUID);
303
+ return super.broadcast(payload, fromUUID);
253
304
  }
254
305
 
255
306
  public async writeTo(clientUUID: string, payload: string): Promise<void> {
@@ -268,7 +319,7 @@ export class ClusterWebSocketServer extends WebSocketServer {
268
319
  // due to the implementation of isUUIDValid depends on this.remoteClients to be sync there can be two clients registered with the same UUID in the cluster
269
320
  if (this.clients.has(clientUUID)) {
270
321
  // write to local client
271
- super.writeTo(clientUUID, payload);
322
+ return super.writeTo(clientUUID, payload);
272
323
  }
273
324
  }
274
325