create-nexwire 4.2.2 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/express/package.json +48 -23
  2. package/express/src/database/migrations/sqlite/0000_init.sql +47 -60
  3. package/express/src/database/migrations/sqlite/meta/0000_snapshot.json +1 -89
  4. package/express/src/database/migrations/sqlite/meta/_journal.json +1 -1
  5. package/express/src/database/schema.ts +2 -3
  6. package/express/src/framework/database/app-schema.ts +37 -0
  7. package/express/src/framework/database/connection.ts +198 -196
  8. package/express/src/framework/database/seed.ts +35 -22
  9. package/express/src/framework/facade.ts +35 -5
  10. package/express/src/framework/kernel.ts +54 -52
  11. package/express/src/framework/maker-cli/db/core.mjs +291 -288
  12. package/express/src/framework/maker-cli/index.mjs +2 -0
  13. package/express/src/framework/maker-cli/module/core.mjs +155 -87
  14. package/express/src/framework/maker-cli/module/index.mjs +13 -4
  15. package/express/src/framework/maker-cli/provider/core.mjs +49 -0
  16. package/express/src/framework/maker-cli/provider/index.mjs +12 -0
  17. package/express/src/framework/maker-cli/stubs/notification/controller.ts.stub +76 -77
  18. package/express/src/framework/maker-cli/stubs/notification/job.ts.stub +11 -13
  19. package/express/src/framework/maker-cli/stubs/notification/model.ts.stub +29 -0
  20. package/express/src/framework/maker-cli/stubs/notification/provider.ts.stub +174 -0
  21. package/express/src/framework/maker-cli/stubs/notification/route.api.ts.stub +11 -10
  22. package/express/src/framework/maker-cli/stubs/notification/route.plain.ts.stub +1 -1
  23. package/express/src/framework/maker-cli/stubs/notification/schema.plain.ts.stub +25 -25
  24. package/express/src/framework/maker-cli/stubs/notification/schema.ts.stub +25 -25
  25. package/express/src/framework/maker-cli/stubs/provider/module-barrel.ts.stub +19 -0
  26. package/express/src/framework/maker-cli/stubs/provider/module.ts.stub +21 -0
  27. package/express/src/framework/maker-cli/stubs/provider/name.ts.stub +21 -0
  28. package/express/src/framework/maker-cli/utils/help.mjs +6 -1
  29. package/express/src/framework/notification/index.ts +65 -47
  30. package/express/src/framework/providers/adapter.ts +139 -0
  31. package/express/src/framework/providers/contracts.ts +126 -0
  32. package/express/src/framework/providers/loader.ts +105 -0
  33. package/express/src/framework/providers/registry.ts +88 -0
  34. package/express/src/middlewares/auth-middleware.ts +65 -38
  35. package/express/src/providers/README.md +107 -0
  36. package/express/src/resources/src/main.ts +1 -1
  37. package/express/src/resources/src/pages/auth/forgetPassword.vue +1 -1
  38. package/express/src/resources/src/pages/auth/login.vue +1 -1
  39. package/express/src/resources/src/pages/auth/register.vue +1 -1
  40. package/express/src/resources/src/pages/auth/resetPassword.vue +1 -1
  41. package/express/src/resources/src/pages/auth/verifyEmail.vue +1 -1
  42. package/express/src/resources/src/pages/dashboard/index.vue +66 -66
  43. package/express/src/storage/database/nexwire.sqlite +0 -0
  44. package/hono/package.json +44 -19
  45. package/hono/src/database/migrations/sqlite/0000_init.sql +47 -60
  46. package/hono/src/database/migrations/sqlite/meta/0000_snapshot.json +1 -89
  47. package/hono/src/database/migrations/sqlite/meta/_journal.json +1 -1
  48. package/hono/src/database/schema.ts +2 -3
  49. package/hono/src/framework/database/app-schema.ts +37 -0
  50. package/hono/src/framework/database/connection.ts +198 -196
  51. package/hono/src/framework/database/seed.ts +35 -22
  52. package/hono/src/framework/facade.ts +59 -29
  53. package/hono/src/framework/kernel.ts +50 -48
  54. package/hono/src/framework/maker-cli/db/core.mjs +291 -288
  55. package/hono/src/framework/maker-cli/index.mjs +2 -0
  56. package/hono/src/framework/maker-cli/module/core.mjs +123 -52
  57. package/hono/src/framework/maker-cli/module/index.mjs +13 -4
  58. package/hono/src/framework/maker-cli/provider/core.mjs +49 -0
  59. package/hono/src/framework/maker-cli/provider/index.mjs +12 -0
  60. package/hono/src/framework/maker-cli/stubs/notification/controller.ts.stub +90 -85
  61. package/hono/src/framework/maker-cli/stubs/notification/job.ts.stub +10 -12
  62. package/hono/src/framework/maker-cli/stubs/notification/model.ts.stub +29 -0
  63. package/hono/src/framework/maker-cli/stubs/notification/provider.ts.stub +174 -0
  64. package/hono/src/framework/maker-cli/stubs/notification/route.api.ts.stub +11 -10
  65. package/hono/src/framework/maker-cli/stubs/notification/route.plain.ts.stub +1 -1
  66. package/hono/src/framework/maker-cli/stubs/notification/schema.plain.ts.stub +25 -25
  67. package/hono/src/framework/maker-cli/stubs/notification/schema.ts.stub +25 -25
  68. package/hono/src/framework/maker-cli/stubs/provider/module-barrel.ts.stub +19 -0
  69. package/hono/src/framework/maker-cli/stubs/provider/module.ts.stub +21 -0
  70. package/hono/src/framework/maker-cli/stubs/provider/name.ts.stub +21 -0
  71. package/hono/src/framework/maker-cli/utils/help.mjs +6 -1
  72. package/hono/src/framework/notification/index.ts +65 -47
  73. package/hono/src/framework/providers/adapter.ts +139 -0
  74. package/hono/src/framework/providers/contracts.ts +126 -0
  75. package/hono/src/framework/providers/loader.ts +105 -0
  76. package/hono/src/framework/providers/registry.ts +88 -0
  77. package/hono/src/middlewares/auth-middleware.ts +65 -38
  78. package/hono/src/providers/README.md +107 -0
  79. package/hono/src/resources/src/main.ts +1 -1
  80. package/hono/src/resources/src/pages/auth/forgetPassword.vue +1 -1
  81. package/hono/src/resources/src/pages/auth/login.vue +1 -1
  82. package/hono/src/resources/src/pages/auth/register.vue +1 -1
  83. package/hono/src/resources/src/pages/auth/resetPassword.vue +1 -1
  84. package/hono/src/resources/src/pages/auth/verifyEmail.vue +1 -1
  85. package/hono/src/resources/src/pages/dashboard/index.vue +66 -66
  86. package/hono/src/storage/database/nexwire.sqlite +0 -0
  87. package/package.json +10 -10
  88. package/src/index.js +14 -6
  89. package/express/src/modules/auth/database/models/notification.ts +0 -24
  90. package/hono/src/modules/auth/database/models/notification.ts +0 -24
