openadminjs 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 (216) hide show
  1. package/dist/create-project.js +38 -6
  2. package/dist/create-project.test.js +69 -24
  3. package/dist/index.js +16 -5
  4. package/package.json +4 -2
  5. package/template/.env.example +2 -2
  6. package/template/README.md +24 -3
  7. package/template/apps/admin/app/api/auth/login/route.ts +51 -0
  8. package/template/apps/admin/app/api/auth/logout/route.ts +11 -0
  9. package/template/apps/admin/app/api/auth/refresh/route.ts +46 -0
  10. package/template/apps/admin/app/api-tokens/page.tsx +253 -0
  11. package/template/apps/admin/app/audit-logs/page.tsx +5 -0
  12. package/template/apps/admin/app/dashboard/page.tsx +392 -0
  13. package/template/apps/admin/app/files/page.tsx +5 -0
  14. package/template/apps/admin/app/globals.css +206 -0
  15. package/template/apps/admin/app/jobs/page.tsx +19 -0
  16. package/template/apps/admin/app/layout.tsx +57 -0
  17. package/template/apps/admin/app/login/page.test.tsx +18 -0
  18. package/template/apps/admin/app/login/page.tsx +161 -0
  19. package/template/apps/admin/app/login/safe-next-param.ts +4 -0
  20. package/template/apps/admin/app/notifications/page.tsx +146 -0
  21. package/template/apps/admin/app/page.tsx +5 -0
  22. package/template/apps/admin/app/plugins/page.tsx +407 -0
  23. package/template/apps/admin/app/profile/page.tsx +116 -0
  24. package/template/apps/admin/app/resources/[resource]/[id]/edit/page.tsx +45 -0
  25. package/template/apps/admin/app/resources/[resource]/[id]/page.tsx +449 -0
  26. package/template/apps/admin/app/resources/[resource]/create/page.tsx +34 -0
  27. package/template/apps/admin/app/resources/[resource]/page.tsx +100 -0
  28. package/template/apps/admin/app/settings/page.tsx +233 -0
  29. package/template/apps/admin/components/ai-assistant-widget.tsx +684 -0
  30. package/template/apps/admin/components/app-shell.tsx +305 -0
  31. package/template/apps/admin/components/auth-guard.test.tsx +55 -0
  32. package/template/apps/admin/components/auth-guard.tsx +39 -0
  33. package/template/apps/admin/components/jobs-panel.tsx +103 -0
  34. package/template/apps/admin/components/logo.tsx +30 -0
  35. package/template/apps/admin/components/resource-form.tsx +349 -0
  36. package/template/apps/admin/components/resource-table.tsx +277 -0
  37. package/template/apps/admin/lib/ai-events.ts +23 -0
  38. package/template/apps/admin/lib/api.test.ts +118 -0
  39. package/template/apps/admin/lib/api.ts +135 -0
  40. package/template/apps/admin/lib/auth-flow.e2e.test.ts +79 -0
  41. package/template/apps/admin/lib/brand.ts +14 -0
  42. package/template/apps/admin/lib/locale.ts +49 -0
  43. package/template/apps/admin/lib/tokens.ts +93 -0
  44. package/template/apps/admin/middleware.ts +58 -0
  45. package/template/apps/admin/next-env.d.ts +6 -0
  46. package/template/apps/admin/next.config.mjs +7 -0
  47. package/template/apps/admin/package.json +44 -0
  48. package/template/apps/admin/postcss.config.mjs +6 -0
  49. package/template/apps/admin/public/brand/apple-touch-icon.png +0 -0
  50. package/template/apps/admin/public/brand/favicon.svg +1 -0
  51. package/template/apps/admin/public/brand/og-image.png +0 -0
  52. package/template/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
  53. package/template/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
  54. package/template/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
  55. package/template/apps/admin/tailwind.config.ts +37 -0
  56. package/template/apps/admin/tsconfig.json +23 -0
  57. package/template/apps/admin/vitest.config.ts +7 -0
  58. package/template/apps/api/package.json +56 -0
  59. package/template/apps/api/plugins.manifest.example.json +34 -0
  60. package/template/apps/api/plugins.manifest.json +4 -0
  61. package/template/apps/api/src/access/catalog.ts +112 -0
  62. package/template/apps/api/src/access/derive-permissions.test.ts +26 -0
  63. package/template/apps/api/src/access/derive-permissions.ts +36 -0
  64. package/template/apps/api/src/access/public-catalog.ts +28 -0
  65. package/template/apps/api/src/admin/admin-ai.controller.ts +125 -0
  66. package/template/apps/api/src/admin/admin-ai.events.ts +23 -0
  67. package/template/apps/api/src/admin/admin-ai.service.ts +1271 -0
  68. package/template/apps/api/src/admin/admin-analytics.service.ts +164 -0
  69. package/template/apps/api/src/admin/admin-plugins.controller.ts +32 -0
  70. package/template/apps/api/src/admin/admin-plugins.service.ts +267 -0
  71. package/template/apps/api/src/admin/admin-resource.service.test.ts +118 -0
  72. package/template/apps/api/src/admin/admin-resource.service.ts +375 -0
  73. package/template/apps/api/src/admin/admin.controller.ts +72 -0
  74. package/template/apps/api/src/admin/admin.module.ts +30 -0
  75. package/template/apps/api/src/admin/dto/plugins.dto.ts +55 -0
  76. package/template/apps/api/src/admin/validate-resource-payload.test.ts +44 -0
  77. package/template/apps/api/src/admin/validate-resource-payload.ts +103 -0
  78. package/template/apps/api/src/app.module.ts +45 -0
  79. package/template/apps/api/src/auth/auth.controller.ts +70 -0
  80. package/template/apps/api/src/auth/auth.dto.ts +49 -0
  81. package/template/apps/api/src/auth/auth.module.ts +30 -0
  82. package/template/apps/api/src/auth/auth.service.test.ts +75 -0
  83. package/template/apps/api/src/auth/auth.service.ts +231 -0
  84. package/template/apps/api/src/common/auth-realm.decorator.ts +6 -0
  85. package/template/apps/api/src/common/auth.guard.test.ts +61 -0
  86. package/template/apps/api/src/common/auth.guard.ts +78 -0
  87. package/template/apps/api/src/common/casl-ability.factory.test.ts +33 -0
  88. package/template/apps/api/src/common/casl-ability.factory.ts +41 -0
  89. package/template/apps/api/src/common/current-user.decorator.ts +6 -0
  90. package/template/apps/api/src/common/permission.decorator.ts +7 -0
  91. package/template/apps/api/src/common/permissions.guard.ts +31 -0
  92. package/template/apps/api/src/common/prisma.service.ts +13 -0
  93. package/template/apps/api/src/health/health.controller.ts +25 -0
  94. package/template/apps/api/src/mail/mail.module.ts +9 -0
  95. package/template/apps/api/src/mail/mail.service.ts +115 -0
  96. package/template/apps/api/src/main.ts +37 -0
  97. package/template/apps/api/src/plugins/bootstrap.ts +4 -0
  98. package/template/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
  99. package/template/apps/api/src/plugins/bundled/hello.plugin.ts +19 -0
  100. package/template/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
  101. package/template/apps/api/src/plugins/bundled/registry.ts +13 -0
  102. package/template/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
  103. package/template/apps/api/src/plugins/manifest-path.ts +35 -0
  104. package/template/apps/api/src/plugins/manifest.schema.test.ts +36 -0
  105. package/template/apps/api/src/plugins/manifest.schema.ts +58 -0
  106. package/template/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
  107. package/template/apps/api/src/plugins/plugin-loader.ts +134 -0
  108. package/template/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
  109. package/template/apps/api/src/plugins/plugin-runtime.ts +85 -0
  110. package/template/apps/api/src/queue/queue.controller.ts +28 -0
  111. package/template/apps/api/src/queue/queue.module.ts +23 -0
  112. package/template/apps/api/src/queue/queue.processor.ts +47 -0
  113. package/template/apps/api/src/queue/queue.service.ts +50 -0
  114. package/template/apps/api/src/resources/categories.resource.ts +21 -0
  115. package/template/apps/api/src/resources/commerce.resource.ts +157 -0
  116. package/template/apps/api/src/resources/operations.resource.ts +111 -0
  117. package/template/apps/api/src/resources/posts.resource.ts +88 -0
  118. package/template/apps/api/src/resources/registry.ts +27 -0
  119. package/template/apps/api/src/resources/resource-hooks.install.ts +18 -0
  120. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +72 -0
  121. package/template/apps/api/src/resources/resource-hooks.registry.ts +66 -0
  122. package/template/apps/api/src/resources/resource-hooks.runner.ts +93 -0
  123. package/template/apps/api/src/resources/system.resource.ts +51 -0
  124. package/template/apps/api/src/resources/users.resource.ts +19 -0
  125. package/template/apps/api/src/store/payment/payment.controller.ts +98 -0
  126. package/template/apps/api/src/store/payment/payment.module.ts +14 -0
  127. package/template/apps/api/src/store/payment/payment.provider.ts +38 -0
  128. package/template/apps/api/src/store/payment/payment.service.ts +235 -0
  129. package/template/apps/api/src/store/store.controller.ts +26 -0
  130. package/template/apps/api/src/store/store.module.ts +12 -0
  131. package/template/apps/api/src/test-setup.ts +1 -0
  132. package/template/apps/api/tsconfig.json +11 -0
  133. package/template/apps/api/vitest.config.ts +21 -0
  134. package/template/apps/web/lib/openadmin-client.ts +11 -0
  135. package/template/apps/web/lib/seo.test.ts +41 -0
  136. package/template/apps/web/lib/seo.ts +24 -13
  137. package/template/apps/web/next-env.d.ts +4 -0
  138. package/template/apps/web/package.json +2 -1
  139. package/template/apps/web/test/next-stub.ts +7 -0
  140. package/template/apps/web/vitest.config.ts +19 -0
  141. package/template/package.json +18 -11
  142. package/template/packages/auth/package.json +17 -0
  143. package/template/packages/auth/src/index.test.ts +10 -0
  144. package/template/packages/auth/src/index.ts +17 -0
  145. package/template/packages/auth/tsconfig.json +8 -0
  146. package/template/packages/brand/apps/admin/public/brand/apple-touch-icon.png +0 -0
  147. package/template/packages/brand/apps/admin/public/brand/favicon.svg +1 -0
  148. package/template/packages/brand/apps/admin/public/brand/og-image.png +0 -0
  149. package/template/packages/brand/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
  150. package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
  151. package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
  152. package/template/packages/brand/apps/web/public/brand/apple-touch-icon.png +0 -0
  153. package/template/packages/brand/apps/web/public/brand/favicon.svg +1 -0
  154. package/template/packages/brand/apps/web/public/brand/og-image.png +0 -0
  155. package/template/packages/brand/apps/web/public/brand/openadminjs-icon-new.png +0 -0
  156. package/template/packages/brand/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
  157. package/template/packages/brand/apps/web/public/brand/openadminjs-logo-new.png +0 -0
  158. package/template/packages/brand/package.json +19 -0
  159. package/template/packages/brand/site/assets/brand/favicon.svg +1 -0
  160. package/template/packages/brand/site/assets/brand/og-image.svg +1 -0
  161. package/template/packages/brand/site/assets/brand/openadminjs-icon.svg +1 -0
  162. package/template/packages/brand/site/assets/brand/openadminjs-logo-dark.svg +1 -0
  163. package/template/packages/brand/site/assets/brand/openadminjs-logo-horizontal.svg +1 -0
  164. package/template/packages/brand/site/assets/brand/openadminjs-logo-monochrome.svg +1 -0
  165. package/template/packages/brand/site/assets/brand/openadminjs-logo.svg +1 -0
  166. package/template/packages/brand/src/generate-assets.mjs +182 -0
  167. package/template/packages/brand/src/index.test.ts +9 -0
  168. package/template/packages/brand/src/index.ts +7 -0
  169. package/template/packages/brand/tsconfig.json +7 -0
  170. package/template/packages/core/package.json +20 -0
  171. package/template/packages/core/src/index.js +1 -0
  172. package/template/packages/core/src/index.test.ts +27 -0
  173. package/template/packages/core/src/index.ts +61 -0
  174. package/template/packages/core/tsconfig.json +8 -0
  175. package/template/packages/mail/package.json +18 -0
  176. package/template/packages/mail/src/index.test.ts +23 -0
  177. package/template/packages/mail/src/index.ts +246 -0
  178. package/template/packages/mail/tsconfig.json +5 -0
  179. package/template/packages/notifications/package.json +16 -0
  180. package/template/packages/notifications/src/index.test.ts +9 -0
  181. package/template/packages/notifications/src/index.ts +5 -0
  182. package/template/packages/notifications/tsconfig.json +5 -0
  183. package/template/packages/payments/package.json +15 -0
  184. package/template/packages/payments/src/index.ts +256 -0
  185. package/template/packages/payments/tsconfig.json +9 -0
  186. package/template/packages/permissions/package.json +17 -0
  187. package/template/packages/permissions/src/blueprints.js +57 -0
  188. package/template/packages/permissions/src/blueprints.test.ts +62 -0
  189. package/template/packages/permissions/src/blueprints.ts +89 -0
  190. package/template/packages/permissions/src/index.js +11 -0
  191. package/template/packages/permissions/src/index.test.ts +34 -0
  192. package/template/packages/permissions/src/index.ts +22 -0
  193. package/template/packages/permissions/tsconfig.json +8 -0
  194. package/template/packages/plugin-sdk/package.json +26 -0
  195. package/template/packages/plugin-sdk/src/hooks.ts +135 -0
  196. package/template/packages/plugin-sdk/src/index.ts +42 -0
  197. package/template/packages/plugin-sdk/src/sdk.test.ts +13 -0
  198. package/template/packages/plugin-sdk/tsconfig.json +8 -0
  199. package/template/packages/plugin-sdk/vitest.config.ts +5 -0
  200. package/template/packages/queue/package.json +16 -0
  201. package/template/packages/queue/src/index.test.ts +12 -0
  202. package/template/packages/queue/src/index.ts +6 -0
  203. package/template/packages/queue/tsconfig.json +5 -0
  204. package/template/packages/resource/package.json +17 -0
  205. package/template/packages/resource/src/index.js +177 -0
  206. package/template/packages/resource/src/index.test.ts +151 -0
  207. package/template/packages/resource/src/index.ts +344 -0
  208. package/template/packages/resource/tsconfig.json +8 -0
  209. package/template/packages/storage/package.json +16 -0
  210. package/template/packages/storage/src/index.test.ts +10 -0
  211. package/template/packages/storage/src/index.ts +23 -0
  212. package/template/packages/storage/tsconfig.json +5 -0
  213. package/template/prisma/migrations/20260505151751_baseline_init_all_tables/migration.sql +371 -0
  214. package/template/prisma/migrations/migration_lock.toml +3 -0
  215. package/template/prisma/schema.prisma +291 -0
  216. package/template/prisma/seed.ts +217 -0
