orange-auth 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) Mathieu Dery.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) Mathieu Dery.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE
@@ -1,3 +1,6 @@
1
+ import type { SerializeOptions } from "cookie";
2
+ import type { IProvider } from "../providers/IProvider";
3
+ import type { IStrategy } from "../strategies/IStrategy";
1
4
  /**
2
5
  * This is a Promise, or not...
3
6
  */
@@ -8,4 +11,87 @@ export type MaybePromise<T> = T | Promise<T>;
8
11
  export interface Session extends Record<string, unknown> {
9
12
  id: string;
10
13
  }
14
+ /**
15
+ * Parameters for the custom callbacks
16
+ */
17
+ type CallbackParams = {
18
+ /**
19
+ * The current token
20
+ */
21
+ token: string;
22
+ /**
23
+ * The current deserialized token
24
+ */
25
+ session: Session;
26
+ /**
27
+ * TThe request's headers
28
+ */
29
+ headers: Headers;
30
+ };
31
+ /**
32
+ * Auth Configuration props.
33
+ */
34
+ export type ConfigOptionsProps = Readonly<{
35
+ /**
36
+ * All the available providers.
37
+ * If multiple instance of a single provider are used, the order does matter.
38
+ */
39
+ providers: IProvider[];
40
+ /**
41
+ * Your secret key.
42
+ */
43
+ secret: string | {
44
+ publicKey: string;
45
+ privateKey: string;
46
+ };
47
+ /**
48
+ * A custom name for the cookie.
49
+ * Otherwise, the default name will be `orange.auth`
50
+ */
51
+ cookieName?: string;
52
+ /**
53
+ * The strategy to be used.
54
+ */
55
+ strategy: IStrategy;
56
+ /**
57
+ * This should be the url path that your auth is set up on, including the action and provider variables.
58
+ * @example
59
+ * ```js
60
+ * const app = express();
61
+ *
62
+ * const { handler } = CreateAuth({
63
+ * basePath: "/api/auth/:action/:provider",
64
+ * ...
65
+ * });
66
+ *
67
+ * app.all("/api/auth/{*auth}", createHandler(handler)());
68
+ * ```
69
+ */
70
+ basePath: string;
71
+ /**
72
+ * Cookie serialization options. see [MDN Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies)
73
+ */
74
+ cookieSettings?: SerializeOptions;
75
+ /**
76
+ * Custom callbacks
77
+ */
78
+ callbacks?: {
79
+ /**
80
+ * Custom login callback. This is ran after logging in with the provider.
81
+ * This can accept 2 return types: a boolean that indicates if the login is valid,
82
+ * or a url which will redirect the user.
83
+ * @param params An object containing the token, session and headers of a request.
84
+ * @returns a boolean that indicates if the login is valid,
85
+ * or a url which will redirect the user.
86
+ */
87
+ login?: (params: CallbackParams) => MaybePromise<boolean | string>;
88
+ /**
89
+ * Custom logout callback. This is ran before logging out with the strategy.
90
+ * @param params An object containing the token, session and headers of a request.
91
+ * @returns Nothing, or an empty promise.
92
+ */
93
+ logout?: (params: CallbackParams) => MaybePromise<void>;
94
+ };
95
+ }>;
96
+ export {};
11
97
  //# sourceMappingURL=globals.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"globals.d.ts","sourceRoot":"","sources":["../../src/@types/globals.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7C;;GAEG;AACH,MAAM,WAAW,OAAQ,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACpD,EAAE,EAAE,MAAM,CAAC;CACd"}