@@ -0,0 +1,139 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { db } from "@/framework/database/connection.js";
3
+ import type { AuthProvider, NotificationProvider } from "./contracts.js";
4
+ import { loadProviders } from "./loader.js";
5
+ import { getAuthProvider, getNotificationProvider } from "./registry.js";
6
+
7
+ let defaultProvider: AuthProvider | null = null;
8
+ let defaultLoadAttempted = false;
9
+
10
+ /**
11
+ * Why: Builds the built-in auth provider from the default auth module.
12
+ * When: No custom provider was registered by the application.
13
+ * Where: Auth provider adapter.
14
+ * How: Lazily imports the default user/refresh-token models. When the default
15
+ * auth module was deleted or replaced, no provider is produced.
16
+ */
17
+ async function loadDefaultProvider(): Promise<AuthProvider | null> {
18
+ if (defaultProvider) return defaultProvider;
19
+ if (defaultLoadAttempted) return null;
20
+ defaultLoadAttempted = true;
21
+ try {
22
+ const userMod = await import("@/modules/auth/database/models/user.js").catch(() => null);
23
+ if (!userMod?.users || !userMod?.refreshTokens) return null;
24
+
25
+ const users = userMod.users;
26
+ const refreshTokens = userMod.refreshTokens;
27
+
28
+ defaultProvider = {
29
+ async getUserById(id: number | string) {
30
+ try {
31
+ const user = await (db.query.users.findFirst as any)?.({
32
+ where: eq(users.id, id as any),
33
+ with: { role: true }
34
+ });
35
+ if (user) return user;
36
+ } catch {}
37
+ try {
38
+ const rows = await db.select().from(users).where(eq(users.id, id as any));
39
+ return rows?.[0] ?? null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ },
44
+ async findRefreshToken(jti: string) {
45
+ try {
46
+ const token = await (db.query.refreshTokens.findFirst as any)?.({
47
+ where: eq(refreshTokens.jti, jti)
48
+ });
49
+ if (token) return token;
50
+ } catch {}
51
+ try {
52
+ const rows = await db.select().from(refreshTokens).where(eq(refreshTokens.jti, jti));
53
+ return rows?.[0] ?? null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ },
58
+ async deleteRefreshToken(tokenId: number | string) {
59
+ try {
60
+ await db.delete(refreshTokens).where(eq(refreshTokens.id, tokenId as any));
61
+ } catch {}
62
+ },
63
+ async revokeRefreshToken(tokenId: number | string) {
64
+ try {
65
+ await db.delete(refreshTokens).where(eq(refreshTokens.id, tokenId as any));
66
+ } catch {}
67
+ },
68
+ async getAuthContext(user: any, payload?: any) {
69
+ try {
70
+ if (user?.role && typeof user.role === "object") {
71
+ return {
72
+ ...(payload || {}),
73
+ id: user.id,
74
+ email: user.email,
75
+ roleId: user.role?.id ?? null,
76
+ role: user.role?.name ?? null,
77
+ ...user
78
+ };
79
+ }
80
+ } catch {}
81
+ return {
82
+ ...(payload || {}),
83
+ id: user.id,
84
+ email: user.email,
85
+ roleId: user.roleId ?? null,
86
+ role: user.role ?? null,
87
+ ...user
88
+ };
89
+ },
90
+ async getUserContact(userId: number | string) {
91
+ try {
92
+ const user = await this.getUserById(userId);
93
+ if (!user) return null;
94
+ return {
95
+ email: user.email ?? null,
96
+ name: user.name ?? user.fullName ?? user.username ?? null,
97
+ phone: user.phone ?? user.phoneNumber ?? null
98
+ };
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+ };
104
+ return defaultProvider;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Why: Resolves the auth provider the framework should use.
112
+ * When: The auth middleware or the notification mailer needs user data.
113
+ * Where: Auth provider adapter.
114
+ * How: Application providers are loaded first, so a file in `src/providers/`
115
+ * wins. Otherwise the built-in provider from the default auth module is
116
+ * used. When neither exists the framework degrades gracefully.
117
+ */
118
+ export async function resolveAuthProvider(): Promise<AuthProvider | null> {
119
+ await loadProviders();
120
+ const registered = getAuthProvider();
121
+ if (registered) return registered;
122
+ const def = await loadDefaultProvider();
123
+ if (def) return def;
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Why: Resolves the notification storage provider.
129
+ * When: `notify()` persists a notification; the HTTP handlers read it back.
130
+ * Where: Notification runtime and the generated notification controller.
131
+ * How: Provider files are loaded first, so a project can replace the store from
132
+ * `src/providers/` or a module provider folder. The notification module is
133
+ * opt-in, so an absent provider is a normal state: callers warn once
134
+ * (runtime) or answer 503 (HTTP) instead of throwing.
135
+ */
136
+ export async function resolveNotificationProvider(): Promise<NotificationProvider | null> {
137
+ await loadProviders();
138
+ return getNotificationProvider();
139
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Why: Defines the shapes a pluggable provider has to satisfy.
3
+ * When: A developer replaces a framework default (auth, notifications, payments later).
4
+ * Where: Imported through the framework facade, never from framework internals.
5
+ * How: Interfaces stay deliberately loose so custom user shapes pass through.
6
+ */
7
+
8
+ /** Registry key of the built-in auth provider contract. */
9
+ export const AUTH_PROVIDER_KEY = "auth";
10
+
11
+ /** Registry key of the built-in notification storage provider. */
12
+ export const NOTIFICATION_PROVIDER_KEY = "notification";
13
+
14
+ /**
15
+ * Registry key for any provider implementation.
16
+ *
17
+ * `string & {}` keeps the literal keys above discoverable by editors while
18
+ * still accepting any custom key, so a project can register its own contracts
19
+ * (payments, otp, storage, ...) without the framework having to know them.
20
+ */
21
+ export type ProviderKey = typeof AUTH_PROVIDER_KEY | typeof NOTIFICATION_PROVIDER_KEY | (string & {});
22
+
23
+ export interface AuthProviderUser {
24
+ id: number | string;
25
+ email?: string | null;
26
+ [key: string]: any;
27
+ }
28
+
29
+ export interface AuthProviderRefreshToken {
30
+ id: number | string;
31
+ jti: string;
32
+ revoked?: boolean | null;
33
+ expiresAt?: Date | string | null;
34
+ userId?: number | string | null;
35
+ [key: string]: any;
36
+ }
37
+
38
+ export interface AuthUserContext {
39
+ id: number | string;
40
+ email?: string | null;
41
+ roleId?: number | null;
42
+ role?: string | null;
43
+ [key: string]: any;
44
+ }
45
+
46
+ export interface AuthUserContact {
47
+ email?: string | null;
48
+ name?: string | null;
49
+ phone?: string | null;
50
+ }
51
+
52
+ export interface AuthProvider {
53
+ getUserById(id: number | string): Promise<AuthProviderUser | null>;
54
+ findRefreshToken(jti: string): Promise<AuthProviderRefreshToken | null>;
55
+ revokeRefreshToken?(tokenId: number | string): Promise<void>;
56
+ deleteRefreshToken?(tokenId: number | string): Promise<void>;
57
+ getAuthContext?(user: AuthProviderUser, payload?: any): Promise<AuthUserContext | any>;
58
+ getUserContact?(userId: number | string): Promise<AuthUserContact | null>;
59
+ }
60
+
61
+ /**
62
+ * Who a notification belongs to. `id` accepts a numeric auth id and a string
63
+ * id (UUID, ULID, ...) so replacing auth does not force a notification change.
64
+ * The provider always stores the id as text.
65
+ */
66
+ export interface NotifiableTarget {
67
+ /** Notifiable class. Defaults to "user". */
68
+ type?: string;
69
+ id: number | string;
70
+ }
71
+
72
+ /** Payload accepted by `NotificationProvider.create()`. */
73
+ export interface NotificationCreateInput {
74
+ type?: string;
75
+ title: string;
76
+ body?: string | null;
77
+ link?: string | null;
78
+ data?: Record<string, unknown> | null;
79
+ }
80
+
81
+ /** Normalized notification returned by every provider operation. */
82
+ export interface NotificationRecord {
83
+ id: string;
84
+ notifiableType: string;
85
+ notifiableId: string;
86
+ type: string;
87
+ title: string;
88
+ body: string | null;
89
+ data: Record<string, unknown> | null;
90
+ link: string | null;
91
+ readAt: string | null;
92
+ createdAt: string;
93
+ }
94
+
95
+ export interface NotificationListOptions {
96
+ page?: number;
97
+ perPage?: number;
98
+ }
99
+
100
+ export interface NotificationPage {
101
+ data: NotificationRecord[];
102
+ total: number;
103
+ unread: number;
104
+ page: number;
105
+ perPage: number;
106
+ }
107
+
108
+ /**
109
+ * Why: Keeps notification storage replaceable without touching `notify()` or
110
+ * the generated HTTP routes.
111
+ * When: The default `src/modules/notification` store is replaced by a custom
112
+ * implementation (a different table, another service, ...).
113
+ * Where: Registered through `registerNotificationProvider()`.
114
+ * How: The framework only reads through this contract; mail and realtime
115
+ * delivery stay in the runtime so a storage swap cannot disable them.
116
+ */
117
+ export interface NotificationProvider {
118
+ create(target: NotifiableTarget, input: NotificationCreateInput): Promise<NotificationRecord>;
119
+ list(target: NotifiableTarget, options?: NotificationListOptions): Promise<NotificationPage>;
120
+ unreadCount(target: NotifiableTarget): Promise<number>;
121
+ markRead(target: NotifiableTarget, id: number | string): Promise<boolean>;
122
+ markAllRead(target: NotifiableTarget): Promise<number>;
123
+ remove(target: NotifiableTarget, id: number | string): Promise<boolean>;
124
+ /** Optional bulk cleanup when a notifiable target is deleted. */
125
+ deleteForTarget?(target: NotifiableTarget): Promise<number>;
126
+ }
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { glob } from "glob";
5
+ import { discoverModuleFiles } from "@/framework/modules/discover.js";
6
+ import { logger } from "@/framework/support/logger.js";
7
+
8
+ /**
9
+ * Why: Finds the app-level provider folder for the running code.
10
+ * When: Providers are loaded at boot.
11
+ * Where: Provider loader.
12
+ * How: Mirrors the module discovery rule — `src/providers` in development,
13
+ * `dist/src/providers` when the compiled server is the entrypoint.
14
+ */
15
+ function resolveProvidersPath() {
16
+ const cwd = process.cwd();
17
+ const srcProviders = path.resolve(cwd, "src/providers");
18
+ const distProviders = path.resolve(cwd, "dist/src/providers");
19
+ const entry = String(process.argv[1] || "");
20
+ const runningDist = /[\\/]dist[\\/]/.test(entry);
21
+
22
+ if (runningDist && fs.existsSync(distProviders)) return distProviders;
23
+ return srcProviders;
24
+ }
25
+
26
+ export const providersPath = resolveProvidersPath();
27
+
28
+ let loadPromise: Promise<number> | null = null;
29
+ let loading = false;
30
+
31
+ /**
32
+ * Why: Collects every provider file that should run at boot.
33
+ * When: The loader runs.
34
+ * Where: Provider loader.
35
+ * How: Globs `src/providers/**` for app-wide providers, and
36
+ * `src/modules/**\/providers.ts` plus `src/modules/**\/providers/*.ts` for
37
+ * module-scoped ones. Tests and declaration files are ignored.
38
+ */
39
+ async function collectProviderFiles(): Promise<string[]> {
40
+ const files: string[] = [];
41
+
42
+ if (fs.existsSync(providersPath)) {
43
+ const appFiles = await glob("**/*.{ts,js,mjs}", {
44
+ cwd: providersPath,
45
+ absolute: true,
46
+ nodir: true,
47
+ ignore: ["**/__tests__/**", "**/*.d.ts", "**/*.test.*", "**/*.spec.*"],
48
+ windowsPathsNoEscape: true
49
+ });
50
+ files.push(...appFiles);
51
+ }
52
+
53
+ try {
54
+ // A module plugs its own implementation in either from a single file
55
+ // (providers.ts) or from a folder (providers/*.ts). Both are imported.
56
+ const moduleFiles = await discoverModuleFiles("**/providers.{ts,js}");
57
+ const moduleProviderFiles = await discoverModuleFiles("**/providers/*.{ts,js}");
58
+ files.push(...moduleFiles, ...moduleProviderFiles);
59
+ } catch {}
60
+
61
+ return [...new Set(files)].sort();
62
+ }
63
+
64
+ /**
65
+ * Why: Imports each discovered provider file so its registration runs.
66
+ * When: The loader runs.
67
+ * Where: Provider loader.
68
+ * How: Imports in sorted order; a broken file is logged and skipped instead of
69
+ * taking the whole application down.
70
+ */
71
+ async function loadProviderFiles(): Promise<number> {
72
+ const files = await collectProviderFiles();
73
+
74
+ for (const file of files) {
75
+ try {
76
+ await import(pathToFileURL(file).href);
77
+ } catch (error) {
78
+ logger.warn("Provider file failed to load", {
79
+ file,
80
+ error: error instanceof Error ? error.message : String(error)
81
+ });
82
+ }
83
+ }
84
+
85
+ return files.length;
86
+ }
87
+
88
+ /**
89
+ * Why: Runs the application's provider files exactly once.
90
+ * When: The kernel boots, and on the first provider lookup.
91
+ * Where: Kernel startup and the auth provider adapter.
92
+ * How: Caches the promise so repeated lookups cost nothing. A provider file
93
+ * that itself asks for a provider during load gets an immediate answer
94
+ * instead of deadlocking on its own load.
95
+ */
96
+ export async function loadProviders(): Promise<number> {
97
+ if (loading) return 0;
98
+ if (!loadPromise) {
99
+ loading = true;
100
+ loadPromise = loadProviderFiles().finally(() => {
101
+ loading = false;
102
+ });
103
+ }
104
+ return loadPromise;
105
+ }
@@ -0,0 +1,88 @@
1
+ import {
2
+ AUTH_PROVIDER_KEY,
3
+ type AuthProvider,
4
+ NOTIFICATION_PROVIDER_KEY,
5
+ type NotificationProvider,
6
+ type ProviderKey
7
+ } from "./contracts.js";
8
+
9
+ /**
10
+ * Why: Holds the app-wide provider implementations in one place.
11
+ * When: A provider file in `src/providers/` (or a module's `providers.ts`)
12
+ * registers its implementation at boot.
13
+ * Where: Read by the framework through `resolve*Provider()` helpers.
14
+ * How: A plain key/value map. No container, no decorators, no auto-wiring.
15
+ */
16
+ const registry = new Map<string, unknown>();
17
+
18
+ /**
19
+ * Why: Registers a provider implementation under a key.
20
+ * When: A provider file runs at boot and claims a contract.
21
+ * Where: Application code, through the framework facade.
22
+ * How: Stores the implementation and returns it so it can be inlined.
23
+ */
24
+ export function registerProvider<T>(key: ProviderKey, implementation: T): T {
25
+ registry.set(key, implementation);
26
+ return implementation;
27
+ }
28
+
29
+ /** Returns the registered implementation for a key, or null when absent. */
30
+ export function getProvider<T = unknown>(key: ProviderKey): T | null {
31
+ const found = registry.get(key);
32
+ return (found as T) ?? null;
33
+ }
34
+
35
+ /** Reports whether a provider is registered for a key. */
36
+ export function hasProvider(key: ProviderKey): boolean {
37
+ return registry.has(key);
38
+ }
39
+
40
+ /** Removes a registered provider. Mainly useful in tests. */
41
+ export function clearProvider(key: ProviderKey): void {
42
+ registry.delete(key);
43
+ }
44
+
45
+ /** Lists every registered provider key, sorted for stable output. */
46
+ export function listProviders(): string[] {
47
+ return [...registry.keys()].sort();
48
+ }
49
+
50
+ /** Registers the auth provider that the framework's auth middleware uses. */
51
+ export function registerAuthProvider(provider: AuthProvider): AuthProvider {
52
+ return registerProvider(AUTH_PROVIDER_KEY, provider);
53
+ }
54
+
55
+ /** Returns the registered auth provider, or null when none was registered. */
56
+ export function getAuthProvider(): AuthProvider | null {
57
+ return getProvider<AuthProvider>(AUTH_PROVIDER_KEY);
58
+ }
59
+
60
+ /** Reports whether a custom auth provider is registered. */
61
+ export function hasAuthProvider(): boolean {
62
+ return hasProvider(AUTH_PROVIDER_KEY);
63
+ }
64
+
65
+ /** Removes the registered auth provider. Mainly useful in tests. */
66
+ export function clearAuthProvider(): void {
67
+ clearProvider(AUTH_PROVIDER_KEY);
68
+ }
69
+
70
+ /** Registers the storage provider `notify()` and `/api/notification/*` use. */
71
+ export function registerNotificationProvider(provider: NotificationProvider): NotificationProvider {
72
+ return registerProvider(NOTIFICATION_PROVIDER_KEY, provider);
73
+ }
74
+
75
+ /** Returns the registered notification provider, or null when none was registered. */
76
+ export function getNotificationProvider(): NotificationProvider | null {
77
+ return getProvider<NotificationProvider>(NOTIFICATION_PROVIDER_KEY);
78
+ }
79
+
80
+ /** Reports whether a notification provider is registered. */
81
+ export function hasNotificationProvider(): boolean {
82
+ return hasProvider(NOTIFICATION_PROVIDER_KEY);
83
+ }
84
+
85
+ /** Removes the registered notification provider. Mainly useful in tests. */
86
+ export function clearNotificationProvider(): void {
87
+ clearProvider(NOTIFICATION_PROVIDER_KEY);
88
+ }
@@ -1,19 +1,23 @@
1
- import { eq } from "drizzle-orm";
2
1
  import { type NextFunction, type Request, type Response } from "express";
3
- import { cookie, db, HttpStatusCodes, jwt } from "@/framework/facade.js";
4
- import { refreshTokens, users } from "@/modules/auth/database/models/user.js";
2
+ import { cookie, HttpStatusCodes, jwt } from "@/framework/facade.js";
3
+ import { resolveAuthProvider } from "@/framework/providers/adapter.js";
5
4
 
6
5
  export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
6
+ const provider = await resolveAuthProvider();
7
+ if (!provider) {
8
+ console.warn(
9
+ "[auth-middleware] auth provider not available; skipping auth. Register one in src/providers/ or restore src/modules/auth."
10
+ );
11
+ return next();
12
+ }
13
+
7
14
  const accessToken = await cookie.getAuth(req);
8
15
 
9
16
  if (accessToken) {
10
- const accessPayload = await jwt.verifyToken(accessToken, "access");
17
+ const accessPayload: any = await jwt.verifyToken(accessToken, "access");
11
18
 
12
19
  if (accessPayload) {
13
- const user = await db.query.users.findFirst({
14
- where: eq(users.id, accessPayload.id as number),
15
- with: { role: true }
16
- });
20
+ const user = await provider.getUserById((accessPayload as any)?.id);
17
21
 
18
22
  if (!user) {
19
23
  cookie.deleteAuth(res);
@@ -21,13 +25,20 @@ export async function authMiddleware(req: Request, res: Response, next: NextFunc
21
25
  return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Unauthorized" });
22
26
  }
23
27
 
24
- res.locals.auth = {
25
- ...accessPayload,
26
- id: user.id,
27
- email: user.email,
28
- roleId: user.role?.id ?? null,
29
- role: user.role?.name ?? null
30
- };
28
+ let authCtx: any;
29
+ if (provider.getAuthContext) {
30
+ authCtx = await provider.getAuthContext(user, accessPayload);
31
+ } else {
32
+ authCtx = {
33
+ ...(accessPayload || {}),
34
+ id: (user as any).id,
35
+ email: (user as any).email,
36
+ roleId: (user as any).role?.id ?? (user as any).roleId ?? null,
37
+ role: (user as any).role?.name ?? (user as any).role ?? null,
38
+ ...(user as any)
39
+ };
40
+ }
41
+ res.locals.auth = authCtx;
31
42
  return next();
32
43
  }
33
44
  }
@@ -40,7 +51,7 @@ export async function authMiddleware(req: Request, res: Response, next: NextFunc
40
51
  return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Unauthorized" });
41
52
  }
42
53
 
43
- const refreshPayload = await jwt.verifyToken(refreshToken, "refresh");
54
+ const refreshPayload: any = await jwt.verifyToken(refreshToken, "refresh");
44
55
 
45
56
  if (!refreshPayload?.jti) {
46
57
  cookie.deleteAuth(res);
@@ -48,27 +59,27 @@ export async function authMiddleware(req: Request, res: Response, next: NextFunc
48
59
  return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Invalid token" });
49
60
  }
50
61
 
51
- const storedToken = await db.query.refreshTokens.findFirst({
52
- where: eq(refreshTokens.jti, refreshPayload.jti as string)
53
- });
62
+ const storedToken = await provider.findRefreshToken((refreshPayload as any)?.jti);
54
63
 
55
- if (!storedToken || storedToken.revoked) {
64
+ if (!storedToken || (storedToken as any).revoked) {
56
65
  cookie.deleteAuth(res);
57
66
  cookie.deleteRefresh(res);
58
67
  return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Invalid token" });
59
68
  }
60
69
 
61
- if (storedToken.expiresAt.getTime() < Date.now()) {
62
- await db.delete(refreshTokens).where(eq(refreshTokens.id, storedToken.id));
63
- cookie.deleteAuth(res);
64
- cookie.deleteRefresh(res);
65
- return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Invalid token" });
70
+ const expiresAt = (storedToken as any).expiresAt;
71
+ if (expiresAt) {
72
+ const exp = expiresAt instanceof Date ? expiresAt.getTime() : new Date(expiresAt).getTime();
73
+ if (!Number.isNaN(exp) && exp < Date.now()) {
74
+ if (provider.deleteRefreshToken) await provider.deleteRefreshToken((storedToken as any).id);
75
+ else if (provider.revokeRefreshToken) await provider.revokeRefreshToken((storedToken as any).id);
76
+ cookie.deleteAuth(res);
77
+ cookie.deleteRefresh(res);
78
+ return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Invalid token" });
79
+ }
66
80
  }
67
81
 
68
- const user = await db.query.users.findFirst({
69
- where: eq(users.id, refreshPayload.id as number),
70
- with: { role: true }
71
- });
82
+ const user = await provider.getUserById((refreshPayload as any)?.id);
72
83
 
73
84
  if (!user) {
74
85
  cookie.deleteAuth(res);
@@ -76,23 +87,39 @@ export async function authMiddleware(req: Request, res: Response, next: NextFunc
76
87
  return res.status(HttpStatusCodes.UNAUTHORIZED).json({ message: "Unauthorized" });
77
88
  }
78
89
 
90
+ let baseCtx: any;
91
+ if (provider.getAuthContext) {
92
+ baseCtx = await provider.getAuthContext(user, refreshPayload);
93
+ } else {
94
+ baseCtx = {
95
+ ...(refreshPayload || {}),
96
+ id: (user as any).id,
97
+ email: (user as any).email,
98
+ roleId: (user as any).role?.id ?? (user as any).roleId ?? null,
99
+ role: (user as any).role?.name ?? (user as any).role ?? null,
100
+ ...(user as any)
101
+ };
102
+ }
103
+
79
104
  const newAccessToken = await jwt.generateToken(
80
105
  {
81
- id: user.id,
82
- email: user.email,
83
- roleId: user.role?.id ?? null,
84
- role: user.role?.name ?? null
106
+ id: (user as any).id,
107
+ email: (user as any).email,
108
+ roleId: baseCtx?.roleId ?? (user as any).role?.id ?? (user as any).roleId ?? null,
109
+ role: baseCtx?.role ?? (user as any).role?.name ?? (user as any).role ?? null
85
110
  },
86
111
  "access"
87
112
  );
88
113
 
89
114
  await cookie.setAuth(res, newAccessToken.token);
90
115
  res.locals.auth = {
91
- id: user.id,
92
- email: user.email,
93
- roleId: user.role?.id ?? null,
94
- role: user.role?.name ?? null,
95
- type: "access"
116
+ ...(baseCtx || {}),
117
+ id: (user as any).id,
118
+ email: (user as any).email,
119
+ roleId: baseCtx?.roleId ?? (user as any).role?.id ?? (user as any).roleId ?? null,
120
+ role: baseCtx?.role ?? (user as any).role?.name ?? (user as any).role ?? null,
121
+ type: "access",
122
+ ...(user as any)
96
123
  };
97
124
  return next();
98
125
  }