@kyro-cms/admin 0.1.6 → 0.1.8

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 (179) hide show
  1. package/README.md +149 -51
  2. package/package.json +54 -5
  3. package/src/collections/auth/index.ts +2 -2
  4. package/src/collections/portfolio/index.ts +343 -0
  5. package/src/components/ActionBar.tsx +153 -16
  6. package/src/components/Admin.tsx +137 -28
  7. package/src/components/ApiExplorer.tsx +325 -0
  8. package/src/components/ApiKeysManager.tsx +563 -0
  9. package/src/components/AuditLogsPage.tsx +664 -0
  10. package/src/components/AutoForm.tsx +2155 -770
  11. package/src/components/BrandingHub.tsx +267 -0
  12. package/src/components/BulkActionsBar.tsx +3 -3
  13. package/src/components/CreateView.tsx +4 -4
  14. package/src/components/Dashboard.tsx +393 -0
  15. package/src/components/DetailView.tsx +200 -58
  16. package/src/components/DeveloperCenter.tsx +403 -0
  17. package/src/components/EnhancedListView.tsx +890 -0
  18. package/src/components/GraphQLExplorer.tsx +675 -0
  19. package/src/components/GraphQLPlayground.tsx +627 -0
  20. package/src/components/ListView.tsx +192 -54
  21. package/src/components/MediaGallery.tsx +1569 -0
  22. package/src/components/Modal.tsx +206 -0
  23. package/src/components/RestPlayground.tsx +951 -0
  24. package/src/components/Sidebar.astro +237 -0
  25. package/src/components/ThemeProvider.tsx +8 -2
  26. package/src/components/UserManagement.tsx +204 -0
  27. package/src/components/VersionHistoryPanel.tsx +3 -3
  28. package/src/components/WebhookManager.tsx +608 -0
  29. package/src/components/blocks/AccordionBlock.tsx +65 -0
  30. package/src/components/blocks/ArrayBlock.tsx +84 -0
  31. package/src/components/blocks/BlockEditModal.tsx +363 -0
  32. package/src/components/blocks/ButtonBlock.tsx +64 -0
  33. package/src/components/blocks/ChildBlocksTree.tsx +551 -0
  34. package/src/components/blocks/CodeBlock.tsx +114 -0
  35. package/src/components/blocks/ColumnsBlock.tsx +93 -0
  36. package/src/components/blocks/DividerBlock.tsx +43 -0
  37. package/src/components/blocks/FileBlock.tsx +63 -0
  38. package/src/components/blocks/HeadingBlock.tsx +59 -0
  39. package/src/components/blocks/HeroBlock.tsx +99 -0
  40. package/src/components/blocks/ImageBlock.tsx +82 -0
  41. package/src/components/blocks/LinkBlock.tsx +65 -0
  42. package/src/components/blocks/ListBlock.tsx +60 -0
  43. package/src/components/blocks/ParagraphBlock.tsx +61 -0
  44. package/src/components/blocks/RelationshipBlock.tsx +72 -0
  45. package/src/components/blocks/RichTextBlock.tsx +66 -0
  46. package/src/components/blocks/VStackBlock.tsx +61 -0
  47. package/src/components/blocks/VideoBlock.tsx +65 -0
  48. package/src/components/blocks/index.ts +10 -0
  49. package/src/components/fields/AccordionField.tsx +213 -0
  50. package/src/components/fields/ArrayField.tsx +241 -0
  51. package/src/components/fields/BlocksField.tsx +323 -0
  52. package/src/components/fields/ButtonField.tsx +53 -0
  53. package/src/components/fields/CheckboxField.tsx +18 -8
  54. package/src/components/fields/ChildrenField.tsx +48 -0
  55. package/src/components/fields/CodeField.tsx +294 -0
  56. package/src/components/fields/ColumnsField.tsx +137 -0
  57. package/src/components/fields/DateField.tsx +24 -12
  58. package/src/components/fields/EditorClient.tsx +537 -0
  59. package/src/components/fields/HeadingField.tsx +31 -0
  60. package/src/components/fields/HeroField.tsx +101 -0
  61. package/src/components/fields/JSONField.tsx +341 -0
  62. package/src/components/fields/LinkField.tsx +81 -0
  63. package/src/components/fields/ListField.tsx +74 -0
  64. package/src/components/fields/MarkdownField.tsx +260 -0
  65. package/src/components/fields/NumberField.tsx +25 -13
  66. package/src/components/fields/PortableTextField.tsx +155 -0
  67. package/src/components/fields/PortableTextRenderer.tsx +68 -0
  68. package/src/components/fields/RelationshipBlockField.tsx +233 -0
  69. package/src/components/fields/RelationshipField.tsx +278 -60
  70. package/src/components/fields/SelectField.tsx +28 -16
  71. package/src/components/fields/TextField.tsx +31 -15
  72. package/src/components/fields/UploadField.tsx +613 -0
  73. package/src/components/fields/VideoField.tsx +73 -0
  74. package/src/components/fields/extensions/blockComponents.tsx +247 -0
  75. package/src/components/fields/extensions/blocksStore.ts +273 -0
  76. package/src/components/fields/index.ts +24 -0
  77. package/src/components/index.ts +1 -2
  78. package/src/components/layout/Header.tsx +2 -2
  79. package/src/components/layout/Layout.tsx +3 -3
  80. package/src/components/ui/Badge.tsx +9 -4
  81. package/src/components/ui/BlockDrawer.tsx +79 -0
  82. package/src/components/ui/Button.tsx +1 -1
  83. package/src/components/ui/CommandPalette.tsx +362 -0
  84. package/src/components/ui/CommandPaletteWrapper.tsx +97 -0
  85. package/src/components/ui/Dropdown.tsx +1 -1
  86. package/src/components/ui/Modal.tsx +37 -12
  87. package/src/components/ui/PromptModal.tsx +94 -0
  88. package/src/components/ui/SlidePanel.tsx +43 -16
  89. package/src/components/ui/Toast.tsx +80 -14
  90. package/src/env.d.ts +16 -0
  91. package/src/env.ts +20 -0
  92. package/src/index.ts +0 -1
  93. package/src/layouts/AdminLayout.astro +164 -170
  94. package/src/layouts/AuthLayout.astro +23 -6
  95. package/src/lib/MediaService.ts +541 -0
  96. package/src/lib/api.ts +163 -0
  97. package/src/lib/auth/sqlite-adapter.ts +319 -0
  98. package/src/lib/config.ts +23 -7
  99. package/src/lib/dataStore.ts +188 -73
  100. package/src/lib/date-utils.ts +69 -0
  101. package/src/lib/db/adapter.ts +54 -0
  102. package/src/lib/db/drizzle-mysql-adapter.ts +194 -0
  103. package/src/lib/db/drizzle-mysql-auth-adapter.ts +327 -0
  104. package/src/lib/db/drizzle-postgres-adapter.ts +202 -0
  105. package/src/lib/db/drizzle-postgres-auth-adapter.ts +304 -0
  106. package/src/lib/db/drizzle-sqlite-adapter.ts +227 -0
  107. package/src/lib/db/drizzle-sqlite-auth-adapter.ts +548 -0
  108. package/src/lib/db/index.ts +449 -0
  109. package/src/lib/db/mongodb-adapter.ts +207 -0
  110. package/src/lib/db/mongodb-auth-adapter.ts +305 -0
  111. package/src/lib/db/schema/mysql-auth.ts +113 -0
  112. package/src/lib/db/schema/mysql-content.ts +20 -0
  113. package/src/lib/db/schema/postgres-auth.ts +116 -0
  114. package/src/lib/db/schema/postgres-content.ts +35 -0
  115. package/src/lib/db/schema/postgres-media.ts +52 -0
  116. package/src/lib/db/schema/postgres-settings.ts +11 -0
  117. package/src/lib/db/schema/sqlite-auth.ts +112 -0
  118. package/src/lib/db/schema/sqlite-content.ts +20 -0
  119. package/src/lib/db/version-adapter.ts +248 -0
  120. package/src/lib/graphql/index.ts +1 -0
  121. package/src/lib/graphql/schema.ts +443 -0
  122. package/src/lib/i18n.tsx +353 -0
  123. package/src/lib/rate-limit.ts +267 -0
  124. package/src/lib/slugify.ts +15 -0
  125. package/src/lib/storage.ts +374 -0
  126. package/src/lib/store.ts +85 -0
  127. package/src/lib/validation.ts +250 -0
  128. package/src/middleware.ts +70 -11
  129. package/src/pages/[collection]/[id].astro +178 -122
  130. package/src/pages/[collection]/index.astro +24 -156
  131. package/src/pages/admin/api-explorer.astro +98 -0
  132. package/src/pages/admin/graphql-explorer.astro +40 -0
  133. package/src/pages/admin/graphql.astro +97 -0
  134. package/src/pages/admin/index.astro +200 -139
  135. package/src/pages/admin/keys.astro +8 -0
  136. package/src/pages/admin/rest-playground.astro +44 -0
  137. package/src/pages/admin/webhooks.astro +8 -0
  138. package/src/pages/api/[collection]/[id]/publish.ts +52 -0
  139. package/src/pages/api/[collection]/[id]/unpublish.ts +42 -0
  140. package/src/pages/api/[collection]/[id]/versions.ts +66 -0
  141. package/src/pages/api/[collection]/[id].ts +114 -159
  142. package/src/pages/api/[collection]/index.ts +150 -230
  143. package/src/pages/api/auth/[id].ts +48 -69
  144. package/src/pages/api/auth/audit-logs.ts +20 -43
  145. package/src/pages/api/auth/login.ts +159 -45
  146. package/src/pages/api/auth/logout.ts +42 -24
  147. package/src/pages/api/auth/refresh.ts +119 -0
  148. package/src/pages/api/auth/register.ts +110 -40
  149. package/src/pages/api/auth/users.ts +22 -97
  150. package/src/pages/api/collections.ts +59 -0
  151. package/src/pages/api/globals/[slug]/test.ts +172 -0
  152. package/src/pages/api/globals/[slug].ts +42 -0
  153. package/src/pages/api/graphql.ts +90 -0
  154. package/src/pages/api/health.ts +417 -40
  155. package/src/pages/api/keys/[id].ts +26 -0
  156. package/src/pages/api/keys/index.ts +75 -0
  157. package/src/pages/api/media/[id].ts +309 -0
  158. package/src/pages/api/media/folders.ts +609 -0
  159. package/src/pages/api/media/index.ts +146 -0
  160. package/src/pages/api/media/resize.ts +267 -0
  161. package/src/pages/api/search.ts +82 -0
  162. package/src/pages/api/slug-availability.ts +70 -0
  163. package/src/pages/api/storage-config.ts +20 -0
  164. package/src/pages/api/storage-status.ts +206 -0
  165. package/src/pages/api/upload.ts +334 -0
  166. package/src/pages/api/webhooks/index.ts +71 -0
  167. package/src/pages/audit/index.astro +2 -104
  168. package/src/pages/login.astro +11 -11
  169. package/src/pages/media.astro +10 -0
  170. package/src/pages/preview/[collection]/[id].astro +178 -0
  171. package/src/pages/register.astro +13 -13
  172. package/src/pages/roles/index.astro +21 -21
  173. package/src/pages/settings/[slug].astro +162 -0
  174. package/src/pages/settings/index.astro +9 -0
  175. package/src/pages/users/[id].astro +29 -21
  176. package/src/pages/users/index.astro +22 -17
  177. package/src/pages/users/new.astro +18 -17
  178. package/src/styles/main.css +563 -128
  179. package/src/components/layout/Sidebar.tsx +0 -497
