@miqro/core 5.0.9 → 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.
- package/build/app.d.ts +6 -0
- package/build/app.js +35 -5
- package/build/app.js.map +1 -1
- package/build/common.d.ts +1 -1
- package/build/common.js +7 -7
- package/build/common.js.map +1 -1
- package/build/lib.d.ts +2 -2
- package/build/lib.js +2 -2
- package/build/lib.js.map +1 -1
- package/build/middleware/router.d.ts +3 -2
- package/build/middleware/router.js +98 -60
- package/build/middleware/router.js.map +1 -1
- package/build/middleware/session.d.ts +4 -0
- package/build/middleware/session.js +17 -40
- package/build/middleware/session.js.map +1 -1
- package/build/types.d.ts +36 -14
- package/build/types.js +91 -28
- package/build/types.js.map +1 -1
- package/build/websocket.d.ts +2 -1
- package/build/websocket.js +88 -36
- package/build/websocket.js.map +1 -1
- package/package.json +2 -2
- package/src/app.ts +36 -5
- package/src/common.ts +8 -8
- package/src/lib.ts +11 -1
- package/src/middleware/router.ts +103 -61
- package/src/middleware/session.ts +17 -40
- package/src/types.ts +119 -42
- package/src/websocket.ts +88 -37
package/src/middleware/router.ts
CHANGED
|
@@ -29,12 +29,14 @@ import {
|
|
|
29
29
|
APIRoute,
|
|
30
30
|
APIRouteSchema,
|
|
31
31
|
MinimalLogger,
|
|
32
|
+
newURL,
|
|
33
|
+
removeStartingBackSlashes,
|
|
32
34
|
} from "../types.js";
|
|
33
35
|
import { ServerOptions } from "http";
|
|
34
36
|
import { SessionHandler, GroupPolicyHandler } from "./session.js";
|
|
35
37
|
import { DEFAULT_PARSER, assertNotUndefined, ResponseHandler, ResultParser, ParseRequest } from "./body-parser.js";
|
|
36
38
|
import { RequestOptions, request } from "@miqro/request";
|
|
37
|
-
import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
|
|
39
|
+
import { existsSync, fstatSync, lstatSync, readFileSync, readdirSync, statSync } from "fs";
|
|
38
40
|
import { basename, extname, join, parse, resolve } from "path";
|
|
39
41
|
|
|
40
42
|
/**
|
|
@@ -59,6 +61,11 @@ export class Router implements MinimalRouter {
|
|
|
59
61
|
};
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
public clear() {
|
|
65
|
+
this.handlers.splice(0, this.handlers.length);
|
|
66
|
+
this.errorHandlers.splice(0, this.errorHandlers.length);
|
|
67
|
+
}
|
|
68
|
+
|
|
62
69
|
public get(path: string | undefined, handler: Array<Handler> | Handler | MinimalRouter | HandlerWithOptions, options?: RouterHandlerOptions): Router {
|
|
63
70
|
return this.use(handler, path, "get", options);
|
|
64
71
|
}
|
|
@@ -148,14 +155,15 @@ export class Router implements MinimalRouter {
|
|
|
148
155
|
return doc;
|
|
149
156
|
}
|
|
150
157
|
|
|
151
|
-
public logPaths(logger: MinimalLogger): void {
|
|
152
|
-
this.toString().split("\n").forEach(l => logger.info(l));
|
|
158
|
+
public logPaths(logger: MinimalLogger, filter?: (path: string, method: string) => boolean): void {
|
|
159
|
+
this.toString(filter).split("\n").forEach(l => logger.info(l));
|
|
153
160
|
}
|
|
154
161
|
|
|
155
|
-
public toString(): string {
|
|
162
|
+
public toString(filter?: (path: string, method: string) => boolean): string {
|
|
156
163
|
let ret = "";
|
|
157
164
|
const doc = this.getJSONDoc();
|
|
158
165
|
const paths = Object.keys(doc);
|
|
166
|
+
const tab = " ";
|
|
159
167
|
|
|
160
168
|
for (const path of paths) {
|
|
161
169
|
if (path) {
|
|
@@ -165,8 +173,13 @@ export class Router implements MinimalRouter {
|
|
|
165
173
|
|
|
166
174
|
for (const method of methods) {
|
|
167
175
|
if (method) {
|
|
168
|
-
const
|
|
169
|
-
|
|
176
|
+
const show = filter ? filter(path, method) : true;
|
|
177
|
+
if (show) {
|
|
178
|
+
const methodDataList = pathData[method];
|
|
179
|
+
for (const methodData of methodDataList) {
|
|
180
|
+
ret += `${ret === "" ? "" : "\n"}${String(method).toUpperCase()}:${path}\n${tab}${methodData.identifier}${methodData.name ? `\n${tab}${tab}${methodData.name}` : ""}${methodData.description ? `\n${tab}${tab}${methodData.description}` : ""}`;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
170
183
|
}
|
|
171
184
|
}
|
|
172
185
|
}
|
|
@@ -247,8 +260,9 @@ class RouterHandler {
|
|
|
247
260
|
this.handler = handlers;
|
|
248
261
|
}
|
|
249
262
|
|
|
250
|
-
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "
|
|
251
|
-
const
|
|
263
|
+
public getJSONDoc(doc: RouterJSONDoc = {}, prePath = ""): RouterJSONDoc {
|
|
264
|
+
const pp = normalizePath(removeStartingBackSlashes(this.path ? this.path : "/"));
|
|
265
|
+
const nPath = pp.length > 1 ? pp.substring(1) : "";
|
|
252
266
|
const nMethod = this.method ? this.method : "";
|
|
253
267
|
|
|
254
268
|
if (this.isRouter) {
|
|
@@ -258,11 +272,11 @@ class RouterHandler {
|
|
|
258
272
|
if (!doc[`${prePath}${nPath}`]) {
|
|
259
273
|
doc[`${prePath}${nPath}`] = Object.create(null);
|
|
260
274
|
}
|
|
261
|
-
if (doc[`${prePath}${nPath}`][nMethod]) {
|
|
262
|
-
|
|
275
|
+
if (!doc[`${prePath}${nPath}`][nMethod]) {
|
|
276
|
+
doc[`${prePath}${nPath}`][nMethod] = [];
|
|
263
277
|
}
|
|
264
278
|
if (this.options) {
|
|
265
|
-
doc[`${prePath}${nPath}`][nMethod]
|
|
279
|
+
doc[`${prePath}${nPath}`][nMethod].push({
|
|
266
280
|
description: this.options.description,
|
|
267
281
|
name: this.options.name,
|
|
268
282
|
identifier: this.options.identifier ? this.options.identifier : `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
|
|
@@ -274,18 +288,23 @@ class RouterHandler {
|
|
|
274
288
|
query: this.options.request.query,
|
|
275
289
|
} : undefined,
|
|
276
290
|
response: typeof this.options.response === "boolean" ? this.options.response : this.options.response ? {
|
|
277
|
-
body: this.options.response.body
|
|
291
|
+
body: this.options.response.body,
|
|
292
|
+
bodyMode: this.options.response.bodyMode,
|
|
293
|
+
headers: this.options.response.headers,
|
|
294
|
+
headersMode: this.options.response.headersMode,
|
|
295
|
+
middleware: this.options.response.middleware,
|
|
296
|
+
status: this.options.response.status
|
|
278
297
|
} : undefined
|
|
279
|
-
};
|
|
298
|
+
});
|
|
280
299
|
} else {
|
|
281
|
-
doc[`${prePath}${nPath}`][nMethod]
|
|
300
|
+
doc[`${prePath}${nPath}`][nMethod].push({
|
|
282
301
|
description: undefined,
|
|
283
302
|
name: undefined,
|
|
284
303
|
identifier: `${prePath}${nPath}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
|
|
285
304
|
policy: undefined,
|
|
286
305
|
request: undefined,
|
|
287
306
|
response: undefined
|
|
288
|
-
};
|
|
307
|
+
});
|
|
289
308
|
}
|
|
290
309
|
}
|
|
291
310
|
return doc;
|
|
@@ -293,6 +312,9 @@ class RouterHandler {
|
|
|
293
312
|
|
|
294
313
|
public async invoke(req: Request, res: Response, pathTokens: PathPart[], prePathTokens: PathPartToken[]): Promise<boolean> {
|
|
295
314
|
for (let i = 0; i < this.handler.length; i++) {
|
|
315
|
+
if (res.headersSent) {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
296
318
|
const h = this.handler[i];
|
|
297
319
|
if (isMinimalRouter(h)) {
|
|
298
320
|
//if (h instanceof Router) {
|
|
@@ -726,31 +748,48 @@ export async function APIRouter(options: APIRouterOptions, logger?: Logger): Pro
|
|
|
726
748
|
}
|
|
727
749
|
const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
|
|
728
750
|
const apiPath = options.path !== undefined ? options.path : "";
|
|
729
|
-
return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger, options.ignore);
|
|
751
|
+
return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger, options.ignore, options.loader, options.extensions);
|
|
730
752
|
}
|
|
731
753
|
|
|
732
754
|
type UseCallArg = [Handler | Handler[] | MinimalRouter, string | undefined, Method | undefined, RouterHandlerOptions];
|
|
733
755
|
|
|
756
|
+
function isIgnored(f: string, ignore?: Array<string | RegExp>): boolean {
|
|
757
|
+
if (!ignore) {
|
|
758
|
+
return false;
|
|
759
|
+
}
|
|
760
|
+
for (const i of ignore) {
|
|
761
|
+
if (i instanceof RegExp && i.test(f)) {
|
|
762
|
+
return true;
|
|
763
|
+
} else if (i === f) {
|
|
764
|
+
return true;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
return false;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const DEFAULTAPIValidExtensions = new Set([".mjsx", ".mts", ".mjs", ".tsx", ".jsx", ".ts", ".js"]);
|
|
771
|
+
|
|
734
772
|
async function traverseAPIRouteDir(
|
|
735
773
|
featureName: string,
|
|
736
774
|
dirname: string,
|
|
737
775
|
basePath = "/",
|
|
738
|
-
router: Router = new Router(), logger?: Logger, ignore?: Array<string
|
|
776
|
+
router: Router = new Router(), logger?: Logger, ignore?: Array<string | RegExp>, importFN?: (path: string) => Promise<any>, extensions?: string[]): Promise<Router> {
|
|
739
777
|
if (logger) {
|
|
740
778
|
logger.trace("loading routes from [%s]", dirname);
|
|
741
779
|
}
|
|
742
|
-
const
|
|
743
|
-
const
|
|
744
|
-
const
|
|
780
|
+
const VALID_EXTENSION = extensions ? new Set(extensions) : DEFAULTAPIValidExtensions;
|
|
781
|
+
const files = readdirSync(dirname).filter(f => !isIgnored(f, ignore));
|
|
782
|
+
const dirs = files.filter(f => statSync(join(dirname, f)).isDirectory());
|
|
783
|
+
const methods = files.filter(f => !statSync(join(dirname, f)).isDirectory());
|
|
745
784
|
|
|
746
785
|
const postFolder: UseCallArg[] = [];
|
|
747
786
|
|
|
748
787
|
for (const f of methods) {
|
|
749
788
|
const { name, ext } = parse(f);
|
|
750
|
-
if (
|
|
789
|
+
if (VALID_EXTENSION.has(ext) && name.slice(-2) !== ".d") {
|
|
751
790
|
const filePath = join(dirname, f);
|
|
752
791
|
//console.log("dirname=%s f=%s", dirname, f);
|
|
753
|
-
let route: APIRoute = await import(filePath);
|
|
792
|
+
let route: APIRoute = importFN ? await importFN(filePath) : await import(filePath);
|
|
754
793
|
//if ((route as any).default && (route as any).__esModule === true) {
|
|
755
794
|
if ((route as any).default) {
|
|
756
795
|
route = (route as any).default;
|
|
@@ -762,19 +801,19 @@ async function traverseAPIRouteDir(
|
|
|
762
801
|
//const ___filePath = filePath + ext;
|
|
763
802
|
const ___filePath = filePath;
|
|
764
803
|
//let routeMethods: Method[] = [name] as Method[];
|
|
765
|
-
let routeMethod: Method | "use" | "USE" = name as Method;
|
|
804
|
+
let routeMethod: Method[] | Method | "use" | "USE" = name as Method;
|
|
766
805
|
if (typeof route === "function") {
|
|
767
806
|
route = {
|
|
768
807
|
handler: route
|
|
769
808
|
} as any;
|
|
770
809
|
} else {
|
|
771
|
-
if (typeof route.method !== "undefined" && (
|
|
810
|
+
if (typeof route.method !== "undefined" && (!(route.method instanceof Array) && (typeof route.method !== "string"))) {
|
|
772
811
|
//throw new Error(`${resolve(dirname, name)} doesn't export method as a string or string array`);
|
|
773
812
|
throw new Error(`${resolve(dirname, name)} doesnt export method as a string`);
|
|
774
813
|
} else if (typeof route.method !== "undefined") {
|
|
775
814
|
routeMethod = route.method;//route.method instanceof Array ? route.method : [route.method];
|
|
776
815
|
}
|
|
777
|
-
if (typeof route.path !== "string" && typeof route.path !== "undefined"
|
|
816
|
+
if (typeof route.path !== "string" && typeof route.path !== "undefined" && route.path !== null && !(route.path instanceof Array)) {
|
|
778
817
|
//throw new Error(`${resolve(dirname, name)} doesn't export path as a string or a string array`);
|
|
779
818
|
throw new Error(`${resolve(dirname, name)} doesnt export path as a string`);
|
|
780
819
|
}
|
|
@@ -794,51 +833,54 @@ async function traverseAPIRouteDir(
|
|
|
794
833
|
if (route.ignore !== undefined && route.ignore === true) {
|
|
795
834
|
continue;
|
|
796
835
|
}
|
|
797
|
-
//
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
//const p = paths[i];
|
|
801
|
-
if (typeof p !== "string" || !p) {
|
|
802
|
-
throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
|
|
836
|
+
//console.dir(route);
|
|
837
|
+
if (route.init) {
|
|
838
|
+
await route.init(route);
|
|
803
839
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
840
|
+
//console.dir(route);
|
|
841
|
+
const p = route.path === undefined ?
|
|
842
|
+
route.method && route.method.indexOf(name as Method) === -1 ?
|
|
843
|
+
`${name}` : "/"
|
|
844
|
+
: route.path;
|
|
808
845
|
|
|
809
|
-
|
|
846
|
+
/*if (p !== null && (typeof p !== "string" && !p)) {
|
|
847
|
+
throw new Error(`${resolve(dirname, name)} doesnt export path as a string or a string array`);
|
|
848
|
+
}*/
|
|
849
|
+
const paths = p instanceof Array ? p : [p];
|
|
850
|
+
const methods = routeMethod instanceof Array ? routeMethod : [routeMethod];
|
|
810
851
|
|
|
811
|
-
|
|
852
|
+
for (const method of methods) {
|
|
853
|
+
for (const pathsP of paths) {
|
|
854
|
+
const path = pathsP === null ? undefined : normalizePath(`${basePath}${pathsP && pathsP !== "/" ? `/${pathsP}` : pathsP}`)
|
|
812
855
|
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
router.use(...useCallArgs);
|
|
856
|
+
if (route.identifier && route.identifier === "__prototype__" || route.identifier === "__proto__") {
|
|
857
|
+
throw new Error(`invalid feature name ${route.identifier}`);
|
|
858
|
+
}
|
|
859
|
+
const useCallArgs: UseCallArg = [route.handler, path, method !== "use" && method !== "USE" ? method : undefined, {
|
|
860
|
+
identifier: route.identifier,
|
|
861
|
+
apiName: route.apiName,
|
|
862
|
+
name: route.name,
|
|
863
|
+
description: route.description,
|
|
864
|
+
parser: route.parser,
|
|
865
|
+
middleware: route.middleware,
|
|
866
|
+
session: route.session,
|
|
867
|
+
policy: route.policy,
|
|
868
|
+
request: route.request,
|
|
869
|
+
response: route.response !== undefined ? route.response : true // ResponseHandler added by default to an APIRoute
|
|
870
|
+
}];
|
|
871
|
+
//console.dir(useCallArgs);
|
|
872
|
+
if (route.postFolder) {
|
|
873
|
+
postFolder.push(useCallArgs);
|
|
874
|
+
} else {
|
|
875
|
+
router.use(...useCallArgs);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
836
878
|
}
|
|
837
879
|
}
|
|
838
880
|
}
|
|
839
881
|
for (const f of dirs) {
|
|
840
882
|
const { name } = parse(f);
|
|
841
|
-
router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger, ignore);
|
|
883
|
+
router = await traverseAPIRouteDir(`${featureName}_${name}`.toUpperCase(), join(dirname, f), `${basePath}/${name}`, router, logger, ignore, importFN, extensions);
|
|
842
884
|
}
|
|
843
885
|
for (const post of postFolder) {
|
|
844
886
|
router.use(...post);
|
|
@@ -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
|
|
92
|
+
verify(args: { token?: string | null; req: Request; res: Response }): Promise<Session | null>;
|
|
91
93
|
};
|
|
92
|
-
options?:
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
};
|
|
@@ -272,7 +288,7 @@ export interface RouteJSONDoc extends RouteOptions {
|
|
|
272
288
|
|
|
273
289
|
export interface RouterJSONDoc {
|
|
274
290
|
[path: string]: {
|
|
275
|
-
[method: string]: RouteJSONDoc
|
|
291
|
+
[method: string]: RouteJSONDoc[]
|
|
276
292
|
}
|
|
277
293
|
}
|
|
278
294
|
|
|
@@ -348,18 +364,22 @@ export function isMinimalRouter(obj: any) {
|
|
|
348
364
|
* ```
|
|
349
365
|
*/
|
|
350
366
|
export interface APIRoute extends RouterHandlerOptions {
|
|
351
|
-
postFolder?: boolean
|
|
352
|
-
|
|
353
|
-
|
|
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 {
|
|
359
377
|
dirname: string;
|
|
360
378
|
apiName?: string;
|
|
361
379
|
path?: string;
|
|
362
|
-
ignore?: Array<string>;
|
|
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> = {
|
|
@@ -368,7 +388,12 @@ export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
|
|
|
368
388
|
dirname: "string",
|
|
369
389
|
apiName: "string?",
|
|
370
390
|
path: "string?",
|
|
371
|
-
ignore:
|
|
391
|
+
ignore: {
|
|
392
|
+
type: "array?",
|
|
393
|
+
arrayType: "string|RegExp"
|
|
394
|
+
},
|
|
395
|
+
loader: "function?",
|
|
396
|
+
extensions: "string[]?",
|
|
372
397
|
}
|
|
373
398
|
};
|
|
374
399
|
|
|
@@ -377,14 +402,19 @@ export const APIRouteSchema: Schema<APIRoute> = {
|
|
|
377
402
|
properties: {
|
|
378
403
|
...RouterHandlerOptionsSchema.properties,
|
|
379
404
|
postFolder: "boolean?",
|
|
380
|
-
|
|
381
|
-
|
|
405
|
+
basePath: "string?",
|
|
406
|
+
method: "string?|string[]?",
|
|
407
|
+
path: {
|
|
408
|
+
type: "string?|string[]?",
|
|
409
|
+
allowNull: true
|
|
410
|
+
},
|
|
382
411
|
ignore: "boolean?",
|
|
383
412
|
handler: {
|
|
384
413
|
type: "function[]!|object",
|
|
385
414
|
properties: MinimalRouterSchema.properties,
|
|
386
415
|
mode: MinimalRouterSchema.mode
|
|
387
|
-
}
|
|
416
|
+
},
|
|
417
|
+
init: "function?"
|
|
388
418
|
}
|
|
389
419
|
};
|
|
390
420
|
|
|
@@ -486,6 +516,8 @@ export interface Response<Request extends IncomingMessage = IncomingMessage> ext
|
|
|
486
516
|
addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse;
|
|
487
517
|
setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse;
|
|
488
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>;
|
|
489
521
|
text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
|
|
490
522
|
redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
|
|
491
523
|
}
|
|
@@ -517,6 +549,26 @@ export class Response<Request extends IncomingMessage = IncomingMessage> extends
|
|
|
517
549
|
body: html
|
|
518
550
|
})
|
|
519
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
|
+
}
|
|
520
572
|
async text(text: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
|
|
521
573
|
return this.asyncEnd({
|
|
522
574
|
status: status !== undefined ? status : 200,
|
|
@@ -722,17 +774,41 @@ export function newURL(input: string): URL {
|
|
|
722
774
|
/*
|
|
723
775
|
remove /+ at the start of the input before using new URL ( it changes the host )
|
|
724
776
|
*/
|
|
777
|
+
const slashIndex = getSlashIndex(input);
|
|
778
|
+
const removedSlashes = input.substring(0, slashIndex - 1);
|
|
779
|
+
const ret = new URL(input.substring(slashIndex - 1), "http://localhost");
|
|
780
|
+
// restore path
|
|
781
|
+
ret.pathname = `${slashIndex > 0 ? removedSlashes : ""}${ret.pathname}`;
|
|
782
|
+
return ret;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
*
|
|
787
|
+
* @param input a url.pathname
|
|
788
|
+
* @returns the pathname ignoring start slashes for example if sended "///page/hi" will return /page/hi
|
|
789
|
+
*/
|
|
790
|
+
export function removeStartingBackSlashes(input: string): string {
|
|
791
|
+
/*
|
|
792
|
+
remove /+ at the start of the input before using new URL ( it changes the host )
|
|
793
|
+
*/
|
|
794
|
+
const slashIndex = getSlashIndex(input);
|
|
795
|
+
|
|
796
|
+
return input.substring(slashIndex - 1);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
*
|
|
801
|
+
* @param input a url.pathname
|
|
802
|
+
* @returns the first real slashindex for example if sended "///page/hi" will return 4
|
|
803
|
+
*/
|
|
804
|
+
export function getSlashIndex(input: string): number {
|
|
725
805
|
let slashIndex = 0
|
|
726
806
|
for (slashIndex = 0; slashIndex < input.length; slashIndex++) {
|
|
727
807
|
if (input.charAt(slashIndex) !== "/") {
|
|
728
808
|
break;
|
|
729
809
|
}
|
|
730
810
|
}
|
|
731
|
-
|
|
732
|
-
const ret = new URL(input.substring(slashIndex), "http://localhost");
|
|
733
|
-
// restore path
|
|
734
|
-
ret.pathname = `${slashIndex > 0 ? removedSlashes : ""}${ret.pathname}`;
|
|
735
|
-
return ret;
|
|
811
|
+
return slashIndex;
|
|
736
812
|
}
|
|
737
813
|
|
|
738
814
|
// adds "/" to the final of path
|
|
@@ -783,6 +859,7 @@ export interface WebSocketServerOptions {
|
|
|
783
859
|
onConnection?: (req: WebSocketClient) => void;
|
|
784
860
|
onMessage?: (req: WebSocketClient, data: string | undefined | null) => void;
|
|
785
861
|
onDisconnect?: (req: WebSocketClient) => void;
|
|
862
|
+
onError?: (req: WebSocketClient, error: Error) => void;
|
|
786
863
|
}
|
|
787
864
|
|
|
788
865
|
export interface WebSocketClient {
|