openadminjs 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +36 -4
  2. package/apps/admin/app/plugins/page.tsx +60 -1
  3. package/apps/api/plugins.manifest.example.json +12 -0
  4. package/apps/api/src/admin/admin-ai.service.ts +36 -3
  5. package/apps/api/src/admin/admin-plugins.service.ts +18 -4
  6. package/apps/api/src/admin/dto/plugins.dto.ts +19 -1
  7. package/apps/api/src/app.module.ts +9 -1
  8. package/apps/api/src/plugins/bootstrap.ts +2 -2
  9. package/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
  10. package/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
  11. package/apps/api/src/plugins/bundled/registry.ts +7 -1
  12. package/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
  13. package/apps/api/src/plugins/manifest.schema.test.ts +9 -1
  14. package/apps/api/src/plugins/manifest.schema.ts +20 -0
  15. package/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
  16. package/apps/api/src/plugins/plugin-loader.ts +34 -9
  17. package/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
  18. package/apps/api/src/plugins/plugin-runtime.ts +85 -0
  19. package/apps/api/src/resources/resource-hooks.runner.ts +13 -6
  20. package/examples/README.md +1 -1
  21. package/examples/basic-admin/README.md +1 -1
  22. package/package.json +1 -1
  23. package/packages/cli/src/create-project.ts +99 -10
  24. package/packages/cli/src/index.ts +35 -8
  25. package/packages/cli/template/.env.example +5 -3
  26. package/packages/create-openadminjs/src/index.ts +56 -4
  27. package/packages/create-openadminjs/src/render-files.ts +1 -1
  28. package/packages/create-openadminjs/template/.env.example +5 -2
  29. package/packages/plugin-sdk/src/hooks.ts +91 -0
  30. package/packages/plugin-sdk/src/index.ts +6 -1
  31. package/site/docs.html +51 -41
  32. package/site/index.html +1 -1
