arkos 2.0.0-next.3 → 2.0.0-next.5
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/dist/cjs/app.js +2 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/components/arkos-policy/index.js +3 -1
- package/dist/cjs/components/arkos-policy/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +142 -5
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +25 -0
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js +276 -0
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js.map +1 -0
- package/dist/cjs/types/arkos-config/utils.js +3 -0
- package/dist/cjs/types/arkos-config/utils.js.map +1 -0
- package/dist/cjs/types/arkos.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +2 -116
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +152 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/router-template.js +40 -6
- package/dist/cjs/utils/cli/utils/template-generator/templates/router-template.js.map +1 -1
- package/dist/cjs/utils/define-config.js +9 -0
- package/dist/cjs/utils/define-config.js.map +1 -1
- package/dist/cjs/utils/initialize-app.js +2 -2
- package/dist/cjs/utils/initialize-app.js.map +1 -1
- package/dist/esm/app.js +2 -1
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/components/arkos-policy/index.js +3 -1
- package/dist/esm/components/arkos-policy/index.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +142 -5
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +25 -0
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js +273 -0
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js.map +1 -0
- package/dist/esm/types/arkos-config/utils.js +2 -0
- package/dist/esm/types/arkos-config/utils.js.map +1 -0
- package/dist/esm/types/arkos.js.map +1 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +3 -117
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +146 -0
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -0
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js +7 -3
- package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js.map +1 -1
- package/dist/esm/utils/define-config.js +9 -0
- package/dist/esm/utils/define-config.js.map +1 -1
- package/dist/esm/utils/initialize-app.js +2 -2
- package/dist/esm/utils/initialize-app.js.map +1 -1
- package/dist/types/modules/auth/auth.service.d.ts +111 -6
- package/dist/types/modules/swagger/utils/get-open-api-login-html.d.ts +1 -0
- package/dist/types/types/arkos-config/utils.d.ts +35 -0
- package/dist/types/types/arkos.d.ts +4 -1
- package/dist/types/types/index.d.ts +25 -5
- package/dist/types/types/new-arkos-config.d.ts +105 -0
- package/dist/types/utils/arkos-router/types/index.d.ts +35 -11
- package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +7 -0
- package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/cjs/app.js
CHANGED
|
@@ -14,13 +14,14 @@ const runtime_cli_commander_1 = __importDefault(require("./utils/cli/utils/runti
|
|
|
14
14
|
const http_1 = require("http");
|
|
15
15
|
const exit_error_1 = __importDefault(require("./utils/helpers/exit-error.js"));
|
|
16
16
|
const arkos_loadable_registry_1 = __importDefault(require("./components/arkos-loadable-registry/index.js"));
|
|
17
|
+
const apply_arkos_router_proxy_1 = require("./utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js");
|
|
17
18
|
let appServer;
|
|
18
19
|
const docsLink = "https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app";
|
|
19
20
|
let instanciated = false;
|
|
20
21
|
function arkos() {
|
|
21
22
|
if (instanciated)
|
|
22
23
|
throw (0, exit_error_1.default)(`arkos() must be called only once, see ${docsLink}`);
|
|
23
|
-
const app = (0, express_1.default)();
|
|
24
|
+
const app = (0, apply_arkos_router_proxy_1.applyArkosRouterProxy)((0, express_1.default)(), {}, "app");
|
|
24
25
|
(0, setup_app_1.default)(app);
|
|
25
26
|
instanciated = true;
|
|
26
27
|
let state = "idle";
|
package/dist/cjs/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;AA0DA,sBAyFC;AAED,oCAEC;AAvJD,gDAA8C;AAC9C,sDAA2C;AAC3C,kEAAyC;AAEzC,4EAAmD;AACnD,qCAAyC;AACzC,oGAA0E;AAC1E,+BAA+D;AAC/D,4EAAmD;AACnD,mGAAoE;AACpE,0GAAoG;AAEpG,IAAI,SAAgE,CAAC;AACr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IAAY,EAAE,MAAM,KAAK,CAAC,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU;YAC9D,SAAS,GAAG,cAAc,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;aACC,IAAI,IAAI,CAAC,CAAC,CAAC,YAAY,aAAM,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ;YAC/D,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CACxB,IAAI,EACJ,IAAI,EACJ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAiB,CAAC,CAC/C,CAAC;QAEJ,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAgB,YAAY;IAC1B,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import \"./utils/helpers/arkos-config.helpers\";\nimport express, { Express } from \"express\";\nimport setupApp from \"./utils/setup-app\";\nimport { Arkos, ArkosLoadable } from \"./types/arkos\";\nimport initializeApp from \"./utils/initialize-app\";\nimport { logAppStartup } from \"./server\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\nimport { IncomingMessage, Server, ServerResponse } from \"http\";\nimport ExitError from \"./utils/helpers/exit-error\";\nimport loadableRegistry from \"./components/arkos-loadable-registry\";\nimport { applyArkosRouterProxy } from \"./utils/arkos-router/utils/helpers/apply-arkos-router-proxy\";\n\nlet appServer: Server<typeof IncomingMessage, typeof ServerResponse>;\nconst docsLink =\n \"https://www.arkosjs.com/docs/core-concepts/routing/setup#setting-up-your-app\";\nlet instanciated = false;\n\n/**\n * Creates and configures an Arkos application instance.\n *\n * Arkos extends Express with a small set of methods for registering routers,\n * loading route/service hooks, and booting the application. All Arkos-specific\n * setup (`app.build()`) must happen before the app starts\n * accepting requests.\n *\n * @example\n * ```ts\n * // Simple setup\n * import arkos from \"arkos\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * app.listen();\n * ```\n *\n * @example\n * ```ts\n * // Custom HTTP server (e.g. for WebSockets)\n * import arkos from \"arkos\";\n * import http from \"http\";\n *\n * const app = arkos();\n *\n * app.use(reportsRouter);\n *\n * async function start() {\n * await app.build();\n *\n * const server = http.createServer(app);\n * app.listen(server)\n * }\n * main()\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport function arkos(): Arkos {\n if (instanciated)\n throw ExitError(`arkos() must be called only once, see ${docsLink}`);\n\n const app = applyArkosRouterProxy(express(), {}, \"app\") as any as Arkos;\n setupApp(app);\n instanciated = true;\n\n type AppState = \"idle\" | \"building\" | \"built\" | \"listening\";\n let state: AppState = \"idle\";\n\n app.load = (...items: ArkosLoadable[]) => {\n if (state !== \"idle\")\n throw ExitError(\n `app.load() must be called before app.${state === \"listening\" ? \"listen\" : \"build\"}(), see ${docsLink}`\n );\n\n if (Array.isArray(items[0])) items = items[0];\n items = Array.isArray(items) ? items : [items];\n\n items.forEach((item) => loadableRegistry.register(item));\n return app;\n };\n\n function loadApp() {\n const _app = initializeApp(app);\n if (process.env.CLI_COMMAND) runtimeCliCommander.handle();\n return _app;\n }\n\n app.build = function () {\n if (state === \"built\" || state === \"building\")\n throw ExitError(`app.build() must only be called once, see ${docsLink}`);\n if (state === \"listening\")\n throw ExitError(\n `app.build() must be called before app.listen(), see ${docsLink}`\n );\n\n state = \"building\";\n const _app = loadApp();\n state = \"built\";\n return _app;\n };\n\n const originalListen = app.listen.bind(app) as any as Express[\"listen\"];\n type UserCallback = (err?: Error) => void;\n\n const defaultCb = (\n port: number | string,\n host: string,\n cb?: UserCallback\n ) => {\n logAppStartup(port, host);\n return cb || function () {};\n };\n\n app.listen = async function (...args): Promise<Server> {\n if (state === \"listening\")\n throw ExitError(`app.listen() must only be called once, see ${docsLink}`);\n if (state === \"building\")\n throw ExitError(\n `app.build() must be awaited before calling app.listen(), see ${docsLink}`\n );\n\n if (state === \"idle\") {\n state = \"listening\";\n loadApp();\n }\n\n const port = Number(process.env.__PORT || process.env.PORT || \"8000\");\n const host = process.env.__HOST! || process.env.HOST || \"0.0.0.0\";\n\n if ((args as any)?.length === 0 || typeof args[0] === \"function\")\n appServer = originalListen(\n port,\n host,\n defaultCb(port, host, args[0] as UserCallback)\n );\n else if (args[0] instanceof Server || typeof args[0] === \"object\")\n appServer = args[0].listen(\n port,\n host,\n defaultCb(port, host, args[1] as UserCallback)\n );\n\n return appServer;\n };\n\n return app;\n}\n\nexport function getAppServer() {\n return appServer;\n}\n"]}
|
|
@@ -19,7 +19,9 @@ function buildPolicy(resource, store) {
|
|
|
19
19
|
action,
|
|
20
20
|
rule: config,
|
|
21
21
|
};
|
|
22
|
-
const checker =
|
|
22
|
+
const checker = auth_service_1.default.permission(action, resource, {
|
|
23
|
+
[action]: config || {},
|
|
24
|
+
});
|
|
23
25
|
const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;
|
|
24
26
|
return [
|
|
25
27
|
[action, authEntry],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;AAuCA,kCAIC;AAnCD,mFAA0D;AA+B1D,SAAgB,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aA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AAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import { User } from \"../../types\";\nimport {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = authService.permission(action, resource, {\n [action]: config || {},\n });\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
|
|
@@ -20,15 +20,110 @@ class AuthService {
|
|
|
20
20
|
constructor() {
|
|
21
21
|
this.actionsPerResource = {};
|
|
22
22
|
this.authenticate = (0, catch_async_1.default)(async (req, _, next) => {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
const hooks = (0, server_1.getArkosConfig)()?.authentication?.hooks?.authenticate;
|
|
24
|
+
const before = await this.runHooks(hooks?.before, req);
|
|
25
|
+
if (before.stopped && !before.skipped)
|
|
26
|
+
return before.error ? next(before.error) : next();
|
|
27
|
+
if (!before.skipped) {
|
|
28
|
+
try {
|
|
29
|
+
if ((0, arkos_config_helpers_1.isAuthenticationEnabled)()) {
|
|
30
|
+
const user = (await this.getAuthenticatedUser(req));
|
|
31
|
+
if (!user)
|
|
32
|
+
throw auth_error_objects_1.loginRequiredError;
|
|
33
|
+
req.user = user;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
const onError = await this.runErrorHooks(hooks?.onError, err, req);
|
|
38
|
+
if (onError.skipped) {
|
|
39
|
+
const after = await this.runAfterHooks(hooks?.after, req);
|
|
40
|
+
return after.error ? next(after.error) : next();
|
|
41
|
+
}
|
|
42
|
+
return next(onError.error ?? err);
|
|
43
|
+
}
|
|
28
44
|
}
|
|
45
|
+
const after = await this.runAfterHooks(hooks?.after, req);
|
|
46
|
+
if (after.stopped)
|
|
47
|
+
return after.error ? next(after.error) : next();
|
|
29
48
|
next();
|
|
30
49
|
});
|
|
31
50
|
}
|
|
51
|
+
async runHooks(hooks, req) {
|
|
52
|
+
if (!hooks)
|
|
53
|
+
return { stopped: false, skipped: false };
|
|
54
|
+
const hookArray = Array.isArray(hooks) ? hooks : [hooks];
|
|
55
|
+
for (const hook of hookArray) {
|
|
56
|
+
let nextCalled = false;
|
|
57
|
+
let skipCalled = false;
|
|
58
|
+
let hookErr;
|
|
59
|
+
await hook({
|
|
60
|
+
req,
|
|
61
|
+
next: (err) => {
|
|
62
|
+
nextCalled = true;
|
|
63
|
+
hookErr = err;
|
|
64
|
+
},
|
|
65
|
+
skip: () => {
|
|
66
|
+
skipCalled = true;
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
if (hookErr)
|
|
70
|
+
return { stopped: true, skipped: false, error: hookErr };
|
|
71
|
+
if (skipCalled)
|
|
72
|
+
return { stopped: true, skipped: true };
|
|
73
|
+
if (nextCalled)
|
|
74
|
+
return { stopped: true, skipped: false };
|
|
75
|
+
}
|
|
76
|
+
return { stopped: false, skipped: false };
|
|
77
|
+
}
|
|
78
|
+
async runAfterHooks(hooks, req) {
|
|
79
|
+
if (!hooks)
|
|
80
|
+
return { stopped: false };
|
|
81
|
+
const hookArray = Array.isArray(hooks) ? hooks : [hooks];
|
|
82
|
+
for (const hook of hookArray) {
|
|
83
|
+
let nextCalled = false;
|
|
84
|
+
let hookErr;
|
|
85
|
+
await hook({
|
|
86
|
+
req,
|
|
87
|
+
next: (err) => {
|
|
88
|
+
nextCalled = true;
|
|
89
|
+
hookErr = err;
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
if (hookErr)
|
|
93
|
+
return { stopped: true, error: hookErr };
|
|
94
|
+
if (nextCalled)
|
|
95
|
+
return { stopped: true };
|
|
96
|
+
}
|
|
97
|
+
return { stopped: false };
|
|
98
|
+
}
|
|
99
|
+
async runErrorHooks(hooks, error, req) {
|
|
100
|
+
if (!hooks)
|
|
101
|
+
return { stopped: false, skipped: false };
|
|
102
|
+
const hookArray = Array.isArray(hooks) ? hooks : [hooks];
|
|
103
|
+
for (const hook of hookArray) {
|
|
104
|
+
let nextCalled = false;
|
|
105
|
+
let skipCalled = false;
|
|
106
|
+
let hookErr;
|
|
107
|
+
await hook({
|
|
108
|
+
req,
|
|
109
|
+
error,
|
|
110
|
+
next: (err) => {
|
|
111
|
+
nextCalled = true;
|
|
112
|
+
hookErr = err;
|
|
113
|
+
},
|
|
114
|
+
skip: () => {
|
|
115
|
+
skipCalled = true;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
if (hookErr)
|
|
119
|
+
return { stopped: true, skipped: false, error: hookErr };
|
|
120
|
+
if (skipCalled)
|
|
121
|
+
return { stopped: true, skipped: true };
|
|
122
|
+
if (nextCalled)
|
|
123
|
+
return { stopped: true, skipped: false };
|
|
124
|
+
}
|
|
125
|
+
return { stopped: false, skipped: false };
|
|
126
|
+
}
|
|
32
127
|
signJwtToken(id, expiresIn, secret) {
|
|
33
128
|
const { authentication: configs } = (0, server_1.getArkosConfig)();
|
|
34
129
|
if (process.env.ARKOS_BUILD === "true" &&
|
|
@@ -234,6 +329,48 @@ class AuthService {
|
|
|
234
329
|
req.accessToken = token;
|
|
235
330
|
return user;
|
|
236
331
|
}
|
|
332
|
+
authorize(resource, action, rule) {
|
|
333
|
+
auth_action_service_1.default.add(action, resource, { [action]: rule });
|
|
334
|
+
return (0, catch_async_1.default)(async (req, _, next) => {
|
|
335
|
+
const hooks = (0, server_1.getArkosConfig)()?.authentication?.hooks?.authorize;
|
|
336
|
+
const before = await this.runHooks(hooks?.before, req);
|
|
337
|
+
if (before.stopped && !before.skipped)
|
|
338
|
+
return before.error ? next(before.error) : next();
|
|
339
|
+
if (!before.skipped) {
|
|
340
|
+
try {
|
|
341
|
+
if (req.user) {
|
|
342
|
+
const user = req.user;
|
|
343
|
+
const configs = (0, server_1.getArkosConfig)();
|
|
344
|
+
if (!user.isSuperUser) {
|
|
345
|
+
const notEnoughPermissionsError = new app_error_1.default("You do not have permission to perform this action", 403, "NotEnoughPermissions");
|
|
346
|
+
if (configs?.authentication?.mode === "dynamic") {
|
|
347
|
+
const hasPermission = await this.checkDynamicAccessControl(user.id, action, resource);
|
|
348
|
+
if (!hasPermission)
|
|
349
|
+
throw notEnoughPermissionsError;
|
|
350
|
+
}
|
|
351
|
+
else if (configs?.authentication?.mode === "static") {
|
|
352
|
+
const hasPermission = this.checkStaticAccessControl(user, action, { [action]: rule });
|
|
353
|
+
if (!hasPermission)
|
|
354
|
+
throw notEnoughPermissionsError;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
const onError = await this.runErrorHooks(hooks?.onError, err, req);
|
|
361
|
+
if (onError.skipped) {
|
|
362
|
+
const after = await this.runAfterHooks(hooks?.after, req);
|
|
363
|
+
return after.error ? next(after.error) : next();
|
|
364
|
+
}
|
|
365
|
+
return next(onError.error ?? err);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const after = await this.runAfterHooks(hooks?.after, req);
|
|
369
|
+
if (after.stopped)
|
|
370
|
+
return after.error ? next(after.error) : next();
|
|
371
|
+
next();
|
|
372
|
+
});
|
|
373
|
+
}
|
|
237
374
|
handleAuthenticationControl(action, authenticationControl) {
|
|
238
375
|
if (authenticationControl && typeof authenticationControl === "object") {
|
|
239
376
|
if (authenticationControl[action] === false)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,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C5F,CAAC;YAEJ,IAAI,CAAC,IAAA,8CAAuB,GAAE;gBAAE,OAAO,KAAK,CAAC;YAC7C,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,EAAE,WAAW;gBAAE,OAAO,IAAI,CAAC;YAEnC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AA3iBD,kCA2iBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
1
|
+
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAUlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAqmBrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,CAAC;YAEpE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;YACvD,IAAI,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO;gBACnC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YAEpD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBACpB,IAAI,CAAC;oBACH,IAAI,IAAA,8CAAuB,GAAE,EAAE,CAAC;wBAC9B,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;wBAC5D,IAAI,CAAC,IAAI;4BAAE,MAAM,uCAAkB,CAAC;wBACpC,GAA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AE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAj0BD,kCAi0BC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthAfterHookHandler,\n AuthErrorHookHandler,\n AuthHookHandler,\n} from \"../../types/arkos-config/utils\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Runs a chain of `before` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run, core logic is skipped.\n * - If a hook calls `ctx.skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runHooks(\n hooks: AuthHookHandler | AuthHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req` and `next` only — no `skip` since\n * there is nothing meaningful to skip to after the pipeline has completed.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards to the global error handler.\n * - If a hook calls `ctx.next()` — chain stops, no further hooks run.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, error? }`\n */\n private async runAfterHooks(\n hooks: AuthAfterHookHandler | AuthAfterHookHandler[] | undefined,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n });\n\n if (hookErr) return { stopped: true, error: hookErr };\n if (nextCalled) return { stopped: true };\n }\n\n return { stopped: false };\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * Each hook receives a `ctx` object with `req`, `error`, `next`, and `skip`.\n *\n * - If a hook calls `ctx.next(err)` — chain aborts and forwards the error (original or replaced) to the global error handler.\n * - If a hook calls `ctx.skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns without calling anything — next hook in chain runs.\n *\n * @returns Promise resolving to `{ stopped, skipped, error? }`\n */\n private async runErrorHooks(\n hooks: AuthErrorHookHandler | AuthErrorHookHandler[] | undefined,\n error: unknown,\n req: ArkosRequest\n ): Promise<{ stopped: boolean; skipped: boolean; error?: unknown }> {\n if (!hooks) return { stopped: false, skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let nextCalled = false;\n let skipCalled = false;\n let hookErr: unknown;\n\n await hook({\n req,\n error,\n next: (err?: unknown) => {\n nextCalled = true;\n hookErr = err;\n },\n skip: () => {\n skipCalled = true;\n },\n });\n\n if (hookErr) return { stopped: true, skipped: false, error: hookErr };\n if (skipCalled) return { stopped: true, skipped: true };\n if (nextCalled) return { stopped: true, skipped: false };\n }\n\n return { stopped: false, skipped: false };\n }\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n resource: string,\n action: AccessAction,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.stopped && !before.skipped)\n return before.error ? next(before.error) : next();\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error ?? err);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.stopped) return after.error ? next(after.error) : next();\n\n next();\n }\n );\n }\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
@@ -15,6 +15,9 @@ const generate_system_json_schemas_1 = __importDefault(require("./utils/helpers/
|
|
|
15
15
|
const arkos_router_1 = require("../../utils/arkos-router/index.js");
|
|
16
16
|
const get_file_upload_json_schema_paths_1 = __importDefault(require("./utils/helpers/get-file-upload-json-schema-paths.js"));
|
|
17
17
|
const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerge.helper.js"));
|
|
18
|
+
const auth_service_1 = __importDefault(require("../auth/auth.service.js"));
|
|
19
|
+
const app_error_1 = __importDefault(require("../error-handler/utils/app-error.js"));
|
|
20
|
+
const get_open_api_login_html_1 = __importDefault(require("./utils/get-open-api-login-html.js"));
|
|
18
21
|
const swaggerRouter = (0, express_1.Router)();
|
|
19
22
|
function getSwaggerRouter(arkosConfig, app) {
|
|
20
23
|
let defaultJsonSchemas = (0, swagger_router_helpers_1.getOpenAPIJsonSchemasByConfigMode)();
|
|
@@ -38,6 +41,28 @@ function getSwaggerRouter(arkosConfig, app) {
|
|
|
38
41
|
...options,
|
|
39
42
|
});
|
|
40
43
|
const endpoint = swaggerConfigs.endpoint;
|
|
44
|
+
const swaggerAuth = arkosConfig?.swagger;
|
|
45
|
+
const requireAuth = swaggerAuth?.requireAuth !== false;
|
|
46
|
+
if (requireAuth) {
|
|
47
|
+
swaggerRouter.use(endpoint, (req, _, next) => {
|
|
48
|
+
if (req.path.includes("/auth"))
|
|
49
|
+
return next();
|
|
50
|
+
next("route");
|
|
51
|
+
});
|
|
52
|
+
swaggerRouter.use(endpoint, auth_service_1.default.authenticate, (req, _, next) => {
|
|
53
|
+
if (!req.user?.isSuperUser)
|
|
54
|
+
return next(new app_error_1.default("Only super users can access API documentation in production.", 403, "SuperUserRequired"));
|
|
55
|
+
next();
|
|
56
|
+
}, (err, req, res, next) => {
|
|
57
|
+
if (req.path.includes("/auth"))
|
|
58
|
+
return next();
|
|
59
|
+
const message = encodeURIComponent(err?.message || "Authentication required.");
|
|
60
|
+
return res.redirect(`${arkosConfig.globalPrefix}${endpoint}/auth/login?error-message=${message}`);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
swaggerRouter.get(`${endpoint}/auth/login`, (_, res) => {
|
|
64
|
+
res.send((0, get_open_api_login_html_1.default)());
|
|
65
|
+
});
|
|
41
66
|
swaggerRouter.get(`${endpoint}/openapi.json`, (_, res) => {
|
|
42
67
|
res.json(swaggerSpecification);
|
|
43
68
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AA2BA,4CA6GC;AAED,4CA2BC;AArKD,qCAAiC;AACjC,kEAAyC;AACzC,mFAGgD;AAChD,oHAAw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AC1B,CAAC,CAAe,EAAE,GAAkB,EAAE,EAAE;QACtC,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACjC,CAAC,CACF,CAAC;IAEF,IAAI,aAAa,GAAQ,IAAI,CAAC;IAE9B,aAAa,CAAC,GAAG,CACf,QAAQ,EACR,gBAAgB,CAAC,aAAa,EAAE,oBAAoB,EAAE,cAAc,CAAC,CACtE,CAAC;IAEF,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,SAAgB,gBAAgB,CAC9B,aAAkB,EAClB,oBAA4B,EAC5B,cAAmB;IAEnB,IAAI,aAAa,GAAyB,IAAI,CAAC;IAE/C,OAAO,KAAK,EACV,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;QACF,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,aAAa,GAAG,IAAA,oDAAmC,EACjD,+BAA+B,CAChC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;oBAChB,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC;wBAClC,OAAO,EAAE,oBAAoB;wBAC7B,GAAG,cAAc,EAAE,+BAA+B;qBACnD,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;YACL,CAAC;YACD,MAAM,aAAa,CAAC;QACtB,CAAC;QACD,OAAO,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport {\n generatePathsForModels,\n getOpenAPIJsonSchemasByConfigMode,\n} from \"./utils/helpers/swagger.router.helpers\";\nimport missingJsonSchemaGenerator from \"./utils/helpers/missing-json-schemas-generator\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport generateSystemJsonSchemas from \"./utils/helpers/json-schema-generators/generate-system-json-schemas\";\nimport { generateOpenAPIFromApp } from \"../../utils/arkos-router\";\nimport getFileUploadJsonSchemaPaths from \"./utils/helpers/get-file-upload-json-schema-paths\";\nimport {\n ArkosConfig,\n ArkosNextFunction,\n ArkosRequest,\n ArkosResponse,\n} from \"../../exports\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { Arkos } from \"../../types/arkos\";\nimport { UserArkosConfig } from \"../../utils/define-config\";\nimport authService from \"../auth/auth.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport getOpenApiLoginHtml from \"./utils/get-open-api-login-html\";\n\nconst swaggerRouter = Router();\n\nexport function getSwaggerRouter(\n arkosConfig: UserArkosConfig,\n app: Arkos\n): Router {\n let defaultJsonSchemas = getOpenAPIJsonSchemasByConfigMode();\n const pathsFromCustomArkosRouters = generateOpenAPIFromApp(app);\n const defaultModelsPaths = generatePathsForModels(\n arkosConfig,\n pathsFromCustomArkosRouters\n );\n const fileUploadDefaultPaths = getFileUploadJsonSchemaPaths(\n arkosConfig,\n pathsFromCustomArkosRouters\n );\n const missingJsonSchemas =\n missingJsonSchemaGenerator.generateMissingJsonSchemas(\n defaultModelsPaths,\n defaultJsonSchemas\n );\n defaultJsonSchemas = {\n ...defaultJsonSchemas,\n ...missingJsonSchemas,\n ...generateSystemJsonSchemas(arkosConfig),\n };\n const swaggerConfigs = deepmerge(\n getSwaggerDefaultConfig(\n {\n ...pathsFromCustomArkosRouters,\n ...defaultModelsPaths,\n ...fileUploadDefaultPaths,\n },\n defaultJsonSchemas\n ) || {},\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n const { definition, ...options } = swaggerConfigs?.options!;\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const endpoint = swaggerConfigs!.endpoint!;\n\n const swaggerAuth = arkosConfig?.swagger;\n const requireAuth = swaggerAuth?.requireAuth !== false;\n\n if (requireAuth) {\n swaggerRouter.use(\n endpoint,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.path.includes(\"/auth\")) return next();\n next(\"route\"); // skip to auth chain below\n }\n );\n\n swaggerRouter.use(\n endpoint,\n authService.authenticate,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (!req.user?.isSuperUser)\n return next(\n new AppError(\n \"Only super users can access API documentation in production.\",\n 403,\n \"SuperUserRequired\"\n )\n );\n next();\n },\n (\n err: AppError,\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.path.includes(\"/auth\")) return next();\n const message = encodeURIComponent(\n err?.message || \"Authentication required.\"\n );\n return res.redirect(\n `${arkosConfig.globalPrefix}${endpoint}/auth/login?error-message=${message}`\n );\n }\n );\n }\n\n swaggerRouter.get(\n `${endpoint}/auth/login`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.send(getOpenApiLoginHtml());\n }\n );\n\n swaggerRouter.get(\n `${endpoint}/openapi.json`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.json(swaggerSpecification);\n }\n );\n\n let scalarHandler: any = null;\n\n swaggerRouter.use(\n endpoint,\n scalarMiddleware(scalarHandler, swaggerSpecification, swaggerConfigs)\n );\n\n return swaggerRouter;\n}\n\nexport function scalarMiddleware(\n scalarHandler: any,\n swaggerSpecification: object,\n swaggerConfigs: any\n) {\n let scalarLoading: Promise<void> | null = null;\n\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (!scalarHandler) {\n if (!scalarLoading) {\n scalarLoading = importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n ).then((scalar) => {\n scalarHandler = scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n });\n });\n }\n await scalarLoading;\n }\n return scalarHandler(req, res, next);\n };\n}\n"]}
|