@@ -0,0 +1,202 @@
1
+ import type { CollectionConfig } from "@kyro-cms/core";
2
+ import type { DatabaseAdapter, DatabaseConfig } from "./adapter";
3
+ import { Pool } from "pg";
4
+ import { drizzle } from "drizzle-orm/postgres-js";
5
+ import { eq, desc, sql, and } from "drizzle-orm";
6
+ import { randomBytes } from "crypto";
7
+ import * as contentSchema from "./schema/postgres-content";
8
+
9
+ export class PostgresAdapter implements DatabaseAdapter {
10
+ private pool: Pool;
11
+ private db = drizzle(this.pool);
12
+ private initialized = false;
13
+
14
+ constructor(private config: DatabaseConfig) {
15
+ this.pool = new Pool({
16
+ connectionString: config.connectionString,
17
+ host: config.host,
18
+ port: config.port,
19
+ database: config.database,
20
+ user: config.username,
21
+ password: config.password,
22
+ min: config.poolMin || 5,
23
+ max: config.poolMax || 20,
24
+ });
25
+ }
26
+
27
+ initialize(collections: Record<string, CollectionConfig>) {
28
+ if (this.initialized) return;
29
+ this.initialized = true;
30
+ }
31
+
32
+ private getTimestamp(): string {
33
+ return new Date().toISOString();
34
+ }
35
+
36
+ private async generateId(slug: string): Promise<string> {
37
+ const result = await this.db
38
+ .select({ count: sql<number>`count(*)` })
39
+ .from(contentSchema.documents)
40
+ .where(eq(contentSchema.documents.collection, slug));
41
+ return `${slug}-${(result[0]?.count || 0) + 1}`;
42
+ }
43
+
44
+ async find<T = any>(
45
+ slug: string,
46
+ options: { page?: number; limit?: number } = {},
47
+ ): Promise<{
48
+ docs: T[];
49
+ totalDocs: number;
50
+ totalPages: number;
51
+ page: number;
52
+ }> {
53
+ const page = options.page || 1;
54
+ const limit = options.limit || 25;
55
+ const start = (page - 1) * limit;
56
+
57
+ const countResult = await this.db
58
+ .select({ count: sql<number>`count(*)` })
59
+ .from(contentSchema.documents)
60
+ .where(eq(contentSchema.documents.collection, slug));
61
+ const count = countResult[0]?.count || 0;
62
+
63
+ const docs = await this.db
64
+ .select({ data: contentSchema.documents.data })
65
+ .from(contentSchema.documents)
66
+ .where(eq(contentSchema.documents.collection, slug))
67
+ .orderBy(desc(contentSchema.documents.createdAt))
68
+ .limit(limit)
69
+ .offset(start);
70
+
71
+ return {
72
+ docs: docs.map((d) => d.data as T),
73
+ totalDocs: count,
74
+ totalPages: Math.ceil(count / limit),
75
+ page,
76
+ };
77
+ }
78
+
79
+ async findById<T = any>(slug: string, id: string): Promise<T | null> {
80
+ const doc = await this.db
81
+ .select({ data: contentSchema.documents.data })
82
+ .from(contentSchema.documents)
83
+ .where(
84
+ and(
85
+ eq(contentSchema.documents.collection, slug),
86
+ eq(contentSchema.documents.id, id),
87
+ ),
88
+ )
89
+ .get();
90
+ return (doc?.data as T) || null;
91
+ }
92
+
93
+ async create<T = any>(slug: string, data: Partial<T>): Promise<T> {
94
+ const now = this.getTimestamp();
95
+ const id = await this.generateId(slug);
96
+ const newDoc = {
97
+ id,
98
+ collection: slug,
99
+ data: { id, ...data, createdAt: now, updatedAt: now },
100
+ createdAt: new Date(now),
101
+ updatedAt: new Date(now),
102
+ };
103
+ await this.db.insert(contentSchema.documents).values(newDoc as any);
104
+ return newDoc.data as T;
105
+ }
106
+
107
+ async update<T = any>(
108
+ slug: string,
109
+ id: string,
110
+ data: Partial<T>,
111
+ ): Promise<T | null> {
112
+ const existing = await this.findById<T>(slug, id);
113
+ if (!existing) return null;
114
+ const now = this.getTimestamp();
115
+ const updated = { ...existing, ...data, id, updatedAt: now };
116
+ await this.db
117
+ .update(contentSchema.documents)
118
+ .set({ data: updated, updatedAt: new Date(now) })
119
+ .where(
120
+ and(
121
+ eq(contentSchema.documents.collection, slug),
122
+ eq(contentSchema.documents.id, id),
123
+ ),
124
+ );
125
+ return updated as T;
126
+ }
127
+
128
+ async delete(slug: string, id: string): Promise<boolean> {
129
+ await this.db
130
+ .delete(contentSchema.documents)
131
+ .where(
132
+ and(
133
+ eq(contentSchema.documents.collection, slug),
134
+ eq(contentSchema.documents.id, id),
135
+ ),
136
+ );
137
+ return true;
138
+ }
139
+
140
+ async findGlobal<T = any>(slug: string): Promise<T> {
141
+ const global = await this.db
142
+ .select({ data: contentSchema.globals.data })
143
+ .from(contentSchema.globals)
144
+ .where(eq(contentSchema.globals.slug, slug))
145
+ .get();
146
+ return (global?.data as T) || ({} as T);
147
+ }
148
+
149
+ async updateGlobal<T = any>(slug: string, data: Partial<T>): Promise<T> {
150
+ const now = this.getTimestamp();
151
+ const current = await this.findGlobal<T>(slug);
152
+ const updated = { ...current, ...data };
153
+ await this.db
154
+ .insert(contentSchema.globals)
155
+ .values({ slug, data: updated, updatedAt: new Date(now) })
156
+ .onConflictDoUpdate({
157
+ target: contentSchema.globals.slug,
158
+ set: { data: updated, updatedAt: new Date(now) },
159
+ });
160
+ return updated as T;
161
+ }
162
+
163
+ async seedGlobal(slug: string, data: any): Promise<void> {
164
+ const now = this.getTimestamp();
165
+ await this.db
166
+ .insert(contentSchema.globals)
167
+ .values({ slug, data, updatedAt: new Date(now) })
168
+ .onConflictDoNothing();
169
+ }
170
+
171
+ async count(slug: string): Promise<number> {
172
+ const result = await this.db
173
+ .select({ count: sql<number>`count(*)` })
174
+ .from(contentSchema.documents)
175
+ .where(eq(contentSchema.documents.collection, slug));
176
+ return result[0]?.count || 0;
177
+ }
178
+
179
+ async seed(slug: string, docs: any[]): Promise<void> {
180
+ const now = this.getTimestamp();
181
+ const values = docs.map((doc, i) => ({
182
+ id: doc.id || `${slug}-${i + 1}`,
183
+ collection: slug,
184
+ data: {
185
+ ...doc,
186
+ createdAt: doc.createdAt || now,
187
+ updatedAt: doc.updatedAt || now,
188
+ },
189
+ createdAt: new Date(now),
190
+ updatedAt: new Date(now),
191
+ }));
192
+ await this.db.insert(contentSchema.documents).values(values as any);
193
+ }
194
+
195
+ async isSeeded(slug: string): Promise<boolean> {
196
+ return (await this.count(slug)) > 0;
197
+ }
198
+
199
+ async close(): Promise<void> {
200
+ await this.pool.end();
201
+ }
202
+ }
@@ -0,0 +1,304 @@
1
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
2
+ import type { AuthAdapter, AuthUser, Session, UserRole } from "@kyro-cms/core";
3
+ import { eq, and, gt, desc, sql } from "drizzle-orm";
4
+ import bcrypt from "bcryptjs";
5
+ import { randomBytes } from "crypto";
6
+ import postgres from "postgres";
7
+ import { drizzle } from "drizzle-orm/postgres-js";
8
+ import {
9
+ users,
10
+ sessions,
11
+ roles,
12
+ auditLogs,
13
+ passwordHistory,
14
+ lockouts,
15
+ } from "./schema/postgres-auth";
16
+ import type { AuditLog, AuditLogFilter } from "@kyro-cms/core";
17
+
18
+ export interface PostgresAuthAdapterOptions {
19
+ db?: PostgresJsDatabase;
20
+ connectionString?: string;
21
+ sessionTTL?: number;
22
+ refreshTokenTTL?: number;
23
+ }
24
+
25
+ const DEFAULT_SESSION_TTL = 86400;
26
+ const DEFAULT_REFRESH_TTL = 604800;
27
+
28
+ export class PostgresAuthAdapter implements AuthAdapter {
29
+ private db: PostgresJsDatabase;
30
+ private sessionTTL: number;
31
+ private refreshTTL: number;
32
+
33
+ constructor(private options: PostgresAuthAdapterOptions) {
34
+ if (options.db) {
35
+ this.db = options.db;
36
+ } else if (options.connectionString) {
37
+ const client = postgres(options.connectionString, { max: 10 });
38
+ this.db = drizzle(client);
39
+ } else {
40
+ throw new Error("Either db or connectionString must be provided");
41
+ }
42
+ this.sessionTTL = options.sessionTTL || DEFAULT_SESSION_TTL;
43
+ this.refreshTTL = options.refreshTokenTTL || DEFAULT_REFRESH_TTL;
44
+ }
45
+
46
+ private generateId(): string {
47
+ return crypto.randomUUID();
48
+ }
49
+
50
+ async createUser(data: {
51
+ email: string;
52
+ passwordHash: string;
53
+ role: UserRole;
54
+ tenantId?: string;
55
+ }): Promise<AuthUser> {
56
+ const now = new Date();
57
+ const [user] = await this.db
58
+ .insert(users)
59
+ .values({
60
+ email: data.email.toLowerCase(),
61
+ passwordHash: data.passwordHash,
62
+ role: data.role,
63
+ tenantId: data.tenantId,
64
+ })
65
+ .returning();
66
+ return {
67
+ id: user.id,
68
+ email: user.email,
69
+ role: user.role as UserRole,
70
+ tenantId: user.tenantId || undefined,
71
+ createdAt: user.createdAt.toISOString(),
72
+ updatedAt: user.updatedAt.toISOString(),
73
+ };
74
+ }
75
+
76
+ async findUserByEmail(email: string): Promise<AuthUser | null> {
77
+ const result = await this.db
78
+ .select()
79
+ .from(users)
80
+ .where(eq(users.email, email.toLowerCase()))
81
+ .limit(1);
82
+ const user = result[0];
83
+ if (!user) return null;
84
+ return {
85
+ id: user.id,
86
+ email: user.email,
87
+ role: user.role as UserRole,
88
+ tenantId: user.tenantId || undefined,
89
+ createdAt: user.createdAt.toISOString(),
90
+ updatedAt: user.updatedAt.toISOString(),
91
+ };
92
+ }
93
+
94
+ async findUserById(id: string): Promise<AuthUser | null> {
95
+ const result = await this.db
96
+ .select()
97
+ .from(users)
98
+ .where(eq(users.id, id))
99
+ .limit(1);
100
+ const user = result[0];
101
+ if (!user) return null;
102
+ return {
103
+ id: user.id,
104
+ email: user.email,
105
+ role: user.role as UserRole,
106
+ tenantId: user.tenantId || undefined,
107
+ createdAt: user.createdAt.toISOString(),
108
+ updatedAt: user.updatedAt.toISOString(),
109
+ };
110
+ }
111
+
112
+ async updateUser(
113
+ id: string,
114
+ data: Partial<AuthUser>,
115
+ ): Promise<AuthUser | null> {
116
+ const updates: Record<string, unknown> = { updatedAt: new Date() };
117
+ if (data.email) updates.email = data.email.toLowerCase();
118
+ if (data.role) updates.role = data.role;
119
+ if (data.passwordHash) updates.passwordHash = data.passwordHash;
120
+
121
+ const result = await this.db
122
+ .update(users)
123
+ .set(updates)
124
+ .where(eq(users.id, id))
125
+ .returning();
126
+ const user = result[0];
127
+ if (!user) return null;
128
+ return {
129
+ id: user.id,
130
+ email: user.email,
131
+ role: user.role as UserRole,
132
+ tenantId: user.tenantId || undefined,
133
+ createdAt: user.createdAt.toISOString(),
134
+ updatedAt: user.updatedAt.toISOString(),
135
+ };
136
+ }
137
+
138
+ async deleteUser(id: string): Promise<boolean> {
139
+ await this.db.delete(users).where(eq(users.id, id));
140
+ return true;
141
+ }
142
+
143
+ async verifyPassword(password: string, hash: string): Promise<boolean> {
144
+ return bcrypt.compare(password, hash);
145
+ }
146
+
147
+ async hashPassword(password: string): Promise<string> {
148
+ return bcrypt.hash(password, 10);
149
+ }
150
+
151
+ async createSession(
152
+ userId: string,
153
+ data?: { ipAddress?: string; userAgent?: string },
154
+ ): Promise<Session> {
155
+ const now = new Date();
156
+ const expiresAt = new Date(now.getTime() + this.sessionTTL * 1000);
157
+ const token = randomBytes(32).toString("hex");
158
+ const refreshToken = randomBytes(32).toString("hex");
159
+
160
+ const result = await this.db
161
+ .insert(sessions)
162
+ .values({
163
+ userId,
164
+ token,
165
+ refreshToken,
166
+ expiresAt,
167
+ })
168
+ .returning();
169
+
170
+ return {
171
+ id: result[0].id,
172
+ token: result[0].token,
173
+ refreshToken: result[0].refreshToken || undefined,
174
+ userId: result[0].userId,
175
+ expiresAt: result[0].expiresAt.toISOString(),
176
+ createdAt: now.toISOString(),
177
+ ipAddress: data?.ipAddress,
178
+ userAgent: data?.userAgent,
179
+ };
180
+ }
181
+
182
+ async findSessionByToken(token: string): Promise<Session | null> {
183
+ const now = new Date();
184
+ const result = await this.db
185
+ .select()
186
+ .from(sessions)
187
+ .where(and(eq(sessions.token, token), gt(sessions.expiresAt, now)))
188
+ .limit(1);
189
+ const session = result[0];
190
+ if (!session) return null;
191
+ return {
192
+ id: session.id,
193
+ token: session.token,
194
+ refreshToken: session.refreshToken || undefined,
195
+ userId: session.userId,
196
+ expiresAt: session.expiresAt.toISOString(),
197
+ createdAt: session.createdAt.toISOString(),
198
+ };
199
+ }
200
+
201
+ async deleteSession(sessionId: string): Promise<boolean> {
202
+ await this.db.delete(sessions).where(eq(sessions.token, sessionId));
203
+ return true;
204
+ }
205
+
206
+ async deleteUserSessions(userId: string): Promise<number> {
207
+ await this.db.delete(sessions).where(eq(sessions.userId, userId));
208
+ return 1;
209
+ }
210
+
211
+ async hasAnyUsers(): Promise<boolean> {
212
+ const result = await this.db
213
+ .select({ count: sql<number>`count(*)` })
214
+ .from(users);
215
+ return Number(result[0]?.count || 0) > 0;
216
+ }
217
+
218
+ async findAuditLogs(
219
+ filter: AuditLogFilter,
220
+ ): Promise<{ logs: AuditLog[]; total: number }> {
221
+ const {
222
+ limit = 50,
223
+ offset = 0,
224
+ userId,
225
+ action,
226
+ success,
227
+ startDate,
228
+ endDate,
229
+ } = filter;
230
+
231
+ const conditions = [];
232
+ if (userId) conditions.push(eq(auditLogs.userId, userId));
233
+ if (action) {
234
+ if (Array.isArray(action)) {
235
+ conditions.push(sql`${auditLogs.action} = ANY(${action})`);
236
+ } else {
237
+ conditions.push(eq(auditLogs.action, action));
238
+ }
239
+ }
240
+ if (success !== undefined) conditions.push(eq(auditLogs.success, success));
241
+ if (startDate) conditions.push(sql`${auditLogs.createdAt} >= ${startDate}`);
242
+ if (endDate) conditions.push(sql`${auditLogs.createdAt} <= ${endDate}`);
243
+
244
+ const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
245
+
246
+ const countResult = await this.db
247
+ .select({ count: sql<number>`count(*)` })
248
+ .from(auditLogs)
249
+ .where(whereClause);
250
+
251
+ const logs = await this.db
252
+ .select()
253
+ .from(auditLogs)
254
+ .where(whereClause)
255
+ .orderBy(desc(auditLogs.createdAt))
256
+ .limit(limit)
257
+ .offset(offset);
258
+
259
+ return {
260
+ logs: logs.map((log) => ({
261
+ id: log.id,
262
+ timestamp: log.createdAt,
263
+ action: log.action as AuditLog["action"],
264
+ userId: log.userId || undefined,
265
+ userEmail: log.userEmail || undefined,
266
+ role: log.role || undefined,
267
+ resource: log.resource,
268
+ ipAddress: log.ipAddress || undefined,
269
+ userAgent: log.userAgent || undefined,
270
+ success: log.success,
271
+ error: log.error || undefined,
272
+ metadata: log.metadata || undefined,
273
+ })),
274
+ total: Number(countResult[0]?.count || 0),
275
+ };
276
+ }
277
+
278
+ async createAuditLog(
279
+ data: Omit<AuditLog, "id" | "timestamp">,
280
+ ): Promise<AuditLog> {
281
+ const id = this.generateId();
282
+ const timestamp = new Date();
283
+
284
+ await this.db.insert(auditLogs).values({
285
+ id,
286
+ action: data.action,
287
+ userId: data.userId,
288
+ userEmail: data.userEmail,
289
+ role: data.role,
290
+ resource: data.resource,
291
+ ipAddress: data.ipAddress,
292
+ userAgent: data.userAgent,
293
+ success: data.success,
294
+ error: data.error,
295
+ metadata: data.metadata,
296
+ });
297
+
298
+ return {
299
+ ...data,
300
+ id,
301
+ timestamp,
302
+ };
303
+ }
304
+ }