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,41 @@
1
+ import { AbilityBuilder, createMongoAbility, type MongoAbility } from "@casl/ability";
2
+ import { Injectable } from "@nestjs/common";
3
+
4
+ type AppAction = "manage" | "create" | "read" | "update" | "delete" | "dispatch";
5
+ type AppAbility = MongoAbility<[AppAction, string]>;
6
+
7
+ type RequestUser = {
8
+ permissions?: string[];
9
+ };
10
+
11
+ @Injectable()
12
+ export class CaslAbilityFactory {
13
+ createForUser(user: RequestUser): AppAbility {
14
+ const { can, build } = new AbilityBuilder<AppAbility>(createMongoAbility);
15
+
16
+ for (const permission of user.permissions ?? []) {
17
+ if (permission === "*") {
18
+ can("manage", "all");
19
+ continue;
20
+ }
21
+
22
+ const dot = permission.lastIndexOf(".");
23
+ if (dot <= 0) continue;
24
+ const subject = permission.slice(0, dot);
25
+ const action = permission.slice(dot + 1);
26
+ if (!subject || !action) continue;
27
+
28
+ can(this.toAction(action), subject);
29
+ }
30
+
31
+ return build();
32
+ }
33
+
34
+ private toAction(action: string): AppAction {
35
+ if (action === "create" || action === "read" || action === "update" || action === "delete") {
36
+ return action;
37
+ }
38
+ if (action === "dispatch") return "dispatch";
39
+ return "manage";
40
+ }
41
+ }
@@ -0,0 +1,6 @@
1
+ import { createParamDecorator, ExecutionContext } from "@nestjs/common";
2
+
3
+ export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
4
+ const request = context.switchToHttp().getRequest();
5
+ return request.user;
6
+ });
@@ -0,0 +1,7 @@
1
+ import { SetMetadata } from "@nestjs/common";
2
+
3
+ export const REQUIRE_PERMISSION = "requirePermission";
4
+ export const REQUIRE_ROLE = "requireRole";
5
+
6
+ export const RequirePermission = (permission: string) => SetMetadata(REQUIRE_PERMISSION, permission);
7
+ export const RequireRole = (role: string) => SetMetadata(REQUIRE_ROLE, role);
@@ -0,0 +1,31 @@
1
+ import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ import { REQUIRE_PERMISSION, REQUIRE_ROLE } from "./permission.decorator";
4
+ import { CaslAbilityFactory } from "./casl-ability.factory";
5
+
6
+ @Injectable()
7
+ export class PermissionsGuard implements CanActivate {
8
+ constructor(
9
+ private readonly reflector: Reflector,
10
+ private readonly abilityFactory: CaslAbilityFactory
11
+ ) {}
12
+
13
+ canActivate(context: ExecutionContext): boolean {
14
+ const permission = this.reflector.getAllAndOverride<string>(REQUIRE_PERMISSION, [context.getHandler(), context.getClass()]);
15
+ const role = this.reflector.getAllAndOverride<string>(REQUIRE_ROLE, [context.getHandler(), context.getClass()]);
16
+ const request = context.switchToHttp().getRequest();
17
+ const user = request.user;
18
+
19
+ if (role && !user?.roles?.includes(role)) throw new ForbiddenException({ message: "Missing role", code: "ROLE_DENIED" });
20
+ if (permission) {
21
+ const [subject, action] = permission.split(".");
22
+ const ability = this.abilityFactory.createForUser(user ?? {});
23
+ const hasRawPermission = user?.permissions?.includes(permission) || user?.permissions?.includes("*");
24
+ const hasCaslPermission = subject && action ? ability.can(action as never, subject) : false;
25
+ if (!hasRawPermission && !hasCaslPermission) {
26
+ throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED", details: { permission } });
27
+ }
28
+ }
29
+ return true;
30
+ }
31
+ }
@@ -0,0 +1,13 @@
1
+ import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
+ import { PrismaClient } from "@prisma/client";
3
+
4
+ @Injectable()
5
+ export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
6
+ async onModuleInit() {
7
+ await this.$connect();
8
+ }
9
+
10
+ async onModuleDestroy() {
11
+ await this.$disconnect();
12
+ }
13
+ }
@@ -0,0 +1,25 @@
1
+ import { Controller, Get, Inject } from "@nestjs/common";
2
+ import Redis from "ioredis";
3
+ import { PrismaService } from "../common/prisma.service";
4
+
5
+ @Controller("health")
6
+ export class HealthController {
7
+ constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {}
8
+
9
+ @Get()
10
+ async health() {
11
+ await this.prisma.$queryRaw`SELECT 1`;
12
+ if (!process.env.REDIS_URL) return { api: "ok", db: "ok", redis: "unavailable", reason: "REDIS_URL is not set" };
13
+
14
+ const redis = new Redis(process.env.REDIS_URL, { lazyConnect: true, maxRetriesPerRequest: 1 });
15
+ try {
16
+ await redis.connect();
17
+ const pong = await redis.ping();
18
+ return { api: "ok", db: "ok", redis: pong === "PONG" ? "ok" : "degraded" };
19
+ } catch {
20
+ return { api: "ok", db: "ok", redis: "error" };
21
+ } finally {
22
+ await redis.quit().catch(() => undefined);
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,9 @@
1
+ import { Global, Module } from "@nestjs/common";
2
+ import { MailService } from "./mail.service";
3
+
4
+ @Global()
5
+ @Module({
6
+ providers: [MailService],
7
+ exports: [MailService]
8
+ })
9
+ export class MailModule {}
@@ -0,0 +1,115 @@
1
+ import { Injectable, Logger } from "@nestjs/common";
2
+ import { ConfigService } from "@nestjs/config";
3
+ import {
4
+ createMailDriver,
5
+ type MailDriver,
6
+ type MailMessage,
7
+ type SentInfo
8
+ } from "@openadminjs/mail";
9
+
10
+ /**
11
+ * NestJS wrapper around @openadminjs/mail.
12
+ *
13
+ * Configure via env:
14
+ * SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM, APP_NAME
15
+ * If SMTP_HOST is not set → uses MockMailDriver (logs to console in dev).
16
+ */
17
+ @Injectable()
18
+ export class MailService {
19
+ private readonly driver: MailDriver;
20
+ private readonly logger = new Logger(MailService.name);
21
+ private readonly appName: string;
22
+ private readonly appUrl: string;
23
+
24
+ constructor(private readonly config: ConfigService) {
25
+ const host = this.config.get<string>("SMTP_HOST");
26
+ this.appName = this.config.get<string>("APP_NAME") ?? "OpenAdminJS";
27
+ this.appUrl = this.config.get<string>("APP_URL") ?? "http://localhost:3000";
28
+
29
+ this.driver = createMailDriver(
30
+ host
31
+ ? {
32
+ host,
33
+ port: Number(this.config.get<string>("SMTP_PORT") ?? "587"),
34
+ secure: this.config.get<string>("SMTP_SECURE") === "true",
35
+ auth:
36
+ this.config.get<string>("SMTP_USER")
37
+ ? {
38
+ user: this.config.get<string>("SMTP_USER")!,
39
+ pass: this.config.get<string>("SMTP_PASS") ?? ""
40
+ }
41
+ : undefined,
42
+ from: this.config.get<string>("SMTP_FROM"),
43
+ appName: this.appName
44
+ }
45
+ : undefined
46
+ );
47
+ this.logger.log(`Mail driver: ${host ? `smtp(${host})` : "mock"}`);
48
+ }
49
+
50
+ async send(message: MailMessage): Promise<SentInfo> {
51
+ return this.driver.send({
52
+ ...message,
53
+ data: { appName: this.appName, appUrl: this.appUrl, ...(message.data ?? {}) }
54
+ });
55
+ }
56
+
57
+ async sendWelcome(to: string, name: string) {
58
+ return this.send({
59
+ to,
60
+ subject: `Welcome to ${this.appName}!`,
61
+ template: "welcome",
62
+ data: { name, loginUrl: `${this.appUrl}/login` }
63
+ });
64
+ }
65
+
66
+ async sendPasswordReset(to: string, name: string, token: string) {
67
+ return this.send({
68
+ to,
69
+ subject: `Reset your ${this.appName} password`,
70
+ template: "password-reset",
71
+ data: {
72
+ name,
73
+ resetUrl: `${this.appUrl}/reset-password?token=${encodeURIComponent(token)}`,
74
+ expiresIn: "1 hour"
75
+ }
76
+ });
77
+ }
78
+
79
+ async sendEmailVerification(to: string, name: string, token: string) {
80
+ return this.send({
81
+ to,
82
+ subject: `Verify your email address`,
83
+ template: "email-verification",
84
+ data: {
85
+ name,
86
+ verifyUrl: `${this.appUrl}/verify-email?token=${encodeURIComponent(token)}`,
87
+ expiresIn: "24 hours"
88
+ }
89
+ });
90
+ }
91
+
92
+ async sendOrderConfirmation(to: string, customerName: string, orderId: string, total: number, currency: string) {
93
+ return this.send({
94
+ to,
95
+ subject: `Order confirmation #${orderId}`,
96
+ template: "order-confirmation",
97
+ data: {
98
+ customerName,
99
+ orderId,
100
+ currency,
101
+ totalDisplay: (total / 100).toFixed(2),
102
+ orderUrl: `${this.appUrl}/orders/${orderId}`
103
+ }
104
+ });
105
+ }
106
+
107
+ async sendRefundNotification(to: string, customerName: string, orderId: string, total: number, currency: string) {
108
+ return this.send({
109
+ to,
110
+ subject: `Refund processed for order #${orderId}`,
111
+ template: "order-refunded",
112
+ data: { customerName, orderId, currency, totalDisplay: (total / 100).toFixed(2) }
113
+ });
114
+ }
115
+ }
@@ -0,0 +1,37 @@
1
+ import "reflect-metadata";
2
+ import helmet from "helmet";
3
+ import { NestFactory } from "@nestjs/core";
4
+ import { ValidationPipe } from "@nestjs/common";
5
+ import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
6
+ import { AppModule } from "./app.module";
7
+
8
+ async function bootstrap() {
9
+ const app = await NestFactory.create(AppModule);
10
+ app.use(helmet());
11
+ const prodOrigins = (process.env.ADMIN_ORIGIN ?? "")
12
+ .split(",")
13
+ .map((s) => s.trim())
14
+ .filter(Boolean);
15
+ app.enableCors({
16
+ origin:
17
+ process.env.NODE_ENV === "production"
18
+ ? prodOrigins.length
19
+ ? prodOrigins
20
+ : false
21
+ : true,
22
+ credentials: true
23
+ });
24
+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
25
+
26
+ const config = new DocumentBuilder()
27
+ .setTitle("OpenAdminJS API")
28
+ .setDescription("Generic admin API")
29
+ .setVersion("0.1.0")
30
+ .addBearerAuth()
31
+ .build();
32
+ SwaggerModule.setup("api/docs", app, SwaggerModule.createDocument(app, config));
33
+
34
+ await app.listen(Number(process.env.API_PORT ?? 4000));
35
+ }
36
+
37
+ bootstrap();
@@ -0,0 +1,4 @@
1
+ import { loadPluginsFromManifest } from "./plugin-loader";
2
+
3
+ /** Runs after core `resource-hooks.install` so plugin hooks stack after built-ins. */
4
+ void loadPluginsFromManifest();
@@ -0,0 +1,25 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const adminWidgetBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.admin-widget",
5
+ version: "0.1.0",
6
+ displayName: "Admin widget demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ adminUi: [
10
+ {
11
+ kind: "widget",
12
+ id: "ops-health",
13
+ title: "Ops Health",
14
+ config: { metric: "queueLag", severity: "info" }
15
+ },
16
+ {
17
+ kind: "menu",
18
+ id: "plugin-insights",
19
+ title: "Plugin Insights",
20
+ route: "/plugins/insights"
21
+ }
22
+ ]
23
+ });
24
+ }
25
+ };
@@ -0,0 +1,19 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ /**
4
+ * Demo bundled plugin: stacks `afterCreate` on `posts` after core hooks.
5
+ * Enable in `plugins.manifest.json` with `{ "id": "io.openadminjs.hello", "bundled": "hello", "enabled": true }`.
6
+ */
7
+ export const helloBundledPlugin: OpenAdminPlugin = {
8
+ id: "io.openadminjs.hello",
9
+ version: "0.1.0",
10
+ displayName: "Hello (bundled demo)",
11
+ register({ registerResourceHooks, config }) {
12
+ const tag = typeof config.tag === "string" ? config.tag : "hello-plugin";
13
+ registerResourceHooks("posts", {
14
+ afterCreate() {
15
+ void tag;
16
+ }
17
+ });
18
+ }
19
+ };
@@ -0,0 +1,22 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const imageOptimizerBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.image-optimizer",
5
+ version: "0.1.0",
6
+ displayName: "Image optimizer demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ media: {
10
+ transform(ctx) {
11
+ if (!ctx.mimeType.startsWith("image/")) return ctx;
12
+ const filename = ctx.filename.replace(/\.(png|jpe?g|webp)$/i, "") + ".webp";
13
+ return {
14
+ ...ctx,
15
+ filename,
16
+ mimeType: "image/webp"
17
+ };
18
+ }
19
+ }
20
+ });
21
+ }
22
+ };
@@ -0,0 +1,13 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+ import { adminWidgetBundledPlugin } from "./admin-widget.plugin";
3
+ import { helloBundledPlugin } from "./hello.plugin";
4
+ import { imageOptimizerBundledPlugin } from "./image-optimizer.plugin";
5
+ import { seoBundledPlugin } from "./seo.plugin";
6
+
7
+ /** First-party plugins shipped inside the API package (no separate npm install). */
8
+ export const bundledOpenAdminPlugins: Record<string, OpenAdminPlugin> = {
9
+ hello: helloBundledPlugin,
10
+ seo: seoBundledPlugin,
11
+ "image-optimizer": imageOptimizerBundledPlugin,
12
+ "admin-widget": adminWidgetBundledPlugin
13
+ };
@@ -0,0 +1,25 @@
1
+ import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+
3
+ export const seoBundledPlugin: OpenAdminPlugin = {
4
+ id: "io.openadminjs.seo",
5
+ version: "0.1.0",
6
+ displayName: "SEO metadata + sitemap demo",
7
+ register({ registerSurface }) {
8
+ registerSurface({
9
+ seo: {
10
+ metadata({ resourceName, record }) {
11
+ if (resourceName !== "posts") return {};
12
+ return {
13
+ title: record.title ?? "Untitled",
14
+ description: record.excerpt ?? "",
15
+ canonical: record.slug ? `/posts/${record.slug}` : undefined
16
+ };
17
+ },
18
+ sitemapEntry({ resourceName, record }) {
19
+ if (resourceName !== "posts" || !record.slug) return null;
20
+ return { url: `/posts/${record.slug}`, lastModified: typeof record.updatedAt === "string" ? record.updatedAt : undefined };
21
+ }
22
+ }
23
+ });
24
+ }
25
+ };
@@ -0,0 +1,35 @@
1
+ import { existsSync } from "node:fs";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ /** Same resolution order as plugin-loader (env → cwd → beside apps/api). */
6
+ export function getManifestCandidateStrings(): string[] {
7
+ const fromEnv = process.env.OPENADMIN_PLUGINS_MANIFEST;
8
+ const fromCwd = join(process.cwd(), "plugins.manifest.json");
9
+ const apiPkgDir = fileURLToPath(new URL("../..", import.meta.url));
10
+ const besideApi = join(apiPkgDir, "plugins.manifest.json");
11
+ return [...new Set([fromEnv, fromCwd, besideApi].filter(Boolean) as string[])];
12
+ }
13
+
14
+ export function toAbsoluteManifestPath(candidate: string): string {
15
+ return isAbsolute(candidate) ? candidate : resolve(process.cwd(), candidate);
16
+ }
17
+
18
+ /** First existing manifest file, if any. */
19
+ export function resolveExistingManifestPath(): string | undefined {
20
+ for (const candidate of getManifestCandidateStrings()) {
21
+ const abs = toAbsoluteManifestPath(candidate);
22
+ if (existsSync(abs)) return abs;
23
+ }
24
+ return undefined;
25
+ }
26
+
27
+ /** Path to write when no file exists yet (beside apps/api). */
28
+ export function defaultWritableManifestPath(): string {
29
+ const apiPkgDir = fileURLToPath(new URL("../..", import.meta.url));
30
+ return join(apiPkgDir, "plugins.manifest.json");
31
+ }
32
+
33
+ export function resolveWritableManifestPath(): string {
34
+ return resolveExistingManifestPath() ?? defaultWritableManifestPath();
35
+ }
@@ -0,0 +1,36 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { pluginManifestSchema } from "./manifest.schema";
3
+
4
+ describe("pluginManifestSchema", () => {
5
+ it("accepts bundled-only entry", () => {
6
+ const r = pluginManifestSchema.safeParse({
7
+ version: 1,
8
+ plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 }, capabilities: ["resource.hooks"], trustMode: "sandboxed" }]
9
+ });
10
+ expect(r.success).toBe(true);
11
+ });
12
+
13
+ it("rejects unknown capability", () => {
14
+ const r = pluginManifestSchema.safeParse({
15
+ version: 1,
16
+ plugins: [{ id: "a.b", bundled: "hello", capabilities: ["unknown.cap"] }]
17
+ });
18
+ expect(r.success).toBe(false);
19
+ });
20
+
21
+ it("rejects both bundled and package", () => {
22
+ const r = pluginManifestSchema.safeParse({
23
+ version: 1,
24
+ plugins: [{ id: "x", bundled: "hello", package: "@x/y" }]
25
+ });
26
+ expect(r.success).toBe(false);
27
+ });
28
+
29
+ it("rejects neither bundled nor package", () => {
30
+ const r = pluginManifestSchema.safeParse({
31
+ version: 1,
32
+ plugins: [{ id: "x" }]
33
+ });
34
+ expect(r.success).toBe(false);
35
+ });
36
+ });
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+
3
+ const capabilitySchema = z.enum([
4
+ "db.read",
5
+ "db.write",
6
+ "resource.hooks",
7
+ "api.hooks",
8
+ "api.routes",
9
+ "media.pipeline",
10
+ "seo.extend",
11
+ "jobs.run",
12
+ "admin.ui.extend"
13
+ ]);
14
+
15
+ export const pluginManifestEntrySchema = z
16
+ .object({
17
+ id: z.string().min(1),
18
+ enabled: z.boolean().optional().default(true),
19
+ trustMode: z.enum(["trusted", "sandboxed"]).optional().default("trusted"),
20
+ capabilities: z.array(capabilitySchema).optional().default([]),
21
+ bundled: z
22
+ .string()
23
+ .regex(/^[a-z0-9-]+$/, "bundled id must be lowercase slug")
24
+ .optional(),
25
+ package: z
26
+ .string()
27
+ .min(1)
28
+ .regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/i, "invalid npm package name")
29
+ .optional(),
30
+ config: z.record(z.string(), z.unknown()).optional().default({}),
31
+ policy: z
32
+ .object({
33
+ allowedRoutes: z.array(z.string()).optional(),
34
+ maxJobRuntimeMs: z.number().int().positive().optional()
35
+ })
36
+ .optional(),
37
+ marketplace: z
38
+ .object({
39
+ listingUrl: z.string().optional(),
40
+ productId: z.string().optional(),
41
+ licenseKey: z.string().optional()
42
+ })
43
+ .optional()
44
+ })
45
+ .strict()
46
+ .refine((e) => Number(Boolean(e.bundled)) + Number(Boolean(e.package)) === 1, {
47
+ message: "Each plugin must set exactly one of: bundled, package"
48
+ });
49
+
50
+ export const pluginManifestSchema = z
51
+ .object({
52
+ version: z.literal(1),
53
+ plugins: z.array(pluginManifestEntrySchema)
54
+ })
55
+ .strict();
56
+
57
+ export type PluginManifest = z.infer<typeof pluginManifestSchema>;
58
+ export type PluginManifestEntry = z.infer<typeof pluginManifestEntrySchema>;
@@ -0,0 +1,47 @@
1
+ import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
2
+ import { Observable, tap } from "rxjs";
3
+ import { pluginRuntime } from "./plugin-runtime";
4
+
5
+ @Injectable()
6
+ export class PluginApiInterceptor implements NestInterceptor {
7
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
8
+ if (context.getType() !== "http") return next.handle();
9
+ const request = context.switchToHttp().getRequest<{
10
+ method?: string;
11
+ route?: { path?: string };
12
+ path?: string;
13
+ body?: unknown;
14
+ query?: Record<string, unknown>;
15
+ user?: { id?: string; email?: string; permissions?: string[] };
16
+ }>();
17
+ const response = context.switchToHttp().getResponse<{ statusCode?: number }>();
18
+ const method = request.method ?? "GET";
19
+ const path = request.route?.path ?? request.path ?? "/";
20
+ const started = Date.now();
21
+ for (const hook of pluginRuntime.getApiHooks()) {
22
+ void hook.beforeRequest?.({
23
+ method,
24
+ path,
25
+ body: request.body,
26
+ query: request.query,
27
+ user: request.user?.id ? { id: request.user.id, email: request.user.email ?? "", permissions: request.user.permissions ?? [] } : undefined
28
+ });
29
+ }
30
+ return next.handle().pipe(
31
+ tap({
32
+ next: () => {
33
+ const durationMs = Date.now() - started;
34
+ for (const hook of pluginRuntime.getApiHooks()) {
35
+ void hook.afterRequest?.({
36
+ method,
37
+ path,
38
+ statusCode: response.statusCode ?? 200,
39
+ durationMs,
40
+ user: request.user?.id ? { id: request.user.id, email: request.user.email ?? "", permissions: request.user.permissions ?? [] } : undefined
41
+ });
42
+ }
43
+ }
44
+ })
45
+ );
46
+ }
47
+ }