1
+ {"version":3,"file":"globals.d.ts","sourceRoot":"","sources":["../../src/@types/globals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7C;;GAEG;AACH,MAAM,WAAW,OAAQ,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACpD,EAAE,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,KAAK,cAAc,GAAG;IAClB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IACjB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;IACtC;;;OAGG;IACH,SAAS,EAAE,SAAS,EAAE,CAAC;IAEvB;;OAEG;IACH,MAAM,EAAE,MAAM,GAAG;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;IAE3D;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,QAAQ,EAAE,SAAS,CAAC;IAEpB;;;;;;;;;;;;;OAaG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,cAAc,CAAC,EAAE,gBAAgB,CAAC;IAElC;;OAEG;IACH,SAAS,CAAC,EAAE;QACR;;;;;;;WAOG;QACH,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,cAAc,KAAK,YAAY,CAAC,OAAO,GAAG,MAAM,CAAC,CAAC;QAEnE;;;;WAIG;QACH,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,cAAc,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;KAC3D,CAAC;CACL,CAAC,CAAC"}
@@ -1,6 +1,13 @@
1
- import type { ConfigOptionsProps } from "../lib";
1
+ import type { RequiredDeep } from "type-fest";
2
+ import type { ConfigOptionsProps } from "./globals";
2
3
  /**
3
4
  * Internally used version of the options
4
5
  */
5
- export type ConfigOptions = Required<Omit<ConfigOptionsProps, "basePath">>;
6
+ export type ConfigOptions = Omit<RequiredDeep<Omit<ConfigOptionsProps, "basePath">>, "cookieSettings"> & {
7
+ cookieSettings: NonNullable<ConfigOptionsProps["cookieSettings"]>;
8
+ };
9
+ /**
10
+ * Maybe there is a value, maybe not 🤷‍♂️
11
+ */
12
+ export type Maybe<T> = T | null | undefined;
6
13
  //# sourceMappingURL=internals.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internals.d.ts","sourceRoot":"","sources":["../../src/@types/internals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAEjD;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC,IAAI,CAAC,kBAAkB,EAAE,UAAU,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"internals.d.ts","sourceRoot":"","sources":["../../src/@types/internals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,kBAAkB,EAAE,UAAU,CAAC,CAAC,EAAE,gBAAgB,CAAC,GAAG;IAErG,cAAc,EAAE,WAAW,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC,CAAC;CACrE,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC"}
@@ -1,2 +1,3 @@
1
1
  export * from "./jwt";
2
+ export * from "./urlencodedToJson";
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/functions/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/functions/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,oBAAoB,CAAC"}
@@ -1 +1,2 @@
1
1
  export * from "./jwt";
2
+ export * from "./urlencodedToJson";
@@ -0,0 +1,2 @@
1
+ export declare function urlencodedToJson<T extends object = object>(value: string): T;
2
+ //# sourceMappingURL=urlencodedToJson.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urlencodedToJson.d.ts","sourceRoot":"","sources":["../../src/functions/urlencodedToJson.ts"],"names":[],"mappings":"AAAA,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAS5E"}
@@ -0,0 +1,8 @@
1
+ export function urlencodedToJson(value) {
2
+ return Object.fromEntries(value
3
+ .trim()
4
+ .split("&")
5
+ .map((s) => s.split("="))
6
+ .filter((pair) => pair.length === 2)
7
+ .map((pair) => pair.map(decodeURIComponent)));
8
+ }
package/dist/lib.d.ts CHANGED
@@ -1,63 +1,46 @@
1
+ import type { Maybe } from "./@types/internals";
1
2
  import type { Session } from "./@types/globals";
2
- import type { IStrategy } from "./strategies/IStrategy";
3
- import type { IProvider } from "./providers/IProvider";
4
- import { type SerializeOptions } from "cookie";
5
- type Maybe<T> = T | null | undefined;
6
3
  /**
7
- * Auth Configuration props.
4
+ * Initializes the auth. This should be called once per backend.
5
+ * @param req Something that has a `headers` field; either a Headers instance, or just a plain object.
6
+ * @returns A session if found and valid, or `null`.
8
7
  */
9
- export type ConfigOptionsProps = Readonly<{
10
- /**
11
- * All the available providers.
12
- * If multiple instance of a single provider are used, the order does matter.
13
- */
14
- providers: IProvider[];
15
- /**
16
- * Your secret key.
17
- */
8
+ export declare const CreateAuth: (config: Readonly<{
9
+ providers: import("./providers").IProvider[];
18
10
  secret: string | {
19
11
  publicKey: string;
20
12
  privateKey: string;
21
13
  };
22
- /**
23
- * A custom name for the cookie.
24
- * Otherwise, the default name will be `orange.auth`
25
- */
26
14
  cookieName?: string;
27
- /**
28
- * The strategy to be used.
29
- */
30
- strategy: IStrategy;
31
- /**
32
- * This should be the url path that your auth is set up on, including the action and provider variables.
33
- * @example
34
- * ```js
35
- * const app = express();
36
- *
37
- * const { handler } = CreateAuth({
38
- * basePath: "/api/auth/:action/:provider",
39
- * ...
40
- * });
41
- *
42
- * app.all("/api/auth/{*auth}", createHandler(handler)());
43
- * ```
44
- */
15
+ strategy: import("./strategies").IStrategy;
45
16
  basePath: string;
17
+ cookieSettings?: import("cookie").SerializeOptions;
18
+ callbacks?: {
19
+ login?: (params: {
20
+ token: string;
21
+ session: Session;
22
+ headers: Headers;
23
+ }) => import(".").MaybePromise<boolean | string>;
24
+ logout?: (params: {
25
+ token: string;
26
+ session: Session;
27
+ headers: Headers;
28
+ }) => import(".").MaybePromise<void>;
29
+ };
30
+ }>) => {
46
31
  /**
47
- * Cookie serialization options. see [MDN Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies)
32
+ * Universal handler route. You can use this with the `createHandler()` method
33
+ * @returns
48
34
  */
49
- cookieSettings?: SerializeOptions;
50
- }>;
51
- /**
52
- * Access a user's session.
53
- * @param req Something that has a `headers` field; either a Headers instance, or just a plain object.
54
- * @returns A session if found and valid, or `null`.
55
- */
56
- export declare const CreateAuth: (config: ConfigOptionsProps) => {
57
35
  handler: () => (req: Request, _: Universal.Context, runtime: import("@universal-middleware/core").RuntimeAdapter) => Promise<Response>;
36
+ /**
37
+ * Deserialize a user's session.
38
+ * @param globalCfg The global auth config
39
+ * @param req An object having a headers field
40
+ * @returns A user's token and session, if found and valid
41
+ */
58
42
  getSession: <T extends Session = Session>(req: {
59
43
  headers: Maybe<Headers | Record<string, string>>;
60
44
  }) => Promise<T | null>;
61
45
  };
62
- export {};
63
46
  //# sourceMappingURL=lib.d.ts.map
package/dist/lib.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src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vB,CAAC;;;;;;;IAOhB;;;OAGG;;IAwGH;;;;;OAKG;iBACU,CAAC,SAAS,OAAO,iBAAiB;QAAE,OAAO,EAAE,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;KAAE,KAEnC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;CAUxF,CAAC"}
package/dist/lib.js CHANGED
@@ -1,24 +1,47 @@
1
1
  import Cookies from "universal-cookie";
2
- import { assign, find, isNil } from "lodash-es";
3
2
  import { serialize as cookie } from "cookie";
3
+ import { assign, find, isNil, isString, merge } from "lodash-es";
4
4
  import { params } from "@universal-middleware/core";
5
- if (!globalThis.crypto) {
6
- /**
7
- * Polyfill needed if this code runs on node18
8
- */
9
- Object.defineProperty(globalThis, "crypto", {
10
- value: await import("node:crypto").then((crypto) => crypto.webcrypto),
11
- writable: false,
12
- configurable: true,
13
- });
14
- }
15
5
  /**
16
- * Access a user's session.
6
+ * Deserialize a user's session based of the headers
7
+ * @param globalCfg The global auth config
8
+ * @param req An object having a headers field
9
+ * @returns A user's token and session, if found and valid
10
+ */
11
+ const getSession = async (globalCfg, req) => {
12
+ if (isNil(req.headers))
13
+ return {
14
+ session: null,
15
+ token: null,
16
+ };
17
+ // Find the correct cookie header
18
+ const cookieHeader = req.headers instanceof Headers ? req.headers.get("cookie") : req.headers["cookie"];
19
+ const cookie = new Cookies(cookieHeader);
20
+ if (isNil(cookie))
21
+ return {
22
+ session: null,
23
+ token: null,
24
+ };
25
+ // Tries to extract the specific cookie.
26
+ const token = cookie.get(globalCfg.cookieName);
27
+ if (isNil(token))
28
+ return {
29
+ session: null,
30
+ token: null,
31
+ };
32
+ // Tries to deserialize it
33
+ return {
34
+ session: (await globalCfg.strategy.deserialize(token, globalCfg)),
35
+ token: token,
36
+ };
37
+ };
38
+ /**
39
+ * Initializes the auth. This should be called once per backend.
17
40
  * @param req Something that has a `headers` field; either a Headers instance, or just a plain object.
18
41
  * @returns A session if found and valid, or `null`.
19
42
  */
20
43
  export const CreateAuth = ((config) => {
21
- const { secret, strategy, cookieName, providers, cookieSettings, basePath } = config;
44
+ const { secret, strategy, cookieName, providers, cookieSettings, basePath, callbacks } = config;
22
45
  if (isNil(secret)) {
23
46
  throw new Error('[ERROR]: Auth secret missing! Make sure to set the "secret" variable in the auth\'s config.');
24
47
  }
@@ -39,8 +62,13 @@ export const CreateAuth = ((config) => {
39
62
  secure: true,
40
63
  maxAge: 3600,
41
64
  },
65
+ callbacks: merge({}, { login: () => ({}), logout: () => ({}) }, callbacks),
42
66
  };
43
67
  return {
68
+ /**
69
+ * Universal handler route. You can use this with the `createHandler()` method
70
+ * @returns
71
+ */
44
72
  handler: () => async (req, _, runtime) => {
45
73
  // Tries to get the action and provider info from the url
46
74
  const routeParams = params(req, runtime, basePath);
@@ -61,14 +89,48 @@ export const CreateAuth = ((config) => {
61
89
  // If failed, return Bad Request response
62
90
  if (isNil(token))
63
91
  return new Response(null, { status: 400 });
92
+ const params = await getSession(globalCfg, {
93
+ // The cookie header is faked here, since the request does not have any token yet.
94
+ headers: { cookie: cookie(globalCfg.cookieName, token) },
95
+ });
96
+ // If there is no session at this point, something as gone wrong
97
+ if (isNil(params.session) || isNil(params.token)) {
98
+ console.error("[AUTH ERROR]: Missing session after login");
99
+ return new Response("internal server error", { status: 500 });
100
+ }
101
+ // Run the login callback
102
+ const customRes = await globalCfg.callbacks.login({
103
+ headers: req.headers,
104
+ token: params.token,
105
+ session: params.session,
106
+ });
107
+ // If the result is false, fail the login
108
+ if (customRes === false) {
109
+ return new Response("Bad Request", { status: 400 });
110
+ }
111
+ // If the result is a string, assume it is a redirection path
112
+ if (isString(customRes)) {
113
+ const headers = new Headers();
114
+ headers.set("Location", customRes);
115
+ return new Response(null, { status: 308, headers });
116
+ }
64
117
  // Creates the set-cookie header
65
118
  const headers = new Headers();
66
119
  headers.set("Set-Cookie", cookie(globalCfg.cookieName, token, globalCfg.cookieSettings));
67
- // And returns it
120
+ // And return it
68
121
  return new Response(null, { status: 200, headers });
69
122
  }
70
123
  case "logout": {
71
- // Use the strategy to logout
124
+ const params = await getSession(globalCfg, req);
125
+ // If there is no session, no need to call the callback
126
+ if (!isNil(params.session) && !isNil(params.token)) {
127
+ await globalCfg.callbacks.logout({
128
+ headers: req.headers,
129
+ token: params.token,
130
+ session: params.session,
131
+ });
132
+ }
133
+ // Use the strategy to logout
72
134
  await globalCfg.strategy.logOut(req, globalCfg);
73
135
  // Clears the header.
74
136
  const headers = new Headers();
@@ -86,22 +148,14 @@ export const CreateAuth = ((config) => {
86
148
  return new Response("Page not found", { status: 404 });
87
149
  }
88
150
  },
89
- getSession: async (req) => {
90
- if (isNil(req.headers))
91
- return null;
92
- // Here, it always outputs the original state
93
- // console.log(ConfigManager.get());
94
- // Find the correct cookie header
95
- const cookieHeader = req.headers instanceof Headers ? req.headers.get("cookie") : req.headers["cookie"];
96
- const cookie = new Cookies(cookieHeader);
97
- if (isNil(cookie))
98
- return null;
99
- // Tries to extract the specific cookie.
100
- const token = cookie.get(globalCfg.cookieName);
101
- if (isNil(token))
102
- return null;
103
- // Tries to deserialize it
104
- return globalCfg.strategy.deserialize(token, globalCfg);
105
- },
151
+ /**
152
+ * Deserialize a user's session.
153
+ * @param globalCfg The global auth config
154
+ * @param req An object having a headers field
155
+ * @returns A user's token and session, if found and valid
156
+ */
157
+ getSession: (req) =>
158
+ // Only returns the session
159
+ getSession(globalCfg, req).then((doc) => doc.session),
106
160
  };
107
161
  });
@@ -1,6 +1,6 @@
1
1
  import { IProvider } from "./IProvider";
2
- import type { Session, MaybePromise } from "../@types/globals";
3
2
  import type { ConfigOptions } from "../@types/internals";
3
+ import type { Session, MaybePromise } from "../@types/globals";
4
4
  /**
5
5
  * Configuration options of the Credentials provider
6
6
  */
@@ -28,7 +28,6 @@ export type CredentialsConfig<TCredentials extends string> = Readonly<{
28
28
  export declare class Credentials<TCredentials extends string = string> extends IProvider {
29
29
  private config;
30
30
  constructor(config: CredentialsConfig<TCredentials>);
31
- getSession(): Promise<Session | null>;
32
31
  logIn(req: Request, globalCfg: ConfigOptions): Promise<string | null>;
33
32
  }
34
33
  //# sourceMappingURL=Credentials.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Credentials.d.ts","sourceRoot":"","sources":["../../src/providers/Credentials.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,iBAAiB,CAAC,YAAY,SAAS,MAAM,IAAI,QAAQ,CAAC;IAClE;;;OAGG;IACH,IAAI,CAAC,EAAE,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IACrC;;OAEG;IACH,WAAW,EAAE,YAAY,EAAE,CAAC;IAC5B;;;;;OAKG;IACH,SAAS,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,KAAK,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;CAC1F,CAAC,CAAC;AAEH;;GAEG;AACH,qBAAa,WAAW,CAAC,YAAY,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,SAAS;IAC5E,OAAO,CAAC,MAAM,CAAkC;gBAEpC,MAAM,EAAE,iBAAiB,CAAC,YAAY,CAAC;IAK7B,UAAU,IAAI,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAIrC,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAW9F"}
1
+ {"version":3,"file":"Credentials.d.ts","sourceRoot":"","sources":["../../src/providers/Credentials.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE/D;;GAEG;AACH,MAAM,MAAM,iBAAiB,CAAC,YAAY,SAAS,MAAM,IAAI,QAAQ,CAAC;IAClE;;;OAGG;IACH,IAAI,CAAC,EAAE,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;IACrC;;OAEG;IACH,WAAW,EAAE,YAAY,EAAE,CAAC;IAC5B;;;;;OAKG;IACH,SAAS,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,KAAK,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;CAC1F,CAAC,CAAC;AAEH;;GAEG;AACH,qBAAa,WAAW,CAAC,YAAY,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,SAAS;IAC5E,OAAO,CAAC,MAAM,CAAkC;gBAEpC,MAAM,EAAE,iBAAiB,CAAC,YAAY,CAAC;IAK7B,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAgC9F"}
@@ -1,5 +1,6 @@
1
1
  import { isNil } from "lodash-es";
2
2
  import { IProvider } from "./IProvider";
3
+ import { urlencodedToJson } from "../functions";
3
4
  /**
4
5
  * Provider used to login a user using basic credentials.
5
6
  */
@@ -9,17 +10,33 @@ export class Credentials extends IProvider {
9
10
  super(config.name ?? "credentials");
10
11
  this.config = config;
11
12
  }
12
- async getSession() {
13
- throw new Error("This should never be used");
14
- }
15
13
  async logIn(req, globalCfg) {
16
- // We assume the body is json here, might change that later to be more flexible
17
- const body = (await req.json());
14
+ const contentType = req.headers.get("Content-Type")?.split(";")[0] ?? "text/plain";
15
+ let body;
16
+ switch (contentType) {
17
+ case "application/json":
18
+ body = await req.json();
19
+ break;
20
+ case "application/x-www-urlencoded":
21
+ body = await req.text().then((urlencodedToJson));
22
+ break;
23
+ case "multipart/form-data":
24
+ const data = await req.formData();
25
+ body = Object.fromEntries(data);
26
+ break;
27
+ // fields should come from a form, so every un-supported types will be failing.
28
+ case "text/plain":
29
+ default:
30
+ return null;
31
+ }
18
32
  // Calls the user defined authorize callback
19
33
  const session = await this.config.authorize(body);
20
34
  if (isNil(session))
21
35
  return null;
22
36
  // Create a token
23
- return globalCfg.strategy.serialize(session, globalCfg);
37
+ return globalCfg.strategy.serialize(session, globalCfg).catch((err) => {
38
+ console.log(err);
39
+ return null;
40
+ });
24
41
  }
25
42
  }
@@ -1,4 +1,3 @@
1
- import type { Session } from "../@types/globals";
2
1
  import type { ConfigOptions } from "../@types/internals";
3
2
  /**
4
3
  * Available url callback actions.
@@ -18,8 +17,6 @@ declare abstract class IProvider {
18
17
  * The provider ID.
19
18
  */
20
19
  get ID(): string;
21
- /** @deprecated You can use the top level `getSession` instead. */
22
- abstract getSession(req: Request, globalCfg: ConfigOptions): Promise<Session | null>;
23
20
  /**
24
21
  * Login function. This is used to call all the login flows of each provider.
25
22
  * For now, the request's body **MUST** be JSON.
@@ -1 +1 @@
1
- {"version":3,"file":"IProvider.d.ts","sourceRoot":"","sources":["../../src/providers/IProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEzC;;;GAGG;AACH,uBAAe,SAAS;IACpB;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;gBAElB,EAAE,EAAE,MAAM;IAItB;;OAEG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED,kEAAkE;aAClD,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAE3F;;;;;OAKG;aACa,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CACxF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
1
+ {"version":3,"file":"IProvider.d.ts","sourceRoot":"","sources":["../../src/providers/IProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEzC;;;GAGG;AACH,uBAAe,SAAS;IACpB;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;gBAElB,EAAE,EAAE,MAAM;IAItB;;OAEG;IACH,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED;;;;;OAKG;aACa,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CACxF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -1,9 +1,28 @@
1
- import { type Session } from "../@types/globals";
1
+ import { type MaybePromise, type Session } from "../@types/globals";
2
2
  import type { ConfigOptions } from "../@types/internals";
3
+ /**
4
+ * Strategies callbacks
5
+ */
6
+ export type Callbacks = Partial<{
7
+ /**
8
+ * Pre-serialization callback. This can be used to add some steps to this process.
9
+ * @param session The session to be serialized.
10
+ * @returns A boolean representing if the serialization should occur.
11
+ */
12
+ serialize: (session: Session) => MaybePromise<boolean>;
13
+ /**
14
+ * Post-deserialization callback. This can be used to add some validation to this process.
15
+ * @param session The token that was deserialized.
16
+ * @returns A boolean representing if the deserialization is valid.
17
+ */
18
+ deserialize: (token: string, session: Session) => MaybePromise<boolean>;
19
+ }>;
3
20
  /**
4
21
  * A strategy is used to handle the creation, validation and accessing a user's session.
5
22
  */
6
23
  declare abstract class IStrategy {
24
+ protected callbacks: Callbacks;
25
+ constructor(callbacks: Callbacks);
7
26
  /**
8
27
  * Handles how a session token is generated.
9
28
  * @param session The validated session object.
@@ -1 +1 @@
1
- {"version":3,"file":"IStrategy.d.ts","sourceRoot":"","sources":["../../src/strategies/IStrategy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,uBAAe,SAAS;IACpB;;;;;OAKG;aACa,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAEtF;;;;;OAKG;aACa,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAE7F;;;;OAIG;aACa,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAChF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
1
+ {"version":3,"file":"IStrategy.d.ts","sourceRoot":"","sources":["../../src/strategies/IStrategy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC;IAC5B;;;;OAIG;IACH,SAAS,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,CAAC;IACvD;;;;OAIG;IACH,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,CAAC;CAC3E,CAAC,CAAC;AAEH;;GAEG;AACH,uBAAe,SAAS;IACpB,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;gBAEnB,SAAS,EAAE,SAAS;IAIhC;;;;;OAKG;aACa,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAEtF;;;;;OAKG;aACa,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAE7F;;;;OAIG;aACa,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAChF;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -3,5 +3,9 @@ import {} from "../@types/globals";
3
3
  * A strategy is used to handle the creation, validation and accessing a user's session.
4
4
  */
5
5
  class IStrategy {
6
+ callbacks;
7
+ constructor(callbacks) {
8
+ this.callbacks = callbacks;
9
+ }
6
10
  }
7
11
  export { IStrategy };
@@ -1,6 +1,6 @@
1
- import { IStrategy } from "./IStrategy";
2
1
  import type { SignOptions } from "jsonwebtoken";
3
2
  import type { Session } from "../@types/globals";
3
+ import { IStrategy, type Callbacks } from "./IStrategy";
4
4
  import type { ConfigOptions } from "../@types/internals";
5
5
  /**
6
6
  * Basic JWT strategy
@@ -10,7 +10,7 @@ declare class JWT extends IStrategy {
10
10
  * Forwarded standard JWT options
11
11
  */
12
12
  private signOptions;
13
- constructor(options?: SignOptions);
13
+ constructor(options?: SignOptions, callbacks?: Callbacks);
14
14
  serialize(session: Session, globalCfg: ConfigOptions): Promise<string>;
15
15
  deserialize(token: string, globalCfg: ConfigOptions): Promise<Session | null>;
16
16
  logOut(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../src/strategies/jwt.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,KAAK,EAAE,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;AAED,OAAO,EAAE,GAAG,EAAE,CAAC"}
@@ -1,18 +1,18 @@
1
- import { isString } from "lodash-es";
2
- import { IStrategy } from "./IStrategy";
1
+ import { isNil, isString } from "lodash-es";
3
2
  import { verify, sign } from "../functions/jwt";
3
+ import { IStrategy } from "./IStrategy";
4
4
  /**
5
5
  * Retrieves either the secret or a private key, depending on the used JWT algorithm
6
6
  * @param secret Secret key, or key pair
7
7
  * @returns The secret or private key
8
8
  */
9
- const secretOrPrivateKey = (secret) => isString(secret) ? secret : secret.privateKey;
9
+ const secretOrPrivateKey = (secret) => (isString(secret) ? secret : secret.privateKey);
10
10
  /**
11
11
  * Retrieves either the secret or a public key, depending on the used JWT algorithm
12
12
  * @param secret Secret key, or key pair
13
13
  * @returns The secret or public key
14
14
  */
15
- const secretOrPublicKey = (secret) => isString(secret) ? secret : secret.publicKey;
15
+ const secretOrPublicKey = (secret) => (isString(secret) ? secret : secret.publicKey);
16
16
  /**
17
17
  * Basic JWT strategy
18
18
  */
@@ -21,17 +21,27 @@ class JWT extends IStrategy {
21
21
  * Forwarded standard JWT options
22
22
  */
23
23
  signOptions;
24
- constructor(options = { expiresIn: "1h" }) {
25
- super();
24
+ constructor(options = { expiresIn: "1h" }, callbacks = {}) {
25
+ super(callbacks);
26
26
  this.signOptions = options;
27
27
  }
28
- serialize(session, globalCfg) {
28
+ async serialize(session, globalCfg) {
29
+ // If there is no callback set, we can just run normally, so fallback to true.
30
+ const shouldRun = await Promise.resolve(this.callbacks.serialize?.(session) ?? true);
31
+ if (!shouldRun) {
32
+ return Promise.reject("Serialize callback rejection");
33
+ }
29
34
  // Directly call the sign function, but make it async.
30
35
  return Promise.resolve(sign(session, secretOrPrivateKey(globalCfg.secret), this.signOptions));
31
36
  }
32
37
  deserialize(token, globalCfg) {
33
38
  // The verify function does everything for us, in this case.
34
- return verify(token, secretOrPublicKey(globalCfg.secret));
39
+ return verify(token, secretOrPublicKey(globalCfg.secret)).then(async (session) => {
40
+ if (isNil(session))
41
+ return null;
42
+ const isValid = await Promise.resolve(this.callbacks.deserialize?.(token, session) ?? true);
43
+ return isValid ? session : null;
44
+ });
35
45
  }
36
46
  logOut() {
37
47
  // Since a JWT does not have any data in a DB, there is nothing to do here.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orange-auth",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Simple modular auth library",
6
6
  "main": "dist/index.js",
@@ -19,7 +19,8 @@
19
19
  "./functions": "./dist/functions/index.js"
20
20
  },
21
21
  "scripts": {
22
- "build": "tsc"
22
+ "build": "tsc",
23
+ "test": "vitest"
23
24
  },
24
25
  "author": "Mathieu Dery mathieu.dery@bananastreaming.ca",
25
26
  "license": "MIT",
@@ -33,8 +34,10 @@
33
34
  "@types/node": "^24.0.15",
34
35
  "eslint-plugin-prettier": "^5.5.3",
35
36
  "tslib": "^2.8.1",
37
+ "type-fest": "^4.41.0",
36
38
  "typescript": "^5.8.3",
37
- "typescript-eslint": "^8.37.0"
39
+ "typescript-eslint": "^8.37.0",
40
+ "vitest": "^3.2.4"
38
41
  },
39
42
  "dependencies": {
40
43
  "@universal-middleware/core": "^0.4.8",