openadminjs 0.1.15 → 0.1.17
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.
- package/dist/create-project.js +4 -1
- package/dist/index.js +127 -0
- package/package.json +2 -2
- package/template/apps/admin/.storybook/main.ts +12 -0
- package/template/apps/admin/.storybook/preview.ts +10 -0
- package/template/apps/admin/app/dashboard/page.tsx +357 -277
- package/template/apps/admin/app/layout.tsx +5 -1
- package/template/apps/admin/app/login/page.tsx +38 -0
- package/template/apps/admin/app/resources/[resource]/page.tsx +15 -1
- package/template/apps/admin/app/settings/page.tsx +40 -2
- package/template/apps/admin/app/system-logs/page.tsx +212 -0
- package/template/apps/admin/components/api-error-banner.tsx +26 -0
- package/template/apps/admin/components/app-shell.tsx +92 -18
- package/template/apps/admin/components/logo.stories.tsx +24 -0
- package/template/apps/admin/components/resource-form.tsx +47 -0
- package/template/apps/admin/components/resource-table.tsx +417 -44
- package/template/apps/admin/lib/api.ts +44 -1
- package/template/apps/admin/lib/resource-table-prefs.ts +57 -0
- package/template/apps/admin/package.json +6 -0
- package/template/apps/admin/storybook-static/370.e922f076.iframe.bundle.js +9 -0
- package/template/apps/admin/storybook-static/389.c0dd6bde.iframe.bundle.js +818 -0
- package/template/apps/admin/storybook-static/990.36428b6c.iframe.bundle.js +25 -0
- package/template/apps/admin/storybook-static/favicon-wrapper.svg +46 -0
- package/template/apps/admin/storybook-static/favicon.svg +1 -0
- package/template/apps/admin/storybook-static/iframe.html +560 -0
- package/template/apps/admin/storybook-static/index.html +139 -0
- package/template/apps/admin/storybook-static/index.json +1 -0
- package/template/apps/admin/storybook-static/logo-stories.c470fc8c.iframe.bundle.js +1 -0
- package/template/apps/admin/storybook-static/main.743ea6f2.iframe.bundle.js +2550 -0
- package/template/apps/admin/storybook-static/mocker-runtime-injected.js +2 -0
- package/template/apps/admin/storybook-static/nunito-sans-bold-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-bold.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/nunito-sans-regular.woff2 +0 -0
- package/template/apps/admin/storybook-static/project.json +1 -0
- package/template/apps/admin/storybook-static/runtime~main.6f822e3b.iframe.bundle.js +2 -0
- package/template/apps/admin/storybook-static/sb-addons/onboarding-1/manager-bundle.js +97 -0
- package/template/apps/admin/storybook-static/sb-addons/storybook-core-server-presets-0/common-manager-bundle.js +630 -0
- package/template/apps/admin/storybook-static/sb-common-assets/favicon-wrapper.svg +46 -0
- package/template/apps/admin/storybook-static/sb-common-assets/favicon.svg +1 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-italic.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-regular.woff2 +0 -0
- package/template/apps/admin/storybook-static/sb-manager/globals-runtime.js +76309 -0
- package/template/apps/admin/storybook-static/sb-manager/globals.js +24 -0
- package/template/apps/admin/storybook-static/sb-manager/manager-stores.js +23 -0
- package/template/apps/admin/storybook-static/sb-manager/runtime.js +26078 -0
- package/template/apps/admin/storybook-static/sb-preview/globals.js +20 -0
- package/template/apps/admin/storybook-static/sb-preview/runtime.js +35472 -0
- package/template/apps/api/package.json +13 -2
- package/template/apps/api/plugins.manifest.example.json +12 -0
- package/template/apps/api/src/admin/admin-logs.controller.ts +31 -0
- package/template/apps/api/src/admin/admin-plugins.controller.ts +5 -0
- package/template/apps/api/src/admin/admin-plugins.service.ts +11 -0
- package/template/apps/api/src/admin/admin-resource.service.ts +235 -1
- package/template/apps/api/src/admin/admin.controller.ts +35 -0
- package/template/apps/api/src/admin/admin.module.ts +6 -3
- package/template/apps/api/src/admin/dto/resource-bulk.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-reorder.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-upload.dto.ts +20 -0
- package/template/apps/api/src/app.module.ts +45 -5
- package/template/apps/api/src/auth/auth.module.ts +5 -3
- package/template/apps/api/src/auth/auth.service.test.ts +6 -3
- package/template/apps/api/src/auth/auth.service.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.controller.ts +78 -0
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.service.ts +281 -0
- package/template/apps/api/src/common/app-logger.service.ts +138 -0
- package/template/apps/api/src/common/auth.guard.test.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +15 -1
- package/template/apps/api/src/common/current-user.decorator.ts +6 -2
- package/template/apps/api/src/common/logging.module.ts +10 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +70 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +44 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.ts +65 -0
- package/template/apps/api/src/graphql/graphql.module.ts +26 -0
- package/template/apps/api/src/main.ts +2 -0
- package/template/apps/api/src/plugins/bundled/registry.ts +3 -1
- package/template/apps/api/src/plugins/bundled/webhook.plugin.ts +64 -0
- package/template/apps/api/src/resources/categories.resource.ts +1 -0
- package/template/apps/api/src/resources/system.resource.ts +1 -0
- package/template/packages/core/src/index.ts +5 -0
- package/template/packages/core/vitest.config.ts +9 -0
- package/template/packages/resource/package.json +11 -0
- package/template/packages/resource/src/index.test.ts +45 -0
- package/template/packages/resource/src/index.ts +63 -0
- package/template/prisma/schema.prisma +5 -0
- package/template/packages/core/src/index.js +0 -1
- package/template/packages/permissions/src/blueprints.js +0 -57
- package/template/packages/permissions/src/index.js +0 -11
- package/template/packages/resource/src/index.js +0 -177
|
@@ -14,11 +14,14 @@
|
|
|
14
14
|
"db:seed": "prisma db seed --schema ../../prisma/schema.prisma"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
+
"@apollo/server": "^4.11.0",
|
|
17
18
|
"@casl/ability": "^6.8.1",
|
|
19
|
+
"@nestjs/apollo": "^12.2.1",
|
|
18
20
|
"@nestjs/bullmq": "^11.0.4",
|
|
19
21
|
"@nestjs/common": "^10.4.15",
|
|
20
22
|
"@nestjs/config": "^3.3.0",
|
|
21
23
|
"@nestjs/core": "^10.4.15",
|
|
24
|
+
"@nestjs/graphql": "^12.2.1",
|
|
22
25
|
"@nestjs/jwt": "^10.2.0",
|
|
23
26
|
"@nestjs/platform-express": "^10.4.15",
|
|
24
27
|
"@nestjs/swagger": "^8.1.0",
|
|
@@ -28,22 +31,30 @@
|
|
|
28
31
|
"@openadminjs/payments": "workspace:*",
|
|
29
32
|
"@openadminjs/permissions": "workspace:*",
|
|
30
33
|
"@openadminjs/plugin-sdk": "workspace:*",
|
|
31
|
-
"
|
|
32
|
-
"stripe": "^17.7.0",
|
|
34
|
+
"@openadminjs/storage": "workspace:^",
|
|
33
35
|
"@prisma/client": "^6.1.0",
|
|
36
|
+
"@types/express": "^5.0.6",
|
|
34
37
|
"bcryptjs": "^2.4.3",
|
|
35
38
|
"bullmq": "^5.76.4",
|
|
36
39
|
"class-transformer": "^0.5.1",
|
|
37
40
|
"class-validator": "^0.14.1",
|
|
41
|
+
"cookie-parser": "^1.4.7",
|
|
42
|
+
"graphql": "^16.14.0",
|
|
43
|
+
"graphql-scalars": "^1.25.0",
|
|
38
44
|
"helmet": "^8.0.0",
|
|
39
45
|
"ioredis": "^5.10.1",
|
|
46
|
+
"nodemailer": "^6.9.16",
|
|
40
47
|
"reflect-metadata": "^0.2.2",
|
|
41
48
|
"rxjs": "^7.8.1",
|
|
49
|
+
"stripe": "^17.7.0",
|
|
50
|
+
"winston": "^3.19.0",
|
|
51
|
+
"winston-daily-rotate-file": "^5.0.0",
|
|
42
52
|
"zod": "^3.24.1"
|
|
43
53
|
},
|
|
44
54
|
"devDependencies": {
|
|
45
55
|
"@nestjs/cli": "^10.4.8",
|
|
46
56
|
"@types/bcryptjs": "^2.4.6",
|
|
57
|
+
"@types/cookie-parser": "^1.4.10",
|
|
47
58
|
"@types/nodemailer": "^6.4.17",
|
|
48
59
|
"prisma": "^6.1.0",
|
|
49
60
|
"tsx": "4.19.2",
|
|
@@ -17,6 +17,18 @@
|
|
|
17
17
|
"bundled": "seo",
|
|
18
18
|
"config": {}
|
|
19
19
|
},
|
|
20
|
+
{
|
|
21
|
+
"id": "io.openadminjs.webhook",
|
|
22
|
+
"enabled": false,
|
|
23
|
+
"trustMode": "sandboxed",
|
|
24
|
+
"capabilities": ["resource.hooks"],
|
|
25
|
+
"bundled": "webhook",
|
|
26
|
+
"config": {
|
|
27
|
+
"url": "https://example.com/openadmin-hooks",
|
|
28
|
+
"secret": "optional-shared-secret",
|
|
29
|
+
"resources": ["posts", "orders"]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
20
32
|
{
|
|
21
33
|
"id": "com.vendor.billing",
|
|
22
34
|
"enabled": false,
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Controller, Get, Inject, Query, UseGuards } from "@nestjs/common";
|
|
2
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
3
|
+
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
4
|
+
import { AppLoggerService } from "../common/app-logger.service";
|
|
5
|
+
|
|
6
|
+
@UseGuards(AuthGuard)
|
|
7
|
+
@RequireAuthRealm("admin")
|
|
8
|
+
@Controller("admin/logs")
|
|
9
|
+
export class AdminLogsController {
|
|
10
|
+
constructor(@Inject(AppLoggerService) private readonly logs: AppLoggerService) {}
|
|
11
|
+
|
|
12
|
+
@Get()
|
|
13
|
+
list(
|
|
14
|
+
@Query("level") level: "info" | "error" | undefined,
|
|
15
|
+
@Query("search") search: string | undefined,
|
|
16
|
+
@Query("from") from: string | undefined,
|
|
17
|
+
@Query("to") to: string | undefined,
|
|
18
|
+
@Query("page") page: string | undefined,
|
|
19
|
+
@Query("limit") limit: string | undefined
|
|
20
|
+
) {
|
|
21
|
+
return this.logs.query({
|
|
22
|
+
level,
|
|
23
|
+
search,
|
|
24
|
+
from,
|
|
25
|
+
to,
|
|
26
|
+
page: Number(page ?? 1),
|
|
27
|
+
limit: Number(limit ?? 50)
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
@@ -74,6 +74,17 @@ export class AdminPluginsService {
|
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
getDashboardWidgets() {
|
|
78
|
+
return pluginRuntime
|
|
79
|
+
.getAdminUiExtensions()
|
|
80
|
+
.filter((item) => item.kind === "widget")
|
|
81
|
+
.map((item) => ({
|
|
82
|
+
id: item.id,
|
|
83
|
+
title: item.title,
|
|
84
|
+
config: item.config ?? {}
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
|
|
77
88
|
private writeManifest(manifest: PluginManifest) {
|
|
78
89
|
const path = resolveWritableManifestPath();
|
|
79
90
|
const parsed = pluginManifestSchema.safeParse(manifest);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { BadRequestException, ForbiddenException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
1
|
+
import { BadRequestException, ForbiddenException, HttpException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
2
2
|
import { Prisma } from "@prisma/client";
|
|
3
|
+
import { defaultFileValidation } from "@openadminjs/storage";
|
|
3
4
|
import type { ResourceConfig, ResourceField } from "@openadminjs/core";
|
|
4
5
|
import {
|
|
5
6
|
listScopeWhereClause,
|
|
@@ -9,7 +10,10 @@ import {
|
|
|
9
10
|
} from "@openadminjs/core";
|
|
10
11
|
import bcrypt from "bcryptjs";
|
|
11
12
|
import { randomBytes } from "node:crypto";
|
|
13
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
12
15
|
import { PrismaService } from "../common/prisma.service";
|
|
16
|
+
import { pluginRuntime } from "../plugins/plugin-runtime";
|
|
13
17
|
import { getResource, resources } from "../resources/registry";
|
|
14
18
|
import {
|
|
15
19
|
runAfterCreate,
|
|
@@ -54,6 +58,48 @@ export class AdminResourceService {
|
|
|
54
58
|
});
|
|
55
59
|
}
|
|
56
60
|
|
|
61
|
+
async globalSearch(
|
|
62
|
+
query: string,
|
|
63
|
+
user: UserContext,
|
|
64
|
+
opts?: { perResourceLimit?: number; resources?: string[] }
|
|
65
|
+
): Promise<Array<{ resource: string; resourceLabel: string; id: string; title: string }>> {
|
|
66
|
+
const q = query.trim();
|
|
67
|
+
if (q.length < 2) return [];
|
|
68
|
+
const perResourceLimit = Math.min(Math.max(opts?.perResourceLimit ?? 5, 1), 20);
|
|
69
|
+
const whitelist = opts?.resources ? new Set(opts.resources.map((v) => v.toLowerCase())) : null;
|
|
70
|
+
const out: Array<{ resource: string; resourceLabel: string; id: string; title: string }> = [];
|
|
71
|
+
|
|
72
|
+
for (const resource of resources) {
|
|
73
|
+
if (whitelist && !whitelist.has(resource.name.toLowerCase())) continue;
|
|
74
|
+
if (!this.has(user, resource.permissions.read)) continue;
|
|
75
|
+
const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable).map(([name]) => name);
|
|
76
|
+
if (!searchable.length) continue;
|
|
77
|
+
|
|
78
|
+
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
79
|
+
const where = mergeWhereClauses(
|
|
80
|
+
{
|
|
81
|
+
OR: searchable.map((field) => ({ [field]: { contains: q, mode: "insensitive" } }))
|
|
82
|
+
},
|
|
83
|
+
scope
|
|
84
|
+
);
|
|
85
|
+
const rows = await this.delegate(resource).findMany({
|
|
86
|
+
where,
|
|
87
|
+
take: perResourceLimit,
|
|
88
|
+
orderBy: this.buildOrderBy(resource, "createdAt:desc")
|
|
89
|
+
});
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
const safe = this.sanitizeRecord(resource, row) as Record<string, unknown>;
|
|
92
|
+
const id = String(safe.id ?? "");
|
|
93
|
+
if (!id) continue;
|
|
94
|
+
const tf = resource.titleField ?? "id";
|
|
95
|
+
const title = String(safe[tf] ?? safe.name ?? safe.title ?? id);
|
|
96
|
+
out.push({ resource: resource.name, resourceLabel: String(resource.label), id, title });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return out.slice(0, 60);
|
|
101
|
+
}
|
|
102
|
+
|
|
57
103
|
async list(name: string, query: Record<string, unknown>, user: UserContext) {
|
|
58
104
|
const resource = this.authorizedResource(name, user, "read");
|
|
59
105
|
const delegate = this.delegate(resource);
|
|
@@ -203,6 +249,194 @@ export class AdminResourceService {
|
|
|
203
249
|
throw new NotFoundException({ message: "Action not implemented for this resource", code: "ACTION_NOT_IMPLEMENTED" });
|
|
204
250
|
}
|
|
205
251
|
|
|
252
|
+
async bulk(
|
|
253
|
+
name: string,
|
|
254
|
+
dto: { action: string; ids: string[]; input?: Record<string, unknown> },
|
|
255
|
+
user: UserContext
|
|
256
|
+
): Promise<{ ok: number; failures: { id: string; message: string }[] }> {
|
|
257
|
+
const uniqueIds = [...new Set(dto.ids.map(String).filter(Boolean))];
|
|
258
|
+
if (!uniqueIds.length) throw new BadRequestException({ message: "No ids provided", code: "BULK_EMPTY" });
|
|
259
|
+
|
|
260
|
+
const failures: { id: string; message: string }[] = [];
|
|
261
|
+
let ok = 0;
|
|
262
|
+
|
|
263
|
+
if (dto.action === "delete") {
|
|
264
|
+
this.authorizedResource(name, user, "delete");
|
|
265
|
+
for (const id of uniqueIds) {
|
|
266
|
+
try {
|
|
267
|
+
await this.delete(name, id, user);
|
|
268
|
+
ok += 1;
|
|
269
|
+
} catch (err: unknown) {
|
|
270
|
+
failures.push({ id, message: this.bulkErrorMessage(err) });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return { ok, failures };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const resource = getResource(name);
|
|
277
|
+
const config = resource?.actions?.[dto.action];
|
|
278
|
+
if (!resource || !config?.handler) {
|
|
279
|
+
throw new NotFoundException({ message: "Action not found", code: "ACTION_NOT_FOUND" });
|
|
280
|
+
}
|
|
281
|
+
if (!this.has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
282
|
+
|
|
283
|
+
for (const id of uniqueIds) {
|
|
284
|
+
try {
|
|
285
|
+
await this.action(name, id, dto.action, user, dto.input);
|
|
286
|
+
ok += 1;
|
|
287
|
+
} catch (err: unknown) {
|
|
288
|
+
failures.push({ id, message: this.bulkErrorMessage(err) });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return { ok, failures };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async reorder(name: string, orderedIds: string[], user: UserContext, baseIndex = 0): Promise<{ ok: true }> {
|
|
295
|
+
const resource = this.authorizedResource(name, user, "update");
|
|
296
|
+
const orderField = resource.fields.order;
|
|
297
|
+
if (!orderField || orderField.type !== "number" || orderField.edit === false) {
|
|
298
|
+
throw new BadRequestException({ message: "Resource does not support drag-and-drop ordering", code: "REORDER_UNSUPPORTED" });
|
|
299
|
+
}
|
|
300
|
+
const uniqueIds = [...new Set(orderedIds.map(String).filter(Boolean))];
|
|
301
|
+
if (!uniqueIds.length) throw new BadRequestException({ message: "No ids provided", code: "REORDER_EMPTY" });
|
|
302
|
+
|
|
303
|
+
const delegate = this.delegate(resource);
|
|
304
|
+
const rows = await delegate.findMany({ where: { id: { in: uniqueIds } } });
|
|
305
|
+
if (rows.length !== uniqueIds.length) {
|
|
306
|
+
throw new BadRequestException({ message: "One or more records were not found", code: "REORDER_IDS_INVALID" });
|
|
307
|
+
}
|
|
308
|
+
for (const row of rows) {
|
|
309
|
+
if (this.isOutOfListScope(resource, user, row)) {
|
|
310
|
+
throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
await this.prisma.$transaction(async (tx) => {
|
|
315
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
316
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
317
|
+
for (let i = 0; i < uniqueIds.length; i++) {
|
|
318
|
+
await txDelegate.update({
|
|
319
|
+
where: { id: uniqueIds[i] },
|
|
320
|
+
data: { order: baseIndex + i }
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
await this.prisma.auditLog.create({
|
|
326
|
+
data: {
|
|
327
|
+
userId: user.id,
|
|
328
|
+
resource: name,
|
|
329
|
+
resourceId: uniqueIds[0],
|
|
330
|
+
action: "reorder",
|
|
331
|
+
before: { ids: uniqueIds, previous: rows.map((r) => ({ id: (r as { id: string }).id, order: (r as { order?: number }).order })) } as object,
|
|
332
|
+
after: { ids: uniqueIds, baseIndex, order: uniqueIds.map((id, index) => ({ id, order: baseIndex + index })) } as object
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
return { ok: true };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async uploadFile(
|
|
340
|
+
input: { filename: string; mimeType: string; contentBase64: string; targetPath?: string },
|
|
341
|
+
user: UserContext
|
|
342
|
+
): Promise<Record<string, unknown>> {
|
|
343
|
+
const filesResource = this.authorizedResource("files", user, "create");
|
|
344
|
+
const filename = String(input.filename ?? "").trim();
|
|
345
|
+
const mimeType = String(input.mimeType ?? "").trim().toLowerCase();
|
|
346
|
+
const rawBase64 = String(input.contentBase64 ?? "").trim();
|
|
347
|
+
if (!filename || !mimeType || !rawBase64) {
|
|
348
|
+
throw new BadRequestException({ message: "filename, mimeType and contentBase64 are required", code: "UPLOAD_INVALID" });
|
|
349
|
+
}
|
|
350
|
+
if (!defaultFileValidation.mimeTypes.includes(mimeType)) {
|
|
351
|
+
throw new BadRequestException({ message: "MIME type is not allowed", code: "UPLOAD_MIME_DENIED" });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
let contentBase64 = rawBase64;
|
|
355
|
+
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
356
|
+
await mediaHook.beforeStore?.({
|
|
357
|
+
filename,
|
|
358
|
+
mimeType,
|
|
359
|
+
size: Math.floor((contentBase64.length * 3) / 4),
|
|
360
|
+
contentBase64,
|
|
361
|
+
user: { ...user, email: user.email ?? "" }
|
|
362
|
+
});
|
|
363
|
+
const transformed = await mediaHook.transform?.({
|
|
364
|
+
filename,
|
|
365
|
+
mimeType,
|
|
366
|
+
contentBase64,
|
|
367
|
+
user: { ...user, email: user.email ?? "" }
|
|
368
|
+
});
|
|
369
|
+
if (transformed) {
|
|
370
|
+
contentBase64 = transformed.contentBase64;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const fileBuffer = Buffer.from(contentBase64, "base64");
|
|
375
|
+
if (fileBuffer.byteLength > defaultFileValidation.maxSizeBytes) {
|
|
376
|
+
throw new BadRequestException({ message: "File is too large", code: "UPLOAD_TOO_LARGE" });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const now = Date.now();
|
|
380
|
+
const safeFilename = filename.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
|
381
|
+
const relPath = this.resolveStorageRelativePath(input.targetPath, `uploads/${now}-${safeFilename}`);
|
|
382
|
+
const absPath = join(process.cwd(), relPath);
|
|
383
|
+
await mkdir(dirname(absPath), { recursive: true });
|
|
384
|
+
await writeFile(absPath, fileBuffer);
|
|
385
|
+
|
|
386
|
+
const record = await this.create(
|
|
387
|
+
"files",
|
|
388
|
+
{ filename, path: relPath, mimeType, size: fileBuffer.byteLength },
|
|
389
|
+
user
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
393
|
+
await mediaHook.afterStore?.({
|
|
394
|
+
fileId: String((record as Record<string, unknown>).id ?? ""),
|
|
395
|
+
filename,
|
|
396
|
+
mimeType,
|
|
397
|
+
size: fileBuffer.byteLength,
|
|
398
|
+
user: { ...user, email: user.email ?? "" }
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return record as Record<string, unknown>;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Resolve a relative storage path strictly under {@link process.cwd} (no traversal, no absolute paths).
|
|
407
|
+
*/
|
|
408
|
+
private resolveStorageRelativePath(targetPath: string | undefined, fallbackRelative: string): string {
|
|
409
|
+
const raw = (targetPath?.trim() || fallbackRelative).replace(/^[\\/]+/, "");
|
|
410
|
+
if (!raw || raw.includes("\0")) {
|
|
411
|
+
throw new BadRequestException({ message: "Invalid storage path", code: "UPLOAD_PATH_INVALID" });
|
|
412
|
+
}
|
|
413
|
+
if (raw.split(/[/\\]/).some((seg) => seg === "..")) {
|
|
414
|
+
throw new BadRequestException({ message: "Path traversal is not allowed", code: "UPLOAD_PATH_INVALID" });
|
|
415
|
+
}
|
|
416
|
+
const cwd = resolve(process.cwd());
|
|
417
|
+
const absolute = resolve(cwd, raw);
|
|
418
|
+
const rel = relative(cwd, absolute);
|
|
419
|
+
if (!rel || rel.startsWith("..") || rel === "..") {
|
|
420
|
+
throw new BadRequestException({ message: "Path must stay within project directory", code: "UPLOAD_PATH_INVALID" });
|
|
421
|
+
}
|
|
422
|
+
return rel.replace(/\\/g, "/");
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private bulkErrorMessage(err: unknown): string {
|
|
426
|
+
if (err instanceof HttpException) {
|
|
427
|
+
const r = err.getResponse();
|
|
428
|
+
if (typeof r === "string") return r;
|
|
429
|
+
if (r && typeof r === "object" && "message" in r) {
|
|
430
|
+
const m = (r as { message: unknown }).message;
|
|
431
|
+
if (Array.isArray(m)) return m.join(", ");
|
|
432
|
+
if (typeof m === "string") return m;
|
|
433
|
+
}
|
|
434
|
+
return err.message;
|
|
435
|
+
}
|
|
436
|
+
if (err instanceof Error) return err.message;
|
|
437
|
+
return "Request failed";
|
|
438
|
+
}
|
|
439
|
+
|
|
206
440
|
private isOutOfListScope(resource: ResourceConfig, user: UserContext, record: unknown): boolean {
|
|
207
441
|
if (!shouldApplyListScope(resource, user.permissions)) return false;
|
|
208
442
|
const clause = listScopeWhereClause(resource, user.id);
|
|
@@ -4,6 +4,9 @@ import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
|
4
4
|
import { CurrentUser } from "../common/current-user.decorator";
|
|
5
5
|
import { AdminResourceService } from "./admin-resource.service";
|
|
6
6
|
import { AdminAnalyticsService } from "./admin-analytics.service";
|
|
7
|
+
import { ResourceBulkDto } from "./dto/resource-bulk.dto";
|
|
8
|
+
import { ResourceReorderDto } from "./dto/resource-reorder.dto";
|
|
9
|
+
import { ResourceUploadDto } from "./dto/resource-upload.dto";
|
|
7
10
|
import { PaymentService } from "../store/payment/payment.service";
|
|
8
11
|
|
|
9
12
|
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
@@ -28,11 +31,43 @@ export class AdminController {
|
|
|
28
31
|
return this.resources.listResources(user, locale);
|
|
29
32
|
}
|
|
30
33
|
|
|
34
|
+
@Get("search")
|
|
35
|
+
search(
|
|
36
|
+
@Query("q") q: string | undefined,
|
|
37
|
+
@Query("limit") limit: string | undefined,
|
|
38
|
+
@CurrentUser() user: UserContext
|
|
39
|
+
) {
|
|
40
|
+
return this.resources.globalSearch(q ?? "", user, { perResourceLimit: Number(limit ?? 5) });
|
|
41
|
+
}
|
|
42
|
+
|
|
31
43
|
@Get(":resource")
|
|
32
44
|
list(@Param("resource") resource: string, @Query() query: Record<string, unknown>, @CurrentUser() user: UserContext) {
|
|
33
45
|
return this.resources.list(resource, query, user);
|
|
34
46
|
}
|
|
35
47
|
|
|
48
|
+
@Post(":resource/bulk")
|
|
49
|
+
bulk(
|
|
50
|
+
@Param("resource") resource: string,
|
|
51
|
+
@Body() body: ResourceBulkDto,
|
|
52
|
+
@CurrentUser() user: UserContext
|
|
53
|
+
) {
|
|
54
|
+
return this.resources.bulk(resource, body, user);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@Post(":resource/reorder")
|
|
58
|
+
reorder(
|
|
59
|
+
@Param("resource") resource: string,
|
|
60
|
+
@Body() body: ResourceReorderDto,
|
|
61
|
+
@CurrentUser() user: UserContext
|
|
62
|
+
) {
|
|
63
|
+
return this.resources.reorder(resource, body.ids, user, body.baseIndex ?? 0);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@Post("files/upload")
|
|
67
|
+
uploadFile(@Body() body: ResourceUploadDto, @CurrentUser() user: UserContext) {
|
|
68
|
+
return this.resources.uploadFile(body, user);
|
|
69
|
+
}
|
|
70
|
+
|
|
36
71
|
@Get(":resource/:id")
|
|
37
72
|
get(@Param("resource") resource: string, @Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
38
73
|
return this.resources.get(resource, id, user);
|
|
@@ -6,16 +6,18 @@ import { PermissionsGuard } from "../common/permissions.guard";
|
|
|
6
6
|
import { CaslAbilityFactory } from "../common/casl-ability.factory";
|
|
7
7
|
import { AdminController } from "./admin.controller";
|
|
8
8
|
import { AdminAiController } from "./admin-ai.controller";
|
|
9
|
+
import { AdminLogsController } from "./admin-logs.controller";
|
|
9
10
|
import { AdminPluginsController } from "./admin-plugins.controller";
|
|
10
11
|
import { AdminPluginsService } from "./admin-plugins.service";
|
|
11
12
|
import { AdminResourceService } from "./admin-resource.service";
|
|
12
13
|
import { AdminAnalyticsService } from "./admin-analytics.service";
|
|
13
14
|
import { AdminAiService } from "./admin-ai.service";
|
|
14
15
|
import { PaymentModule } from "../store/payment/payment.module";
|
|
16
|
+
import { LoggingModule } from "../common/logging.module";
|
|
15
17
|
|
|
16
18
|
@Module({
|
|
17
|
-
imports: [JwtModule.register({}), PaymentModule],
|
|
18
|
-
controllers: [AdminController, AdminPluginsController, AdminAiController],
|
|
19
|
+
imports: [JwtModule.register({}), PaymentModule, LoggingModule],
|
|
20
|
+
controllers: [AdminController, AdminPluginsController, AdminAiController, AdminLogsController],
|
|
19
21
|
providers: [
|
|
20
22
|
AdminResourceService,
|
|
21
23
|
AdminAnalyticsService,
|
|
@@ -25,6 +27,7 @@ import { PaymentModule } from "../store/payment/payment.module";
|
|
|
25
27
|
AuthGuard,
|
|
26
28
|
PermissionsGuard,
|
|
27
29
|
CaslAbilityFactory
|
|
28
|
-
]
|
|
30
|
+
],
|
|
31
|
+
exports: [AdminResourceService]
|
|
29
32
|
})
|
|
30
33
|
export class AdminModule {}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ArrayMaxSize, ArrayMinSize, IsArray, IsObject, IsOptional, IsString } from "class-validator";
|
|
2
|
+
|
|
3
|
+
export class ResourceBulkDto {
|
|
4
|
+
/** Use `"delete"` for bulk delete, or a key from `resource.actions`. */
|
|
5
|
+
@IsString()
|
|
6
|
+
action!: string;
|
|
7
|
+
|
|
8
|
+
@IsArray()
|
|
9
|
+
@ArrayMinSize(1)
|
|
10
|
+
@ArrayMaxSize(200)
|
|
11
|
+
@IsString({ each: true })
|
|
12
|
+
ids!: string[];
|
|
13
|
+
|
|
14
|
+
@IsOptional()
|
|
15
|
+
@IsObject()
|
|
16
|
+
input?: Record<string, unknown>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ArrayMaxSize, ArrayMinSize, IsArray, IsInt, IsOptional, IsString, Max, Min } from "class-validator";
|
|
2
|
+
|
|
3
|
+
export class ResourceReorderDto {
|
|
4
|
+
/** Ids in desired order (first = lowest `order` value). */
|
|
5
|
+
@IsArray()
|
|
6
|
+
@ArrayMinSize(1)
|
|
7
|
+
@ArrayMaxSize(500)
|
|
8
|
+
@IsString({ each: true })
|
|
9
|
+
ids!: string[];
|
|
10
|
+
|
|
11
|
+
/** When reordering a single page, pass `(page - 1) * pageSize` so `order` stays globally consistent. */
|
|
12
|
+
@IsOptional()
|
|
13
|
+
@IsInt()
|
|
14
|
+
@Min(0)
|
|
15
|
+
@Max(1_000_000)
|
|
16
|
+
baseIndex?: number;
|
|
17
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { IsOptional, IsString, MaxLength } from "class-validator";
|
|
2
|
+
|
|
3
|
+
export class ResourceUploadDto {
|
|
4
|
+
@IsString()
|
|
5
|
+
@MaxLength(260)
|
|
6
|
+
filename!: string;
|
|
7
|
+
|
|
8
|
+
@IsString()
|
|
9
|
+
@MaxLength(120)
|
|
10
|
+
mimeType!: string;
|
|
11
|
+
|
|
12
|
+
/** Base64 body without data-uri prefix. */
|
|
13
|
+
@IsString()
|
|
14
|
+
contentBase64!: string;
|
|
15
|
+
|
|
16
|
+
@IsOptional()
|
|
17
|
+
@IsString()
|
|
18
|
+
@MaxLength(260)
|
|
19
|
+
targetPath?: string;
|
|
20
|
+
}
|
|
@@ -3,12 +3,16 @@ 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";
|
|
7
|
-
import { ConfigModule } from "@nestjs/config";
|
|
8
|
-
import {
|
|
6
|
+
import { APP_GUARD, APP_INTERCEPTOR } from "@nestjs/core";
|
|
7
|
+
import { ConfigModule, ConfigService } from "@nestjs/config";
|
|
8
|
+
import { JwtService } from "@nestjs/jwt";
|
|
9
|
+
import { ThrottlerGuard, ThrottlerModule } from "@nestjs/throttler";
|
|
9
10
|
import { PrismaService } from "./common/prisma.service";
|
|
11
|
+
import { LoggingModule } from "./common/logging.module";
|
|
12
|
+
import { RequestLoggingInterceptor } from "./common/request-logging.interceptor";
|
|
10
13
|
import { AuthModule } from "./auth/auth.module";
|
|
11
14
|
import { AdminModule } from "./admin/admin.module";
|
|
15
|
+
import { GraphqlApiModule } from "./graphql/graphql.module";
|
|
12
16
|
import { HealthController } from "./health/health.controller";
|
|
13
17
|
import { QueueModule } from "./queue/queue.module";
|
|
14
18
|
import { StoreModule } from "./store/store.module";
|
|
@@ -25,9 +29,43 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
25
29
|
isGlobal: true,
|
|
26
30
|
envFilePath: envFilePath.length > 0 ? envFilePath : [".env"]
|
|
27
31
|
}),
|
|
28
|
-
|
|
29
|
-
MailModule,
|
|
32
|
+
LoggingModule,
|
|
30
33
|
AuthModule,
|
|
34
|
+
ThrottlerModule.forRootAsync({
|
|
35
|
+
imports: [AuthModule],
|
|
36
|
+
inject: [JwtService, ConfigService],
|
|
37
|
+
useFactory: (jwt: JwtService, config: ConfigService) => [
|
|
38
|
+
{
|
|
39
|
+
name: "default",
|
|
40
|
+
ttl: 60_000,
|
|
41
|
+
limit: 100,
|
|
42
|
+
getTracker: (req: { ip?: string }) => req.ip ?? "unknown"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "perUser",
|
|
46
|
+
ttl: 60_000,
|
|
47
|
+
limit: Number(config.get("RATE_LIMIT_USER_PER_MIN") ?? 120),
|
|
48
|
+
getTracker: async (req: { headers?: { authorization?: string }; ip?: string }) => {
|
|
49
|
+
const h = req.headers?.authorization;
|
|
50
|
+
const t = h?.startsWith("Bearer ") ? h.slice(7) : undefined;
|
|
51
|
+
if (t) {
|
|
52
|
+
try {
|
|
53
|
+
const secret = config.get<string>("JWT_SECRET")?.trim();
|
|
54
|
+
if (secret) {
|
|
55
|
+
const p = await jwt.verifyAsync<{ sub?: string }>(t, { secret });
|
|
56
|
+
if (p.sub) return `user:${p.sub}`;
|
|
57
|
+
}
|
|
58
|
+
} catch {
|
|
59
|
+
/* use IP bucket for invalid JWT */
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return `ip:${req.ip ?? "anon"}`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}),
|
|
67
|
+
GraphqlApiModule,
|
|
68
|
+
MailModule,
|
|
31
69
|
AdminModule,
|
|
32
70
|
QueueModule,
|
|
33
71
|
StoreModule
|
|
@@ -35,6 +73,8 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
35
73
|
controllers: [HealthController],
|
|
36
74
|
providers: [
|
|
37
75
|
PrismaService,
|
|
76
|
+
{ provide: APP_GUARD, useClass: ThrottlerGuard },
|
|
77
|
+
{ provide: APP_INTERCEPTOR, useClass: RequestLoggingInterceptor },
|
|
38
78
|
{
|
|
39
79
|
provide: APP_INTERCEPTOR,
|
|
40
80
|
useClass: PluginApiInterceptor
|
|
@@ -6,6 +6,8 @@ import { PrismaService } from "../common/prisma.service";
|
|
|
6
6
|
import { MailModule } from "../mail/mail.module";
|
|
7
7
|
import { AuthController } from "./auth.controller";
|
|
8
8
|
import { AuthService } from "./auth.service";
|
|
9
|
+
import { SsoOidcController } from "./sso-oidc.controller";
|
|
10
|
+
import { SsoOidcService } from "./sso-oidc.service";
|
|
9
11
|
|
|
10
12
|
@Module({
|
|
11
13
|
imports: [
|
|
@@ -24,8 +26,8 @@ import { AuthService } from "./auth.service";
|
|
|
24
26
|
}
|
|
25
27
|
})
|
|
26
28
|
],
|
|
27
|
-
controllers: [AuthController],
|
|
28
|
-
providers: [AuthService, PrismaService, AuthGuard],
|
|
29
|
-
exports: [AuthService, AuthGuard]
|
|
29
|
+
controllers: [AuthController, SsoOidcController],
|
|
30
|
+
providers: [AuthService, SsoOidcService, PrismaService, AuthGuard],
|
|
31
|
+
exports: [AuthService, AuthGuard, JwtModule]
|
|
30
32
|
})
|
|
31
33
|
export class AuthModule {}
|
|
@@ -39,7 +39,8 @@ describe("AuthService", () => {
|
|
|
39
39
|
});
|
|
40
40
|
bcryptCompareMock.mockResolvedValue(true);
|
|
41
41
|
|
|
42
|
-
const
|
|
42
|
+
const config = { get: vi.fn().mockReturnValue(undefined) };
|
|
43
|
+
const service = new AuthService(prisma as never, jwt as never, config as never);
|
|
43
44
|
const result = await service.login("openadminjs@proton.me", "password", {}, "admin");
|
|
44
45
|
|
|
45
46
|
expect(result.accessToken).toBe("jwt");
|
|
@@ -59,7 +60,8 @@ describe("AuthService", () => {
|
|
|
59
60
|
});
|
|
60
61
|
bcryptCompareMock.mockResolvedValue(true);
|
|
61
62
|
|
|
62
|
-
const
|
|
63
|
+
const config = { get: vi.fn().mockReturnValue(undefined) };
|
|
64
|
+
const service = new AuthService(prisma as never, jwt as never, config as never);
|
|
63
65
|
await expect(service.login("openadminjs@proton.me", "password", {}, "admin")).rejects.toBeInstanceOf(UnauthorizedException);
|
|
64
66
|
});
|
|
65
67
|
|
|
@@ -69,7 +71,8 @@ describe("AuthService", () => {
|
|
|
69
71
|
prisma.user.findMany.mockResolvedValue([{ id: "u1", refreshTokenHash: "hash-1" }]);
|
|
70
72
|
bcryptCompareMock.mockResolvedValue(false);
|
|
71
73
|
|
|
72
|
-
const
|
|
74
|
+
const config = { get: vi.fn().mockReturnValue(undefined) };
|
|
75
|
+
const service = new AuthService(prisma as never, jwt as never, config as never);
|
|
73
76
|
await expect(service.refresh("bad-token", "admin")).rejects.toBeInstanceOf(UnauthorizedException);
|
|
74
77
|
});
|
|
75
78
|
});
|