package/README.md CHANGED
@@ -11,17 +11,19 @@ Full documentation: [https://js-senpai.github.io/open-admin-js/docs.html](https:
11
11
  ### 1. Create a new project
12
12
 
13
13
  ```bash
14
- npm create openadminjs@latest my-app
14
+ npx openadminjs create my-app
15
15
  cd my-app
16
16
  ```
17
17
 
18
- Use `npm create ...` for bootstrap. Global installation (`npm i -g openadminjs`) is not the recommended flow.
18
+ `npx` runs the single `openadminjs` package and scaffolds the project with dependencies installed automatically.
19
+ During scaffolding, you can choose the database driver from a list (PostgreSQL, MySQL, or SQLite), and the CLI fills `DATABASE_URL` for you.
19
20
 
20
21
  ### 2. Configure environment
21
22
 
22
- Create `apps/api/.env` in the generated project.
23
+ The scaffold wizard asks for database access and key env values (`DATABASE_URL`, `REDIS_URL`, JWT secrets, `ADMIN_ORIGIN`, `API_PORT`) and writes them into `.env.example`.
24
+ Copy it to `.env` in the generated project, then adjust as needed.
23
25
 
24
- Minimal example:
26
+ Minimal `.env` example:
25
27
 
26
28
  ```env
27
29
  NODE_ENV=development
@@ -71,6 +73,36 @@ After a successful seed:
71
73
  - Generated app `apps/web` for public frontend pages and SEO.
72
74
  - CLI: `dev`, `build`, `db migrate`, `db seed`, `generate resource`, `doctor`, `security check`.
73
75
 
76
+ ## Plugin Platform
77
+
78
+ OpenAdminJS now uses a broad extension model (no legacy compatibility layer). Plugins can register multiple surfaces through `@openadminjs/plugin-sdk`:
79
+
80
+ - `resource` hooks (CRUD lifecycle)
81
+ - `api` hooks/routes
82
+ - `media` pipeline (upload transforms)
83
+ - `seo` metadata/sitemap contributors
84
+ - `jobs` handlers
85
+ - `adminUi` extensions (menus/pages/widgets/actions)
86
+
87
+ Plugins are controlled by manifest capabilities and trust mode (`trusted` / `sandboxed`) in `apps/api/plugins.manifest.json`.
88
+
89
+ ### Capability matrix
90
+
91
+ - `resource.hooks` — CRUD lifecycle hooks per resource.
92
+ - `api.hooks` / `api.routes` — request lifecycle hooks and custom API endpoints.
93
+ - `media.pipeline` — file/image transform pipeline.
94
+ - `seo.extend` — metadata + sitemap contributors.
95
+ - `jobs.run` — background job handlers.
96
+ - `admin.ui.extend` — admin menu/page/widget/action extensions.
97
+
98
+ `trusted` mode may run with broad access; `sandboxed` mode should explicitly declare only required capabilities.
99
+
100
+ Generate a starter plugin:
101
+
102
+ ```bash
103
+ pnpm exec openadminjs generate plugin com.example.my-plugin
104
+ ```
105
+
74
106
  ### Optional queue setup
75
107
 
76
108
  Set `REDIS_URL` in your environment to enable queue processing (example: `redis://localhost:6379`).
@@ -19,12 +19,21 @@ type PluginRow = {
19
19
  bundled?: string;
20
20
  package?: string;
21
21
  config?: Record<string, unknown>;
22
+ trustMode?: "trusted" | "sandboxed";
23
+ capabilities?: string[];
22
24
  };
23
25
 
24
26
  type PluginsState = {
25
27
  manifestPath: string;
26
28
  bundledAvailable: string[];
27
29
  plugins: PluginRow[];
30
+ runtime?: {
31
+ adminUiExtensions: number;
32
+ jobs: number;
33
+ apiHooks: number;
34
+ mediaHooks: number;
35
+ seoHooks: number;
36
+ };
28
37
  };
29
38
 
30
39
  export default function PluginsPage() {
@@ -38,6 +47,8 @@ export default function PluginsPage() {
38
47
  const [bundledKey, setBundledKey] = useState("hello");
39
48
  const [packageName, setPackageName] = useState("");
40
49
  const [runPnpm, setRunPnpm] = useState(false);
50
+ const [trustMode, setTrustMode] = useState<"trusted" | "sandboxed">("trusted");
51
+ const [capsText, setCapsText] = useState("");
41
52
  const [adding, setAdding] = useState(false);
42
53
 
43
54
  const load = useCallback(async () => {
@@ -76,18 +87,34 @@ export default function PluginsPage() {
76
87
  method: "POST",
77
88
  body: JSON.stringify(
78
89
  addMode === "bundled"
79
- ? { id: newId.trim(), bundled: bundledKey, enabled: true, config: {} }
90
+ ? {
91
+ id: newId.trim(),
92
+ bundled: bundledKey,
93
+ enabled: true,
94
+ config: {},
95
+ trustMode,
96
+ capabilities: capsText
97
+ .split(",")
98
+ .map((item) => item.trim())
99
+ .filter(Boolean)
100
+ }
80
101
  : {
81
102
  id: newId.trim(),
82
103
  package: packageName.trim(),
83
104
  enabled: true,
84
105
  config: {},
106
+ trustMode,
107
+ capabilities: capsText
108
+ .split(",")
109
+ .map((item) => item.trim())
110
+ .filter(Boolean),
85
111
  runPnpmInstall: runPnpm
86
112
  }
87
113
  )
88
114
  });
89
115
  setNewId("");
90
116
  setPackageName("");
117
+ setCapsText("");
91
118
  await load();
92
119
  } catch (e) {
93
120
  setError(e instanceof Error ? e.message : "Failed to add plugin");
@@ -178,6 +205,12 @@ export default function PluginsPage() {
178
205
  <span className="break-all font-mono text-slate-700">{state.manifestPath}</span>
179
206
  </p>
180
207
  )}
208
+ {state?.runtime && (
209
+ <p className="mt-2 text-xs text-slate-500">
210
+ Runtime surfaces: ui {state.runtime.adminUiExtensions}, jobs {state.runtime.jobs}, api {state.runtime.apiHooks}, media{" "}
211
+ {state.runtime.mediaHooks}, seo {state.runtime.seoHooks}
212
+ </p>
213
+ )}
181
214
  </div>
182
215
  </div>
183
216
  </div>
@@ -250,6 +283,24 @@ export default function PluginsPage() {
250
283
  </label>
251
284
  )}
252
285
  </div>
286
+ <div className="mt-3 grid gap-3 sm:grid-cols-2">
287
+ <label className="block space-y-1.5">
288
+ <span className="text-xs font-semibold uppercase tracking-wide text-slate-500">Trust mode</span>
289
+ <select className="input-base" value={trustMode} onChange={(e) => setTrustMode(e.target.value as "trusted" | "sandboxed")}>
290
+ <option value="trusted">trusted</option>
291
+ <option value="sandboxed">sandboxed</option>
292
+ </select>
293
+ </label>
294
+ <label className="block space-y-1.5">
295
+ <span className="text-xs font-semibold uppercase tracking-wide text-slate-500">Capabilities (comma separated)</span>
296
+ <input
297
+ className="input-base font-mono text-xs"
298
+ value={capsText}
299
+ onChange={(e) => setCapsText(e.target.value)}
300
+ placeholder="resource.hooks,seo.extend,media.pipeline"
301
+ />
302
+ </label>
303
+ </div>
253
304
 
254
305
  {addMode === "package" && (
255
306
  <label className="mt-3 flex cursor-pointer items-center gap-2 text-sm text-slate-600">
@@ -311,6 +362,14 @@ export default function PluginsPage() {
311
362
  >
312
363
  {row.enabled === false ? "Disabled" : "Enabled"}
313
364
  </span>
365
+ <p className="mt-1 text-xs text-slate-500">
366
+ trust: <span className="font-mono text-slate-700">{row.trustMode ?? "trusted"}</span>
367
+ </p>
368
+ {row.capabilities && row.capabilities.length > 0 && (
369
+ <p className="mt-1 text-xs text-slate-500">
370
+ caps: <span className="font-mono text-slate-700">{row.capabilities.join(", ")}</span>
371
+ </p>
372
+ )}
314
373
  </div>
315
374
  <div className="flex shrink-0 items-center gap-2">
316
375
  <button
@@ -4,12 +4,24 @@
4
4
  {
5
5
  "id": "io.openadminjs.hello",
6
6
  "enabled": true,
7
+ "trustMode": "trusted",
8
+ "capabilities": ["resource.hooks"],
7
9
  "bundled": "hello",
8
10
  "config": { "tag": "optional-config-passed-to-plugin" }
9
11
  },
12
+ {
13
+ "id": "io.openadminjs.seo",
14
+ "enabled": false,
15
+ "trustMode": "sandboxed",
16
+ "capabilities": ["seo.extend"],
17
+ "bundled": "seo",
18
+ "config": {}
19
+ },
10
20
  {
11
21
  "id": "com.vendor.billing",
12
22
  "enabled": false,
23
+ "trustMode": "sandboxed",
24
+ "capabilities": ["resource.hooks", "api.routes", "jobs.run", "admin.ui.extend"],
13
25
  "package": "@vendor/openadmin-billing",
14
26
  "marketplace": {
15
27
  "listingUrl": "https://example.com/plugins/billing",
@@ -1,6 +1,7 @@
1
1
  import { BadRequestException, ForbiddenException, Injectable } from "@nestjs/common";
2
2
  import type { Prisma } from "@prisma/client";
3
3
  import { PrismaService } from "../common/prisma.service";
4
+ import { pluginRuntime } from "../plugins/plugin-runtime";
4
5
  import { resources } from "../resources/registry";
5
6
  import { AdminResourceService } from "./admin-resource.service";
6
7
 
@@ -1071,20 +1072,52 @@ export class AdminAiService {
1071
1072
  meta?: Record<string, unknown>;
1072
1073
  }
1073
1074
  ) {
1074
- const contentBase64 =
1075
+ const initialContentBase64 =
1075
1076
  input.encoding === "base64" ? content : Buffer.from(content, "utf8").toString("base64");
1077
+ let filename = input.filename.slice(0, 180);
1078
+ let mimeType = input.mimeType.slice(0, 120);
1079
+ let contentBase64 = initialContentBase64;
1080
+ for (const hooks of pluginRuntime.getMediaHooks()) {
1081
+ await hooks.beforeStore?.({
1082
+ filename,
1083
+ mimeType,
1084
+ size: Buffer.from(contentBase64, "base64").byteLength,
1085
+ contentBase64,
1086
+ user: { id: userId, email: "", permissions: [] }
1087
+ });
1088
+ if (hooks.transform) {
1089
+ const transformed = await hooks.transform({
1090
+ filename,
1091
+ mimeType,
1092
+ contentBase64,
1093
+ user: { id: userId, email: "", permissions: [] }
1094
+ });
1095
+ filename = (transformed.filename ?? filename).slice(0, 180);
1096
+ mimeType = (transformed.mimeType ?? mimeType).slice(0, 120);
1097
+ contentBase64 = transformed.contentBase64;
1098
+ }
1099
+ }
1076
1100
  const size = Buffer.from(contentBase64, "base64").byteLength;
1077
1101
  const artifact = await this.prisma.aiArtifact.create({
1078
1102
  data: {
1079
1103
  userId,
1080
1104
  conversationId: input.conversationId ?? null,
1081
- filename: input.filename.slice(0, 180),
1082
- mimeType: input.mimeType.slice(0, 120),
1105
+ filename,
1106
+ mimeType,
1083
1107
  size,
1084
1108
  contentBase64,
1085
1109
  meta: (input.meta ?? null) as Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput
1086
1110
  }
1087
1111
  });
1112
+ for (const hooks of pluginRuntime.getMediaHooks()) {
1113
+ await hooks.afterStore?.({
1114
+ fileId: artifact.id,
1115
+ filename: artifact.filename,
1116
+ mimeType: artifact.mimeType,
1117
+ size: artifact.size,
1118
+ user: { id: userId, email: "", permissions: [] }
1119
+ });
1120
+ }
1088
1121
  return {
1089
1122
  id: artifact.id,
1090
1123
  artifactId: artifact.id,
@@ -17,6 +17,7 @@ import {
17
17
  type PluginManifest,
18
18
  type PluginManifestEntry
19
19
  } from "../plugins/manifest.schema";
20
+ import { pluginRuntime } from "../plugins/plugin-runtime";
20
21
 
21
22
  const execFileAsync = promisify(execFile);
22
23
 
@@ -62,7 +63,14 @@ export class AdminPluginsService {
62
63
  return {
63
64
  manifestPath: path,
64
65
  bundledAvailable: Object.keys(bundledOpenAdminPlugins),
65
- plugins: manifest.plugins
66
+ plugins: manifest.plugins,
67
+ runtime: {
68
+ adminUiExtensions: pluginRuntime.getAdminUiExtensions().length,
69
+ jobs: pluginRuntime.getJobs().length,
70
+ apiHooks: pluginRuntime.getApiHooks().length,
71
+ mediaHooks: pluginRuntime.getMediaHooks().length,
72
+ seoHooks: pluginRuntime.getSeoHooks().length
73
+ }
66
74
  };
67
75
  }
68
76
 
@@ -81,6 +89,8 @@ export class AdminPluginsService {
81
89
  package?: string;
82
90
  enabled?: boolean;
83
91
  config?: Record<string, unknown>;
92
+ trustMode?: "trusted" | "sandboxed";
93
+ capabilities?: string[];
84
94
  runPnpmInstall?: boolean;
85
95
  }) {
86
96
  const hasBundled = Boolean(dto.bundled);
@@ -103,7 +113,9 @@ export class AdminPluginsService {
103
113
  id: dto.id,
104
114
  enabled: dto.enabled ?? true,
105
115
  ...(dto.bundled ? { bundled: dto.bundled } : { package: dto.package! }),
106
- config: dto.config ?? {}
116
+ config: dto.config ?? {},
117
+ trustMode: dto.trustMode ?? "trusted",
118
+ capabilities: dto.capabilities ?? []
107
119
  };
108
120
 
109
121
  const entryParsed = pluginManifestEntrySchema.safeParse(entry);
@@ -144,7 +156,7 @@ export class AdminPluginsService {
144
156
  };
145
157
  }
146
158
 
147
- async patch(id: string, dto: { enabled?: boolean; config?: Record<string, unknown> }) {
159
+ async patch(id: string, dto: { enabled?: boolean; config?: Record<string, unknown>; trustMode?: "trusted" | "sandboxed"; capabilities?: string[] }) {
148
160
  const manifest = this.readManifestOrEmpty();
149
161
  const idx = manifest.plugins.findIndex((p) => p.id === id);
150
162
  if (idx === -1) {
@@ -153,6 +165,8 @@ export class AdminPluginsService {
153
165
  const cur = { ...manifest.plugins[idx]! };
154
166
  if (dto.enabled !== undefined) cur.enabled = dto.enabled;
155
167
  if (dto.config !== undefined) cur.config = dto.config;
168
+ if (dto.trustMode !== undefined) cur.trustMode = dto.trustMode;
169
+ if (dto.capabilities !== undefined) cur.capabilities = dto.capabilities;
156
170
 
157
171
  const entryParsed = pluginManifestEntrySchema.safeParse(cur);
158
172
  if (!entryParsed.success) {
@@ -224,7 +238,7 @@ export class AdminPluginsService {
224
238
  invalidateNpmPluginMainModule(entry.package);
225
239
  }
226
240
  try {
227
- applyManifestPluginEntry(entry);
241
+ await applyManifestPluginEntry(entry);
228
242
  return;
229
243
  } catch (e) {
230
244
  last = e instanceof Error ? e : new Error(String(e));
@@ -1,4 +1,4 @@
1
- import { IsBoolean, IsObject, IsOptional, IsString } from "class-validator";
1
+ import { IsArray, IsBoolean, IsIn, IsObject, IsOptional, IsString } from "class-validator";
2
2
 
3
3
  export class AddPluginDto {
4
4
  @IsString()
@@ -20,6 +20,15 @@ export class AddPluginDto {
20
20
  @IsObject()
21
21
  config?: Record<string, unknown>;
22
22
 
23
+ @IsOptional()
24
+ @IsIn(["trusted", "sandboxed"])
25
+ trustMode?: "trusted" | "sandboxed";
26
+
27
+ @IsOptional()
28
+ @IsArray()
29
+ @IsString({ each: true })
30
+ capabilities?: string[];
31
+
23
32
  /** When true and `package` is set, runs `pnpm add <package> --filter @openadminjs/api` (dev / non-production only). */
24
33
  @IsOptional()
25
34
  @IsBoolean()
@@ -34,4 +43,13 @@ export class PatchPluginDto {
34
43
  @IsOptional()
35
44
  @IsObject()
36
45
  config?: Record<string, unknown>;
46
+
47
+ @IsOptional()
48
+ @IsIn(["trusted", "sandboxed"])
49
+ trustMode?: "trusted" | "sandboxed";
50
+
51
+ @IsOptional()
52
+ @IsArray()
53
+ @IsString({ each: true })
54
+ capabilities?: string[];
37
55
  }
@@ -3,6 +3,7 @@ import "./plugins/bootstrap";
3
3
  import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { Module } from "@nestjs/common";
6
+ import { APP_INTERCEPTOR } from "@nestjs/core";
6
7
  import { ConfigModule } from "@nestjs/config";
7
8
  import { ThrottlerModule } from "@nestjs/throttler";
8
9
  import { PrismaService } from "./common/prisma.service";
@@ -12,6 +13,7 @@ import { HealthController } from "./health/health.controller";
12
13
  import { QueueModule } from "./queue/queue.module";
13
14
  import { StoreModule } from "./store/store.module";
14
15
  import { MailModule } from "./mail/mail.module";
16
+ import { PluginApiInterceptor } from "./plugins/plugin-api.interceptor";
15
17
 
16
18
  const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "api", ".env")].filter((p) =>
17
19
  existsSync(p)
@@ -31,7 +33,13 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
31
33
  StoreModule
32
34
  ],
33
35
  controllers: [HealthController],
34
- providers: [PrismaService],
36
+ providers: [
37
+ PrismaService,
38
+ {
39
+ provide: APP_INTERCEPTOR,
40
+ useClass: PluginApiInterceptor
41
+ }
42
+ ],
35
43
  exports: [PrismaService]
36
44
  })
37
45
  export class AppModule {}
@@ -1,4 +1,4 @@
1
- import { loadPluginsFromManifestSync } from "./plugin-loader";
1
+ import { loadPluginsFromManifest } from "./plugin-loader";
2
2
 
3
3
  /** Runs after core `resource-hooks.install` so plugin hooks stack after built-ins. */
4
- loadPluginsFromManifestSync();
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,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
+ };
@@ -1,7 +1,13 @@
1
1
  import type { OpenAdminPlugin } from "@openadminjs/plugin-sdk";
2
+ import { adminWidgetBundledPlugin } from "./admin-widget.plugin";
2
3
  import { helloBundledPlugin } from "./hello.plugin";
4
+ import { imageOptimizerBundledPlugin } from "./image-optimizer.plugin";
5
+ import { seoBundledPlugin } from "./seo.plugin";
3
6
 
4
7
  /** First-party plugins shipped inside the API package (no separate npm install). */
5
8
  export const bundledOpenAdminPlugins: Record<string, OpenAdminPlugin> = {
6
- hello: helloBundledPlugin
9
+ hello: helloBundledPlugin,
10
+ seo: seoBundledPlugin,
11
+ "image-optimizer": imageOptimizerBundledPlugin,
12
+ "admin-widget": adminWidgetBundledPlugin
7
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
+ };
@@ -5,11 +5,19 @@ describe("pluginManifestSchema", () => {
5
5
  it("accepts bundled-only entry", () => {
6
6
  const r = pluginManifestSchema.safeParse({
7
7
  version: 1,
8
- plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 } }]
8
+ plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 }, capabilities: ["resource.hooks"], trustMode: "sandboxed" }]
9
9
  });
10
10
  expect(r.success).toBe(true);
11
11
  });
12
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
+
13
21
  it("rejects both bundled and package", () => {
14
22
  const r = pluginManifestSchema.safeParse({
15
23
  version: 1,
@@ -1,9 +1,23 @@
1
1
  import { z } from "zod";
2
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
+
3
15
  export const pluginManifestEntrySchema = z
4
16
  .object({
5
17
  id: z.string().min(1),
6
18
  enabled: z.boolean().optional().default(true),
19
+ trustMode: z.enum(["trusted", "sandboxed"]).optional().default("trusted"),
20
+ capabilities: z.array(capabilitySchema).optional().default([]),
7
21
  bundled: z
8
22
  .string()
9
23
  .regex(/^[a-z0-9-]+$/, "bundled id must be lowercase slug")
@@ -14,6 +28,12 @@ export const pluginManifestEntrySchema = z
14
28
  .regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/i, "invalid npm package name")
15
29
  .optional(),
16
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(),
17
37
  marketplace: z
18
38
  .object({
19
39
  listingUrl: z.string().optional(),
@@ -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
+ }