@@ -0,0 +1,45 @@
1
+ import "./resources/resource-hooks.install";
2
+ import "./plugins/bootstrap";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { Module } from "@nestjs/common";
6
+ import { APP_INTERCEPTOR } from "@nestjs/core";
7
+ import { ConfigModule } from "@nestjs/config";
8
+ import { ThrottlerModule } from "@nestjs/throttler";
9
+ import { PrismaService } from "./common/prisma.service";
10
+ import { AuthModule } from "./auth/auth.module";
11
+ import { AdminModule } from "./admin/admin.module";
12
+ import { HealthController } from "./health/health.controller";
13
+ import { QueueModule } from "./queue/queue.module";
14
+ import { StoreModule } from "./store/store.module";
15
+ import { MailModule } from "./mail/mail.module";
16
+ import { PluginApiInterceptor } from "./plugins/plugin-api.interceptor";
17
+
18
+ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "api", ".env")].filter((p) =>
19
+ existsSync(p)
20
+ );
21
+
22
+ @Module({
23
+ imports: [
24
+ ConfigModule.forRoot({
25
+ isGlobal: true,
26
+ envFilePath: envFilePath.length > 0 ? envFilePath : [".env"]
27
+ }),
28
+ ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]),
29
+ AuthModule,
30
+ AdminModule,
31
+ MailModule,
32
+ QueueModule,
33
+ StoreModule
34
+ ],
35
+ controllers: [HealthController],
36
+ providers: [
37
+ PrismaService,
38
+ {
39
+ provide: APP_INTERCEPTOR,
40
+ useClass: PluginApiInterceptor
41
+ }
42
+ ],
43
+ exports: [PrismaService]
44
+ })
45
+ export class AppModule {}
@@ -0,0 +1,70 @@
1
+ import { Body, Controller, Get, Inject, Post, Req, UseGuards } from "@nestjs/common";
2
+ import { Throttle } from "@nestjs/throttler";
3
+ import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
4
+ import { AuthGuard } from "../common/auth.guard";
5
+ import type { RequestUser } from "../common/auth.guard";
6
+ import { RequireAuthRealm } from "../common/auth-realm.decorator";
7
+ import { CurrentUser } from "../common/current-user.decorator";
8
+ import { AuthService } from "./auth.service";
9
+ import { ForgotPasswordDto, LoginDto, RefreshDto, ResetPasswordDto, VerifyEmailDto } from "./auth.dto";
10
+
11
+ @Controller("auth")
12
+ export class AuthController {
13
+ constructor(@Inject(AuthService) private readonly auth: AuthService) {}
14
+
15
+ @Throttle({ default: { limit: 5, ttl: 60000 } })
16
+ @Post("login")
17
+ login(@Body() dto: LoginDto, @Req() req: Request & { ip?: string; headers: Record<string, string> }) {
18
+ const realm = dto.realm ?? DEFAULT_AUTH_REALM;
19
+ return this.auth.login(
20
+ dto.email,
21
+ dto.password,
22
+ {
23
+ ipAddress: req.ip,
24
+ userAgent: req.headers["user-agent"]
25
+ },
26
+ realm
27
+ );
28
+ }
29
+
30
+ @Post("refresh")
31
+ refresh(@Body() dto: RefreshDto) {
32
+ const realm = dto.realm ?? DEFAULT_AUTH_REALM;
33
+ return this.auth.refresh(dto.refreshToken, realm);
34
+ }
35
+
36
+ @UseGuards(AuthGuard)
37
+ @Post("logout")
38
+ logout(@CurrentUser() user: { id: string }, @Req() req: Request & { ip?: string; headers: Record<string, string> }) {
39
+ return this.auth.logout(user.id, { ipAddress: req.ip, userAgent: req.headers["user-agent"] });
40
+ }
41
+
42
+ @UseGuards(AuthGuard)
43
+ @Get("me")
44
+ me(@CurrentUser() user: RequestUser) {
45
+ return this.auth.me(user.id, user.realm);
46
+ }
47
+
48
+ /** Cross-realm role summary (admin JWT only — avoids leaking admin role names to storefront tokens). */
49
+ @UseGuards(AuthGuard)
50
+ @RequireAuthRealm("admin")
51
+ @Get("me/realms")
52
+ membership(@CurrentUser() user: RequestUser) {
53
+ return this.auth.membershipSummary(user.id);
54
+ }
55
+
56
+ @Post("password/forgot")
57
+ forgotPassword(@Body() dto: ForgotPasswordDto) {
58
+ return this.auth.forgotPassword(dto.email);
59
+ }
60
+
61
+ @Post("password/reset")
62
+ resetPassword(@Body() dto: ResetPasswordDto) {
63
+ return this.auth.resetPassword(dto.token, dto.password);
64
+ }
65
+
66
+ @Post("email/verify")
67
+ verifyEmail(@Body() dto: VerifyEmailDto) {
68
+ return this.auth.verifyEmail(dto.token);
69
+ }
70
+ }
@@ -0,0 +1,49 @@
1
+ import { IsEmail, IsOptional, IsString, Matches, MinLength } from "class-validator";
2
+
3
+ /** Safe realm segment for `Role.realm` / JWT (extend pattern in DB if you need more). */
4
+ const REALM_SLUG = /^[a-z][a-z0-9_-]{0,63}$/i;
5
+
6
+ export class LoginDto {
7
+ @IsEmail()
8
+ email!: string;
9
+
10
+ @IsString()
11
+ @MinLength(8)
12
+ password!: string;
13
+
14
+ /** When omitted, defaults to `admin` (back-office). Use `public` for storefront tokens, or any custom realm you seed. */
15
+ @IsOptional()
16
+ @IsString()
17
+ @Matches(REALM_SLUG, { message: "realm must be a short slug (e.g. admin, public, partner_api)" })
18
+ realm?: string;
19
+ }
20
+
21
+ export class RefreshDto {
22
+ @IsString()
23
+ refreshToken!: string;
24
+
25
+ /** Must match the realm used when the refresh token was issued (same default as login). */
26
+ @IsOptional()
27
+ @IsString()
28
+ @Matches(REALM_SLUG, { message: "realm must be a short slug (e.g. admin, public, partner_api)" })
29
+ realm?: string;
30
+ }
31
+
32
+ export class ForgotPasswordDto {
33
+ @IsEmail()
34
+ email!: string;
35
+ }
36
+
37
+ export class ResetPasswordDto {
38
+ @IsString()
39
+ token!: string;
40
+
41
+ @IsString()
42
+ @MinLength(8)
43
+ password!: string;
44
+ }
45
+
46
+ export class VerifyEmailDto {
47
+ @IsString()
48
+ token!: string;
49
+ }
@@ -0,0 +1,30 @@
1
+ import { Module } from "@nestjs/common";
2
+ import { ConfigModule, ConfigService } from "@nestjs/config";
3
+ import { JwtModule } from "@nestjs/jwt";
4
+ import { AuthGuard } from "../common/auth.guard";
5
+ import { PrismaService } from "../common/prisma.service";
6
+ import { MailService } from "../mail/mail.service";
7
+ import { AuthController } from "./auth.controller";
8
+ import { AuthService } from "./auth.service";
9
+
10
+ @Module({
11
+ imports: [
12
+ JwtModule.registerAsync({
13
+ imports: [ConfigModule],
14
+ inject: [ConfigService],
15
+ useFactory: (config: ConfigService) => {
16
+ const secret = config.get<string>("JWT_SECRET")?.trim();
17
+ if (!secret) {
18
+ throw new Error(
19
+ "JWT_SECRET is not set. Add it to apps/api/.env (see README). Example: JWT_SECRET=$(openssl rand -hex 32)"
20
+ );
21
+ }
22
+ return { secret, signOptions: { expiresIn: "15m" } };
23
+ }
24
+ })
25
+ ],
26
+ controllers: [AuthController],
27
+ providers: [AuthService, PrismaService, AuthGuard, MailService],
28
+ exports: [AuthService, AuthGuard]
29
+ })
30
+ export class AuthModule {}
@@ -0,0 +1,75 @@
1
+ import { UnauthorizedException } from "@nestjs/common";
2
+ import { describe, expect, it, vi } from "vitest";
3
+
4
+ vi.mock("bcryptjs", () => ({
5
+ default: {
6
+ compare: vi.fn(),
7
+ hash: vi.fn().mockResolvedValue("hashed")
8
+ }
9
+ }));
10
+
11
+ import bcrypt from "bcryptjs";
12
+ import { AuthService } from "./auth.service";
13
+
14
+ const bcryptCompareMock = bcrypt.compare as unknown as ReturnType<typeof vi.fn>;
15
+
16
+ function createPrismaMock() {
17
+ return {
18
+ user: {
19
+ findUnique: vi.fn(),
20
+ findMany: vi.fn(),
21
+ update: vi.fn()
22
+ },
23
+ auditLog: {
24
+ create: vi.fn()
25
+ }
26
+ };
27
+ }
28
+
29
+ describe("AuthService", () => {
30
+ it("login succeeds for valid credentials and admin realm", async () => {
31
+ const prisma = createPrismaMock();
32
+ const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
33
+ prisma.user.findUnique.mockResolvedValue({
34
+ id: "u1",
35
+ email: "openadminjs@proton.me",
36
+ name: "Admin",
37
+ passwordHash: "hash",
38
+ roles: [{ role: { name: "admin", realm: "admin", permissions: [{ permission: { name: "*" } }] } }]
39
+ });
40
+ bcryptCompareMock.mockResolvedValue(true);
41
+
42
+ const service = new AuthService(prisma as never, jwt as never);
43
+ const result = await service.login("openadminjs@proton.me", "password", {}, "admin");
44
+
45
+ expect(result.accessToken).toBe("jwt");
46
+ expect(result.user.email).toBe("openadminjs@proton.me");
47
+ expect(prisma.auditLog.create).toHaveBeenCalled();
48
+ });
49
+
50
+ it("login fails for wrong realm", async () => {
51
+ const prisma = createPrismaMock();
52
+ const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
53
+ prisma.user.findUnique.mockResolvedValue({
54
+ id: "u1",
55
+ email: "openadminjs@proton.me",
56
+ name: "Admin",
57
+ passwordHash: "hash",
58
+ roles: [{ role: { name: "admin", realm: "public", permissions: [] } }]
59
+ });
60
+ bcryptCompareMock.mockResolvedValue(true);
61
+
62
+ const service = new AuthService(prisma as never, jwt as never);
63
+ await expect(service.login("openadminjs@proton.me", "password", {}, "admin")).rejects.toBeInstanceOf(UnauthorizedException);
64
+ });
65
+
66
+ it("refresh fails when token does not match any user", async () => {
67
+ const prisma = createPrismaMock();
68
+ const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
69
+ prisma.user.findMany.mockResolvedValue([{ id: "u1", refreshTokenHash: "hash-1" }]);
70
+ bcryptCompareMock.mockResolvedValue(false);
71
+
72
+ const service = new AuthService(prisma as never, jwt as never);
73
+ await expect(service.refresh("bad-token", "admin")).rejects.toBeInstanceOf(UnauthorizedException);
74
+ });
75
+ });
@@ -0,0 +1,231 @@
1
+ import { BadRequestException, Inject, Injectable, Optional, UnauthorizedException } from "@nestjs/common";
2
+ import { JwtService } from "@nestjs/jwt";
3
+ import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
4
+ import bcrypt from "bcryptjs";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { PrismaService } from "../common/prisma.service";
7
+ import { MailService } from "../mail/mail.service";
8
+
9
+ @Injectable()
10
+ export class AuthService {
11
+ constructor(
12
+ @Inject(PrismaService) private readonly prisma: PrismaService,
13
+ @Inject(JwtService) private readonly jwt: JwtService,
14
+ @Optional() private readonly mail?: MailService
15
+ ) {}
16
+
17
+ async login(
18
+ email: string,
19
+ password: string,
20
+ meta: { ipAddress?: string; userAgent?: string },
21
+ realm: string = DEFAULT_AUTH_REALM
22
+ ) {
23
+ const user = await this.prisma.user.findUnique({
24
+ where: { email },
25
+ include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
26
+ });
27
+ if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
28
+ throw new UnauthorizedException({ message: "Invalid email or password", code: "AUTH_INVALID" });
29
+ }
30
+ const assignments = user.roles.filter((ur) => ur.role.realm === realm);
31
+ if (assignments.length === 0) {
32
+ throw new UnauthorizedException({
33
+ message: "Invalid email or password",
34
+ code: "AUTH_REALM_DENIED"
35
+ });
36
+ }
37
+ const session = await this.issueSession(user.id, realm);
38
+ await this.prisma.auditLog.create({
39
+ data: {
40
+ userId: user.id,
41
+ action: "login",
42
+ ipAddress: meta.ipAddress,
43
+ userAgent: meta.userAgent,
44
+ after: { realm }
45
+ }
46
+ });
47
+ return {
48
+ ...session,
49
+ realm,
50
+ user: {
51
+ id: user.id,
52
+ email: user.email,
53
+ name: user.name,
54
+ roles: assignments.map((item) => item.role.name),
55
+ permissions: assignments.flatMap((item) => item.role.permissions.map((permission) => permission.permission.name))
56
+ }
57
+ };
58
+ }
59
+
60
+ async issueSession(userId: string, realm: string = DEFAULT_AUTH_REALM) {
61
+ const refreshToken = randomBytes(48).toString("base64url");
62
+ await this.prisma.user.update({
63
+ where: { id: userId },
64
+ data: { refreshTokenHash: await bcrypt.hash(refreshToken, 12) }
65
+ });
66
+ return {
67
+ accessToken: await this.jwt.signAsync({ sub: userId, realm }),
68
+ refreshToken,
69
+ expiresIn: 900
70
+ };
71
+ }
72
+
73
+ async refresh(refreshToken: string, realm: string = DEFAULT_AUTH_REALM) {
74
+ const users = await this.prisma.user.findMany({ where: { refreshTokenHash: { not: null } } });
75
+ const user = await users.reduce<Promise<(typeof users)[number] | undefined>>(async (match, candidate) => {
76
+ const found = await match;
77
+ if (found) return found;
78
+ return candidate.refreshTokenHash && (await bcrypt.compare(refreshToken, candidate.refreshTokenHash)) ? candidate : undefined;
79
+ }, Promise.resolve(undefined));
80
+ if (!user) throw new UnauthorizedException({ message: "Invalid refresh token", code: "REFRESH_INVALID" });
81
+ return this.issueSession(user.id, realm);
82
+ }
83
+
84
+ async logout(userId: string, meta: { ipAddress?: string; userAgent?: string }) {
85
+ await this.prisma.user.update({ where: { id: userId }, data: { refreshTokenHash: null } });
86
+ await this.prisma.auditLog.create({
87
+ data: { userId, action: "logout", ipAddress: meta.ipAddress, userAgent: meta.userAgent }
88
+ });
89
+ return { ok: true };
90
+ }
91
+
92
+ async forgotPassword(email: string) {
93
+ const user = await this.prisma.user.findUnique({ where: { email } });
94
+ if (!user) return { ok: true, message: "If the email exists, reset instructions will be sent." };
95
+
96
+ const rawToken = randomBytes(32).toString("base64url");
97
+ const tokenHash = this.hashToken(rawToken);
98
+ const expiresAt = new Date(Date.now() + 1000 * 60 * 30);
99
+
100
+ await this.prisma.passwordResetToken.create({
101
+ data: {
102
+ userId: user.id,
103
+ tokenHash,
104
+ expiresAt
105
+ }
106
+ });
107
+
108
+ await this.prisma.auditLog.create({
109
+ data: { userId: user.id, action: "password.reset.requested", resource: "auth", after: { expiresAt } }
110
+ });
111
+
112
+ if (this.mail) {
113
+ await this.mail.sendPasswordReset(user.email, user.name ?? user.email, rawToken).catch(() => {
114
+ // Don't fail the request if mail sending fails
115
+ });
116
+ }
117
+
118
+ if (process.env.NODE_ENV !== "production") return { ok: true, message: "Reset token generated", token: rawToken };
119
+ return { ok: true, message: "If the email exists, reset instructions will be sent." };
120
+ }
121
+
122
+ async resetPassword(token: string, password: string) {
123
+ const tokenHash = this.hashToken(token);
124
+ const now = new Date();
125
+ const resetToken = await this.prisma.passwordResetToken.findFirst({
126
+ where: {
127
+ tokenHash,
128
+ usedAt: null,
129
+ expiresAt: { gt: now }
130
+ },
131
+ include: { user: true }
132
+ });
133
+
134
+ if (!resetToken) throw new BadRequestException({ message: "Invalid or expired reset token", code: "RESET_TOKEN_INVALID" });
135
+
136
+ const nextPasswordHash = await bcrypt.hash(password, 12);
137
+ await this.prisma.$transaction([
138
+ this.prisma.user.update({
139
+ where: { id: resetToken.userId },
140
+ data: { passwordHash: nextPasswordHash, refreshTokenHash: null }
141
+ }),
142
+ this.prisma.passwordResetToken.update({
143
+ where: { id: resetToken.id },
144
+ data: { usedAt: now }
145
+ }),
146
+ this.prisma.auditLog.create({
147
+ data: { userId: resetToken.userId, action: "password.reset.completed", resource: "auth" }
148
+ })
149
+ ]);
150
+
151
+ return { ok: true };
152
+ }
153
+
154
+ async verifyEmail(token: string) {
155
+ const tokenHash = this.hashToken(token);
156
+ const now = new Date();
157
+ const verification = await this.prisma.emailVerificationToken.findFirst({
158
+ where: {
159
+ tokenHash,
160
+ usedAt: null,
161
+ expiresAt: { gt: now }
162
+ }
163
+ });
164
+ if (!verification) throw new BadRequestException({ message: "Invalid or expired verification token", code: "VERIFY_TOKEN_INVALID" });
165
+
166
+ await this.prisma.$transaction([
167
+ this.prisma.emailVerificationToken.update({
168
+ where: { id: verification.id },
169
+ data: { usedAt: now }
170
+ }),
171
+ this.prisma.user.update({
172
+ where: { id: verification.userId },
173
+ data: { status: "active" }
174
+ }),
175
+ this.prisma.auditLog.create({
176
+ data: { userId: verification.userId, action: "email.verified", resource: "auth" }
177
+ })
178
+ ]);
179
+
180
+ return { ok: true };
181
+ }
182
+
183
+ async me(userId: string, realm: string = DEFAULT_AUTH_REALM) {
184
+ const user = await this.prisma.user.findUnique({
185
+ where: { id: userId },
186
+ include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
187
+ });
188
+ if (!user) throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
189
+ const assignments = user.roles.filter((ur) => ur.role.realm === realm);
190
+ return {
191
+ id: user.id,
192
+ email: user.email,
193
+ name: user.name,
194
+ avatarUrl: user.avatarUrl,
195
+ status: user.status,
196
+ realm,
197
+ roles: assignments.map((item) => item.role.name),
198
+ permissions: assignments.flatMap((item) => item.role.permissions.map((permission) => permission.permission.name))
199
+ };
200
+ }
201
+
202
+ /** All role bindings across realms (account / picker UI). */
203
+ async membershipSummary(userId: string) {
204
+ const user = await this.prisma.user.findUnique({
205
+ where: { id: userId },
206
+ include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
207
+ });
208
+ if (!user) throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
209
+ const byRealm = new Map<string, { roles: string[]; permissions: string[] }>();
210
+ for (const ur of user.roles) {
211
+ const r = ur.role.realm;
212
+ const bucket = byRealm.get(r) ?? { roles: [], permissions: [] };
213
+ bucket.roles.push(ur.role.name);
214
+ bucket.permissions.push(...ur.role.permissions.map((p) => p.permission.name));
215
+ byRealm.set(r, bucket);
216
+ }
217
+ return {
218
+ id: user.id,
219
+ email: user.email,
220
+ realms: [...byRealm.entries()].map(([realm, data]) => ({
221
+ realm,
222
+ roles: [...new Set(data.roles)].sort(),
223
+ permissions: [...new Set(data.permissions)].sort()
224
+ }))
225
+ };
226
+ }
227
+
228
+ private hashToken(value: string) {
229
+ return createHash("sha256").update(value).digest("hex");
230
+ }
231
+ }
@@ -0,0 +1,6 @@
1
+ import { SetMetadata } from "@nestjs/common";
2
+
3
+ /** When set on a route/controller, JWT must have been issued for this `realm` (see `Role.realm`). */
4
+ export const AUTH_REALM_KEY = "openadminjs:authRealm";
5
+
6
+ export const RequireAuthRealm = (realm: string) => SetMetadata(AUTH_REALM_KEY, realm);
@@ -0,0 +1,61 @@
1
+ import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { AuthGuard } from "./auth.guard";
4
+
5
+ function createContext(authHeader?: string, requiredRealm?: string) {
6
+ const request: { headers: Record<string, string>; user?: unknown } = { headers: {} };
7
+ if (authHeader) request.headers.authorization = authHeader;
8
+ return {
9
+ request,
10
+ ctx: {
11
+ switchToHttp: () => ({ getRequest: () => request }),
12
+ getHandler: () => "handler",
13
+ getClass: () => "class"
14
+ },
15
+ reflector: {
16
+ getAllAndOverride: vi.fn().mockReturnValue(requiredRealm)
17
+ }
18
+ };
19
+ }
20
+
21
+ const mockConfig = { get: vi.fn().mockReturnValue("test-secret") };
22
+
23
+ describe("AuthGuard", () => {
24
+ it("rejects missing token", async () => {
25
+ const { ctx, reflector } = createContext(undefined);
26
+ const guard = new AuthGuard({ verifyAsync: vi.fn() } as never, { user: { findUnique: vi.fn() } } as never, reflector as never, mockConfig as never);
27
+ await expect(guard.canActivate(ctx as never)).rejects.toBeInstanceOf(UnauthorizedException);
28
+ });
29
+
30
+ it("rejects realm mismatch", async () => {
31
+ const { ctx, reflector } = createContext("Bearer token", "public");
32
+ const guard = new AuthGuard(
33
+ { verifyAsync: vi.fn().mockResolvedValue({ sub: "u1", realm: "admin" }) } as never,
34
+ { user: { findUnique: vi.fn() } } as never,
35
+ reflector as never,
36
+ mockConfig as never
37
+ );
38
+ await expect(guard.canActivate(ctx as never)).rejects.toBeInstanceOf(ForbiddenException);
39
+ });
40
+
41
+ it("attaches request.user for valid token", async () => {
42
+ const { ctx, reflector, request } = createContext("Bearer token", "admin");
43
+ const guard = new AuthGuard(
44
+ { verifyAsync: vi.fn().mockResolvedValue({ sub: "u1", realm: "admin" }) } as never,
45
+ {
46
+ user: {
47
+ findUnique: vi.fn().mockResolvedValue({
48
+ id: "u1",
49
+ email: "openadminjs@proton.me",
50
+ name: "Admin",
51
+ roles: [{ role: { name: "admin", realm: "admin", permissions: [{ permission: { name: "*" } }] } }]
52
+ })
53
+ }
54
+ } as never,
55
+ reflector as never,
56
+ mockConfig as never
57
+ );
58
+ await expect(guard.canActivate(ctx as never)).resolves.toBe(true);
59
+ expect((request.user as { id: string }).id).toBe("u1");
60
+ });
61
+ });
@@ -0,0 +1,78 @@
1
+ import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
2
+ import { ConfigService } from "@nestjs/config";
3
+ import { Reflector } from "@nestjs/core";
4
+ import { JwtService } from "@nestjs/jwt";
5
+ import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
6
+ import { PrismaService } from "./prisma.service";
7
+ import { AUTH_REALM_KEY } from "./auth-realm.decorator";
8
+
9
+ export type RequestUser = {
10
+ id: string;
11
+ email?: string;
12
+ name?: string | null;
13
+ realm: string;
14
+ roles: string[];
15
+ permissions: string[];
16
+ };
17
+
18
+ @Injectable()
19
+ export class AuthGuard implements CanActivate {
20
+ constructor(
21
+ private readonly jwt: JwtService,
22
+ private readonly prisma: PrismaService,
23
+ private readonly reflector: Reflector,
24
+ private readonly config: ConfigService
25
+ ) {}
26
+
27
+ async canActivate(context: ExecutionContext): Promise<boolean> {
28
+ const request = context.switchToHttp().getRequest();
29
+ const header = request.headers.authorization;
30
+ const token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
31
+ if (!token) throw new UnauthorizedException({ message: "Missing access token", code: "AUTH_REQUIRED" });
32
+ try {
33
+ const jwtSecret = this.config.get<string>("JWT_SECRET")?.trim() ?? process.env.JWT_SECRET?.trim();
34
+ const payload = await this.jwt.verifyAsync<{ sub: string; realm?: string }>(token, { secret: jwtSecret });
35
+ const realm = payload.realm ?? DEFAULT_AUTH_REALM;
36
+
37
+ const requiredRealm = this.reflector.getAllAndOverride<string | undefined>(AUTH_REALM_KEY, [
38
+ context.getHandler(),
39
+ context.getClass()
40
+ ]);
41
+ if (requiredRealm !== undefined && requiredRealm !== realm) {
42
+ throw new ForbiddenException({
43
+ message: "Token was issued for a different application area",
44
+ code: "AUTH_REALM_MISMATCH",
45
+ details: { expected: requiredRealm, tokenRealm: realm }
46
+ });
47
+ }
48
+
49
+ const user = await this.prisma.user.findUnique({
50
+ where: { id: payload.sub },
51
+ include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
52
+ });
53
+ if (!user) throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
54
+
55
+ const assignments = user.roles.filter((ur) => ur.role.realm === realm);
56
+ if (assignments.length === 0) {
57
+ throw new ForbiddenException({
58
+ message: "No roles for this application area",
59
+ code: "AUTH_REALM_EMPTY",
60
+ details: { realm }
61
+ });
62
+ }
63
+
64
+ request.user = {
65
+ id: user.id,
66
+ email: user.email,
67
+ name: user.name,
68
+ realm,
69
+ roles: assignments.map((item) => item.role.name),
70
+ permissions: assignments.flatMap((item) => item.role.permissions.map((p) => p.permission.name))
71
+ } satisfies RequestUser;
72
+ return true;
73
+ } catch (e) {
74
+ if (e instanceof ForbiddenException) throw e;
75
+ throw new UnauthorizedException({ message: "Invalid access token", code: "AUTH_INVALID" });
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { CaslAbilityFactory } from "./casl-ability.factory";
3
+
4
+ describe("CaslAbilityFactory", () => {
5
+ const factory = new CaslAbilityFactory();
6
+
7
+ it("maps dotted permissions to CASL rules", () => {
8
+ const ability = factory.createForUser({ permissions: ["posts.read", "users.update"] });
9
+ expect(ability.can("read", "posts")).toBe(true);
10
+ expect(ability.can("update", "users")).toBe(true);
11
+ expect(ability.can("delete", "posts")).toBe(false);
12
+ });
13
+
14
+ it("uses the last dot for namespaced slugs", () => {
15
+ const ability = factory.createForUser({ permissions: ["public.orders.read_own"] });
16
+ expect(ability.can("manage", "public.orders")).toBe(true);
17
+ });
18
+
19
+ it("grants manage all for star permission", () => {
20
+ const ability = factory.createForUser({ permissions: ["*"] });
21
+ expect(ability.can("manage", "all")).toBe(true);
22
+ });
23
+
24
+ it("maps unknown actions to manage", () => {
25
+ const ability = factory.createForUser({ permissions: ["reports.export"] });
26
+ expect(ability.can("manage", "reports")).toBe(true);
27
+ });
28
+
29
+ it("ignores malformed permission strings", () => {
30
+ const ability = factory.createForUser({ permissions: ["noparts", ".", "ok.read"] });
31
+ expect(ability.can("read", "ok")).toBe(true);
32
+ });
33
+ });