openadminjs 0.1.24 → 0.3.0-rc.1
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/README.md +117 -81
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +118 -0
- package/dist/create-project.d.ts +77 -2
- package/dist/create-project.js +685 -224
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +26 -0
- package/dist/doctor.js +232 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +476 -166
- package/dist/render-schema.d.ts +3 -0
- package/dist/render-schema.js +33 -0
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/package.json +39 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +23 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +13 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +138 -0
- package/template/apps/api/src/common/prisma.service.ts +12 -7
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +14 -1
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +8 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -99
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -7
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- package/template/packages/storage/src/index.test.ts +0 -10
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import { BadRequestException, ForbiddenException, HttpException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
2
2
|
import { Prisma } from "@prisma/client";
|
|
3
|
-
import { defaultFileValidation } from "@openadminjs/storage";
|
|
4
|
-
import type { ResourceConfig
|
|
3
|
+
import { defaultFileValidation, LocalStorage } from "@openadminjs/storage";
|
|
4
|
+
import type { ResourceConfig } from "@openadminjs/core";
|
|
5
5
|
import {
|
|
6
6
|
listScopeWhereClause,
|
|
7
7
|
mergeWhereClauses,
|
|
8
8
|
resolveResourceForLocale,
|
|
9
9
|
shouldApplyListScope
|
|
10
10
|
} from "@openadminjs/core";
|
|
11
|
-
import
|
|
12
|
-
import { randomBytes } from "node:crypto";
|
|
13
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
14
|
-
import { dirname, join, relative, resolve } from "node:path";
|
|
11
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
15
12
|
import { PrismaService } from "../common/prisma.service";
|
|
16
13
|
import { pluginRuntime } from "../plugins/plugin-runtime";
|
|
17
14
|
import { getResource, resources } from "../resources/registry";
|
|
@@ -25,7 +22,8 @@ import {
|
|
|
25
22
|
} from "../resources/resource-hooks.runner";
|
|
26
23
|
import { parseWritePayload } from "./validate-resource-payload";
|
|
27
24
|
|
|
28
|
-
|
|
25
|
+
import { isOutOfListScope, has, systemScope, canReadField, safeData, auditSnapshot, sanitizeRecord, type UserContext } from "./resource-policy";
|
|
26
|
+
import { buildWhere, buildOrderBy } from "./resource-query";
|
|
29
27
|
type PrismaDelegate = {
|
|
30
28
|
findMany(args?: unknown): Promise<unknown[]>;
|
|
31
29
|
count(args?: unknown): Promise<number>;
|
|
@@ -41,7 +39,7 @@ export class AdminResourceService {
|
|
|
41
39
|
|
|
42
40
|
listResources(user: UserContext, locale?: string) {
|
|
43
41
|
return resources
|
|
44
|
-
.filter((resource) =>
|
|
42
|
+
.filter((resource) => has(user, resource.permissions.read))
|
|
45
43
|
.map((resource) => {
|
|
46
44
|
const view = resolveResourceForLocale(resource, locale);
|
|
47
45
|
return {
|
|
@@ -50,8 +48,8 @@ export class AdminResourceService {
|
|
|
50
48
|
icon: view.icon,
|
|
51
49
|
titleField: view.titleField,
|
|
52
50
|
permissions: view.permissions,
|
|
53
|
-
fields: view.fields,
|
|
54
|
-
actions: view.actions,
|
|
51
|
+
fields: Object.fromEntries(Object.entries(view.fields).filter(([name]) => canReadField(resource, name, user)).map(([name, field]) => [name, { ...field, create: field.create !== false && (!field.permissions?.create || has(user, field.permissions.create)), edit: field.edit !== false && (!field.permissions?.update || has(user, field.permissions.update)) }])),
|
|
52
|
+
actions: Object.fromEntries(Object.entries(view.actions ?? {}).filter(([,action])=>has(user,action.permission)).map(([name,{handler,...config}])=>[name,config])),
|
|
55
53
|
i18n: view.i18n,
|
|
56
54
|
seo: view.seo
|
|
57
55
|
};
|
|
@@ -65,30 +63,32 @@ export class AdminResourceService {
|
|
|
65
63
|
): Promise<Array<{ resource: string; resourceLabel: string; id: string; title: string }>> {
|
|
66
64
|
const q = query.trim();
|
|
67
65
|
if (q.length < 2) return [];
|
|
68
|
-
const
|
|
66
|
+
const requestedLimit = opts?.perResourceLimit ?? 5;
|
|
67
|
+
if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1) throw new BadRequestException("Invalid search limit");
|
|
68
|
+
const perResourceLimit = Math.min(requestedLimit, 20);
|
|
69
69
|
const whitelist = opts?.resources ? new Set(opts.resources.map((v) => v.toLowerCase())) : null;
|
|
70
70
|
const out: Array<{ resource: string; resourceLabel: string; id: string; title: string }> = [];
|
|
71
71
|
|
|
72
72
|
for (const resource of resources) {
|
|
73
73
|
if (whitelist && !whitelist.has(resource.name.toLowerCase())) continue;
|
|
74
|
-
if (!
|
|
75
|
-
const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable).map(([name]) => name);
|
|
74
|
+
if (!has(user, resource.permissions.read)) continue;
|
|
75
|
+
const searchable = Object.entries(resource.fields).filter(([name, f]) => f.searchable && canReadField(resource, name, user)).map(([name]) => name);
|
|
76
76
|
if (!searchable.length) continue;
|
|
77
77
|
|
|
78
78
|
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
79
79
|
const where = mergeWhereClauses(
|
|
80
80
|
{
|
|
81
|
-
OR: searchable.map((field) => ({ [field]: { contains: q, mode: "insensitive" } }))
|
|
81
|
+
OR: searchable.map((field) => ({ [field]: { contains: q, ...(/^(postgres|postgresql):/.test(process.env.DATABASE_URL ?? "postgresql:") ? { mode: "insensitive" } : {}) } }))
|
|
82
82
|
},
|
|
83
|
-
scope
|
|
83
|
+
mergeWhereClauses(scope, systemScope(resource))
|
|
84
84
|
);
|
|
85
85
|
const rows = await this.delegate(resource).findMany({
|
|
86
86
|
where,
|
|
87
87
|
take: perResourceLimit,
|
|
88
|
-
orderBy:
|
|
88
|
+
orderBy: buildOrderBy(resource, "createdAt:desc", user)
|
|
89
89
|
});
|
|
90
90
|
for (const row of rows) {
|
|
91
|
-
const safe =
|
|
91
|
+
const safe = sanitizeRecord(resource, row, user) as Record<string, unknown>;
|
|
92
92
|
const id = String(safe.id ?? "");
|
|
93
93
|
if (!id) continue;
|
|
94
94
|
const tf = resource.titleField ?? "id";
|
|
@@ -104,73 +104,71 @@ export class AdminResourceService {
|
|
|
104
104
|
const resource = this.authorizedResource(name, user, "read");
|
|
105
105
|
const delegate = this.delegate(resource);
|
|
106
106
|
const page = Number(query.page ?? 1);
|
|
107
|
-
const
|
|
108
|
-
|
|
107
|
+
const requestedLimit = Number(query.limit ?? 20);
|
|
108
|
+
if (!Number.isSafeInteger(page) || page < 1 || !Number.isSafeInteger(requestedLimit) || requestedLimit < 1) throw new BadRequestException({ message: "Invalid pagination", code: "PAGINATION_INVALID" });
|
|
109
|
+
const limit = Math.min(requestedLimit, 100);
|
|
110
|
+
if (!Number.isSafeInteger((page - 1) * limit)) throw new BadRequestException("Invalid pagination offset");
|
|
111
|
+
const baseWhere = buildWhere(resource, query, user);
|
|
109
112
|
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
110
|
-
const where = mergeWhereClauses(baseWhere, scope);
|
|
111
|
-
const orderBy =
|
|
113
|
+
const where = mergeWhereClauses(baseWhere, mergeWhereClauses(scope, systemScope(resource)));
|
|
114
|
+
const orderBy = buildOrderBy(resource, String(query.sort ?? "createdAt:desc"), user);
|
|
112
115
|
const [data, total] = await Promise.all([
|
|
113
116
|
delegate.findMany({ where, orderBy, skip: (page - 1) * limit, take: limit }),
|
|
114
117
|
delegate.count({ where })
|
|
115
118
|
]);
|
|
116
|
-
return { data: data.map((row) =>
|
|
119
|
+
return { data: data.map((row) => sanitizeRecord(resource, row, user)), meta: { page, limit, total, pages: Math.ceil(total / limit) || 1 } };
|
|
117
120
|
}
|
|
118
121
|
|
|
119
122
|
async get(name: string, id: string, user: UserContext) {
|
|
120
123
|
const resource = this.authorizedResource(name, user, "read");
|
|
121
124
|
const record = await this.delegate(resource).findUnique({ where: { id } });
|
|
122
125
|
if (!record) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
123
|
-
if (
|
|
126
|
+
if (isOutOfListScope(resource, user, record)) {
|
|
124
127
|
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
125
128
|
}
|
|
126
|
-
return
|
|
129
|
+
return sanitizeRecord(resource, record, user);
|
|
127
130
|
}
|
|
128
131
|
|
|
129
132
|
async create(name: string, data: Record<string, unknown>, user: UserContext) {
|
|
133
|
+
if (name === "files") throw new ForbiddenException("Use the dedicated upload endpoint");
|
|
134
|
+
return this.createRecord(name, data, user);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async createRecord(name: string, data: Record<string, unknown>, user: UserContext) {
|
|
130
138
|
const resource = this.authorizedResource(name, user, "create");
|
|
131
139
|
|
|
132
140
|
if (name === "api-tokens") {
|
|
133
|
-
const
|
|
134
|
-
const scopes =
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
userId: user.id,
|
|
143
|
-
tokenHash: await bcrypt.hash(rawToken, 12)
|
|
144
|
-
}
|
|
145
|
-
});
|
|
146
|
-
const safeRecord = this.sanitizeRecord(resource, created) as Record<string, unknown>;
|
|
147
|
-
await tx.auditLog.create({
|
|
148
|
-
data: { userId: user.id, resource: name, resourceId: (created as { id?: string }).id, action: "create", before: Prisma.JsonNull, after: safeRecord as object }
|
|
149
|
-
});
|
|
150
|
-
return created;
|
|
141
|
+
const label = typeof data.name === "string" ? data.name.trim() : "";
|
|
142
|
+
const scopes = Array.isArray(data.scopes) ? [...new Set(data.scopes)] : [];
|
|
143
|
+
const allowed = new Set(resources.filter(r => !["api-tokens","settings","audit-logs","users","job-logs","webhook-logs"].includes(r.name) && has(user,r.permissions.read)).map(r=>r.permissions.read));
|
|
144
|
+
if (!label || label.length > 120 || !scopes.length || scopes.length > 50 || !scopes.every(s=>typeof s==="string" && allowed.has(s))) throw new BadRequestException("Choose explicit permitted resource read scopes");
|
|
145
|
+
const plainToken = "oajs_" + randomBytes(32).toString("base64url");
|
|
146
|
+
const created = await this.prisma.$transaction(async tx => {
|
|
147
|
+
const record = await tx.apiToken.create({data:{name:label, scopes:scopes as string[], userId:user.id, tokenHash:createHash("sha256").update(plainToken).digest("hex")}});
|
|
148
|
+
await tx.auditLog.create({data:{userId:user.id,resource:name,resourceId:record.id,action:"create"}});
|
|
149
|
+
return record;
|
|
151
150
|
});
|
|
152
|
-
|
|
153
|
-
return { ...safeRecord, plainToken: rawToken };
|
|
151
|
+
return {...sanitizeRecord(resource,created,user) as object,plainToken};
|
|
154
152
|
}
|
|
155
153
|
|
|
156
|
-
const payload =
|
|
157
|
-
if (name === "notifications") payload.userId = String(data.userId ?? user.id);
|
|
154
|
+
const payload = safeData(resource, data, "create", user);
|
|
158
155
|
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
159
156
|
await runBeforeCreate(name, resource, hookUser, this.prisma, payload);
|
|
160
|
-
const validated = parseWritePayload(resource, "create", payload);
|
|
157
|
+
const validated = parseWritePayload(resource, "create", safeData(resource, payload, "create", user));
|
|
158
|
+
if (name === "notifications") validated.userId = user.id;
|
|
161
159
|
|
|
162
160
|
const record = await this.prisma.$transaction(async (tx) => {
|
|
163
161
|
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
164
162
|
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
165
163
|
const created = await txDelegate.create({ data: validated });
|
|
166
164
|
await tx.auditLog.create({
|
|
167
|
-
data: { userId: user.id, resource: name, resourceId: (created as { id?: string }).id, action: "create", before: Prisma.JsonNull, after: created as object }
|
|
165
|
+
data: { userId: user.id, resource: name, resourceId: (created as { id?: string }).id, action: "create", before: Prisma.JsonNull, after: auditSnapshot(resource, created) as object }
|
|
168
166
|
});
|
|
169
167
|
return created;
|
|
170
168
|
});
|
|
171
169
|
|
|
172
170
|
await runAfterCreate(name, resource, hookUser, this.prisma, payload, record);
|
|
173
|
-
return
|
|
171
|
+
return sanitizeRecord(resource, record, user);
|
|
174
172
|
}
|
|
175
173
|
|
|
176
174
|
async update(name: string, id: string, data: Record<string, unknown>, user: UserContext) {
|
|
@@ -178,26 +176,27 @@ export class AdminResourceService {
|
|
|
178
176
|
const delegate = this.delegate(resource);
|
|
179
177
|
const before = await delegate.findUnique({ where: { id } });
|
|
180
178
|
if (!before) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
181
|
-
if (
|
|
179
|
+
if (isOutOfListScope(resource, user, before)) {
|
|
182
180
|
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
183
181
|
}
|
|
184
|
-
const payload =
|
|
182
|
+
const payload = safeData(resource, data, "edit", user);
|
|
185
183
|
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
186
184
|
await runBeforeUpdate(name, resource, hookUser, this.prisma, id, payload);
|
|
187
|
-
const validated = parseWritePayload(resource, "edit", payload);
|
|
185
|
+
const validated = parseWritePayload(resource, "edit", safeData(resource, payload, "edit", user));
|
|
186
|
+
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
188
187
|
|
|
189
188
|
const record = await this.prisma.$transaction(async (tx) => {
|
|
190
189
|
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
191
190
|
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
192
|
-
const updated = await txDelegate.update({ where: { id }, data: validated });
|
|
191
|
+
const updated = await txDelegate.update({ where: { id, ...(scope ?? {}), ...(systemScope(resource) ?? {}) }, data: validated });
|
|
193
192
|
await tx.auditLog.create({
|
|
194
|
-
data: { userId: user.id, resource: name, resourceId: id, action: "update", before: before as object, after: updated as object }
|
|
193
|
+
data: { userId: user.id, resource: name, resourceId: id, action: "update", before: auditSnapshot(resource, before) as object, after: auditSnapshot(resource, updated) as object }
|
|
195
194
|
});
|
|
196
195
|
return updated;
|
|
197
196
|
});
|
|
198
197
|
|
|
199
198
|
await runAfterUpdate(name, resource, hookUser, this.prisma, id, payload, before, record);
|
|
200
|
-
return
|
|
199
|
+
return sanitizeRecord(resource, record, user);
|
|
201
200
|
}
|
|
202
201
|
|
|
203
202
|
async delete(name: string, id: string, user: UserContext) {
|
|
@@ -205,7 +204,7 @@ export class AdminResourceService {
|
|
|
205
204
|
const delegate = this.delegate(resource);
|
|
206
205
|
const before = await delegate.findUnique({ where: { id } });
|
|
207
206
|
if (!before) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
208
|
-
if (
|
|
207
|
+
if (isOutOfListScope(resource, user, before)) {
|
|
209
208
|
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
210
209
|
}
|
|
211
210
|
const hookUser = { id: user.id, email: user.email ?? "", permissions: user.permissions };
|
|
@@ -214,26 +213,31 @@ export class AdminResourceService {
|
|
|
214
213
|
await this.prisma.$transaction(async (tx) => {
|
|
215
214
|
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
216
215
|
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
217
|
-
|
|
216
|
+
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
217
|
+
await txDelegate.delete({ where: { id, ...(scope ?? {}), ...(systemScope(resource) ?? {}) } });
|
|
218
218
|
await tx.auditLog.create({
|
|
219
|
-
data: { userId: user.id, resource: name, resourceId: id, action: "delete", before: before as object, after: Prisma.JsonNull }
|
|
219
|
+
data: { userId: user.id, resource: name, resourceId: id, action: "delete", before: auditSnapshot(resource, before) as object, after: Prisma.JsonNull }
|
|
220
220
|
});
|
|
221
221
|
});
|
|
222
222
|
|
|
223
|
+
if (name === "files") {
|
|
224
|
+
const path = String((before as Record<string,unknown>).path ?? "");
|
|
225
|
+
await new LocalStorage().delete(path).catch(() => console.warn("Storage cleanup requires operator review", id));
|
|
226
|
+
}
|
|
223
227
|
await runAfterDelete(name, resource, hookUser, this.prisma, id);
|
|
224
228
|
return { ok: true };
|
|
225
229
|
}
|
|
226
230
|
|
|
227
231
|
async action(name: string, id: string, action: string, user: UserContext, input?: unknown) {
|
|
228
|
-
const resource =
|
|
229
|
-
const config = resource
|
|
232
|
+
const resource = this.authorizedResource(name,user,"read");
|
|
233
|
+
const config = resource.actions?.[action];
|
|
230
234
|
if (!resource || !config) throw new NotFoundException({ message: "Action not found", code: "ACTION_NOT_FOUND" });
|
|
231
|
-
if (!
|
|
235
|
+
if (!has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
232
236
|
|
|
233
237
|
if (config.handler) {
|
|
234
238
|
const existing = await this.delegate(resource).findUnique({ where: { id } });
|
|
235
239
|
if (!existing) throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
236
|
-
if (
|
|
240
|
+
if (isOutOfListScope(resource, user, existing)) {
|
|
237
241
|
throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
|
|
238
242
|
}
|
|
239
243
|
const result = await config.handler({
|
|
@@ -242,8 +246,8 @@ export class AdminResourceService {
|
|
|
242
246
|
user: { id: user.id, email: user.email ?? "", permissions: user.permissions },
|
|
243
247
|
input
|
|
244
248
|
});
|
|
245
|
-
await this.audit(user.id, name, id, action, existing, result);
|
|
246
|
-
return
|
|
249
|
+
await this.audit(user.id, name, id, action, auditSnapshot(resource, existing), auditSnapshot(resource, result));
|
|
250
|
+
return sanitizeRecord(resource, result, user);
|
|
247
251
|
}
|
|
248
252
|
|
|
249
253
|
throw new NotFoundException({ message: "Action not implemented for this resource", code: "ACTION_NOT_IMPLEMENTED" });
|
|
@@ -260,6 +264,7 @@ export class AdminResourceService {
|
|
|
260
264
|
const failures: { id: string; message: string }[] = [];
|
|
261
265
|
let ok = 0;
|
|
262
266
|
|
|
267
|
+
if (uniqueIds.length > 100) throw new BadRequestException("Bulk limit is 100");
|
|
263
268
|
if (dto.action === "delete") {
|
|
264
269
|
this.authorizedResource(name, user, "delete");
|
|
265
270
|
for (const id of uniqueIds) {
|
|
@@ -278,7 +283,7 @@ export class AdminResourceService {
|
|
|
278
283
|
if (!resource || !config?.handler) {
|
|
279
284
|
throw new NotFoundException({ message: "Action not found", code: "ACTION_NOT_FOUND" });
|
|
280
285
|
}
|
|
281
|
-
if (!
|
|
286
|
+
if (!has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
282
287
|
|
|
283
288
|
for (const id of uniqueIds) {
|
|
284
289
|
try {
|
|
@@ -294,11 +299,11 @@ export class AdminResourceService {
|
|
|
294
299
|
async reorder(name: string, orderedIds: string[], user: UserContext, baseIndex = 0): Promise<{ ok: true }> {
|
|
295
300
|
const resource = this.authorizedResource(name, user, "update");
|
|
296
301
|
const orderField = resource.fields.order;
|
|
297
|
-
if (!orderField || orderField.type !== "number" || orderField.edit === false) {
|
|
302
|
+
if (!orderField || orderField.type !== "number" || orderField.edit === false || (orderField.permissions?.update && !has(user,orderField.permissions.update))) {
|
|
298
303
|
throw new BadRequestException({ message: "Resource does not support drag-and-drop ordering", code: "REORDER_UNSUPPORTED" });
|
|
299
304
|
}
|
|
300
305
|
const uniqueIds = [...new Set(orderedIds.map(String).filter(Boolean))];
|
|
301
|
-
if (!uniqueIds.length) throw new BadRequestException({ message: "
|
|
306
|
+
if (!uniqueIds.length || uniqueIds.length > 100 || !Number.isSafeInteger(baseIndex) || baseIndex < 0 || baseIndex + uniqueIds.length > 2147483647) throw new BadRequestException({ message: "Invalid reorder request", code: "REORDER_INVALID" });
|
|
302
307
|
|
|
303
308
|
const delegate = this.delegate(resource);
|
|
304
309
|
const rows = await delegate.findMany({ where: { id: { in: uniqueIds } } });
|
|
@@ -306,7 +311,7 @@ export class AdminResourceService {
|
|
|
306
311
|
throw new BadRequestException({ message: "One or more records were not found", code: "REORDER_IDS_INVALID" });
|
|
307
312
|
}
|
|
308
313
|
for (const row of rows) {
|
|
309
|
-
if (
|
|
314
|
+
if (isOutOfListScope(resource, user, row)) {
|
|
310
315
|
throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
311
316
|
}
|
|
312
317
|
}
|
|
@@ -316,13 +321,11 @@ export class AdminResourceService {
|
|
|
316
321
|
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
317
322
|
for (let i = 0; i < uniqueIds.length; i++) {
|
|
318
323
|
await txDelegate.update({
|
|
319
|
-
where: { id: uniqueIds[i] },
|
|
324
|
+
where: { id: uniqueIds[i], ...(shouldApplyListScope(resource,user.permissions)?listScopeWhereClause(resource,user.id):{}) },
|
|
320
325
|
data: { order: baseIndex + i }
|
|
321
326
|
});
|
|
322
327
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
await this.prisma.auditLog.create({
|
|
328
|
+
await tx.auditLog.create({
|
|
326
329
|
data: {
|
|
327
330
|
userId: user.id,
|
|
328
331
|
resource: name,
|
|
@@ -332,6 +335,7 @@ export class AdminResourceService {
|
|
|
332
335
|
after: { ids: uniqueIds, baseIndex, order: uniqueIds.map((id, index) => ({ id, order: baseIndex + index })) } as object
|
|
333
336
|
}
|
|
334
337
|
});
|
|
338
|
+
});
|
|
335
339
|
|
|
336
340
|
return { ok: true };
|
|
337
341
|
}
|
|
@@ -340,7 +344,8 @@ export class AdminResourceService {
|
|
|
340
344
|
input: { filename: string; mimeType: string; contentBase64: string; targetPath?: string },
|
|
341
345
|
user: UserContext
|
|
342
346
|
): Promise<Record<string, unknown>> {
|
|
343
|
-
|
|
347
|
+
this.authorizedResource("files", user, "create");
|
|
348
|
+
if (input.targetPath !== undefined) throw new BadRequestException({ message: "Custom upload paths are not allowed", code: "UPLOAD_PATH_INVALID" });
|
|
344
349
|
const filename = String(input.filename ?? "").trim();
|
|
345
350
|
const mimeType = String(input.mimeType ?? "").trim().toLowerCase();
|
|
346
351
|
const rawBase64 = String(input.contentBase64 ?? "").trim();
|
|
@@ -351,6 +356,7 @@ export class AdminResourceService {
|
|
|
351
356
|
throw new BadRequestException({ message: "MIME type is not allowed", code: "UPLOAD_MIME_DENIED" });
|
|
352
357
|
}
|
|
353
358
|
|
|
359
|
+
if (rawBase64.length > Math.ceil(defaultFileValidation.maxSizeBytes / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(rawBase64) || rawBase64.length % 4 !== 0) throw new BadRequestException("Invalid or oversized base64");
|
|
354
360
|
let contentBase64 = rawBase64;
|
|
355
361
|
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
356
362
|
await mediaHook.beforeStore?.({
|
|
@@ -376,18 +382,23 @@ export class AdminResourceService {
|
|
|
376
382
|
throw new BadRequestException({ message: "File is too large", code: "UPLOAD_TOO_LARGE" });
|
|
377
383
|
}
|
|
378
384
|
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
385
|
+
const signatures: Record<string, (buffer: Buffer) => boolean> = {
|
|
386
|
+
"image/png": b => b.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])),
|
|
387
|
+
"image/jpeg": b => b[0] === 255 && b[1] === 216 && b[2] === 255,
|
|
388
|
+
"image/webp": b => b.toString("ascii", 0, 4) === "RIFF" && b.toString("ascii", 8, 12) === "WEBP",
|
|
389
|
+
"application/pdf": b => b.toString("ascii", 0, 5) === "%PDF-",
|
|
390
|
+
"text/plain": b => !b.includes(0)
|
|
391
|
+
};
|
|
392
|
+
if (!signatures[mimeType]?.(fileBuffer)) throw new BadRequestException("File content does not match MIME type");
|
|
393
|
+
const storage = new LocalStorage();
|
|
394
|
+
const stored = await storage.put(fileBuffer,{filename,path:"",mimeType,size:fileBuffer.length});
|
|
395
|
+
let record: unknown;
|
|
396
|
+
try {
|
|
397
|
+
record = await this.createRecord("files", stored, user);
|
|
398
|
+
} catch (error) {
|
|
399
|
+
await storage.delete(stored.path).catch(()=>undefined);
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
391
402
|
|
|
392
403
|
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
393
404
|
await mediaHook.afterStore?.({
|
|
@@ -402,24 +413,14 @@ export class AdminResourceService {
|
|
|
402
413
|
return record as Record<string, unknown>;
|
|
403
414
|
}
|
|
404
415
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
const
|
|
410
|
-
if (
|
|
411
|
-
|
|
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, "/");
|
|
416
|
+
async downloadFile(id: string, user: UserContext) {
|
|
417
|
+
this.authorizedResource("files", user, "read");
|
|
418
|
+
const file = await this.prisma.fileAsset.findUnique({where:{id}});
|
|
419
|
+
if (!file) throw new NotFoundException("File not found");
|
|
420
|
+
const resource = this.authorizedResource("files",user,"read");
|
|
421
|
+
if (isOutOfListScope(resource,user,file)) throw new NotFoundException("File not found");
|
|
422
|
+
try { return {filename:file.filename, bytes:await new LocalStorage().read(file.path)}; }
|
|
423
|
+
catch { throw new NotFoundException("File unavailable"); }
|
|
423
424
|
}
|
|
424
425
|
|
|
425
426
|
private bulkErrorMessage(err: unknown): string {
|
|
@@ -437,22 +438,11 @@ export class AdminResourceService {
|
|
|
437
438
|
return "Request failed";
|
|
438
439
|
}
|
|
439
440
|
|
|
440
|
-
private isOutOfListScope(resource: ResourceConfig, user: UserContext, record: unknown): boolean {
|
|
441
|
-
if (!shouldApplyListScope(resource, user.permissions)) return false;
|
|
442
|
-
const clause = listScopeWhereClause(resource, user.id);
|
|
443
|
-
if (!clause) return false;
|
|
444
|
-
const row = record as Record<string, unknown>;
|
|
445
|
-
for (const [key, expected] of Object.entries(clause)) {
|
|
446
|
-
if (row[key] !== expected) return true;
|
|
447
|
-
}
|
|
448
|
-
return false;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
441
|
private authorizedResource(name: string, user: UserContext, action: keyof ResourceConfig["permissions"]) {
|
|
452
442
|
const resource = getResource(name);
|
|
453
443
|
if (!resource) throw new NotFoundException({ message: "Resource not found", code: "RESOURCE_NOT_FOUND" });
|
|
454
444
|
const permission = resource.permissions[action];
|
|
455
|
-
if (!permission || !
|
|
445
|
+
if (!permission || !has(user, permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
456
446
|
return resource;
|
|
457
447
|
}
|
|
458
448
|
|
|
@@ -462,145 +452,6 @@ export class AdminResourceService {
|
|
|
462
452
|
return delegate;
|
|
463
453
|
}
|
|
464
454
|
|
|
465
|
-
private has(user: UserContext, permission?: string) {
|
|
466
|
-
return Boolean(permission && (user.permissions.includes(permission) || user.permissions.includes("*")));
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
private safeData(resource: ResourceConfig, data: Record<string, unknown>, mode: "create" | "edit") {
|
|
470
|
-
return Object.fromEntries(
|
|
471
|
-
Object.entries(data).filter(([name]) => {
|
|
472
|
-
const field = resource.fields[name];
|
|
473
|
-
return field && field[mode] !== false && !field.sensitive && field.type !== "id";
|
|
474
|
-
})
|
|
475
|
-
);
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
private sanitizeRecord(resource: ResourceConfig, record: unknown) {
|
|
479
|
-
if (!record || typeof record !== "object") return record;
|
|
480
|
-
const hiddenFields = Object.entries(resource.fields)
|
|
481
|
-
.filter(([, field]) => field.type === "hidden" || field.sensitive)
|
|
482
|
-
.map(([name]) => name);
|
|
483
|
-
const copy = { ...(record as Record<string, unknown>) };
|
|
484
|
-
for (const hidden of hiddenFields) delete copy[hidden];
|
|
485
|
-
return copy;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
private normalizeScopes(input: unknown): string[] {
|
|
489
|
-
if (Array.isArray(input)) return input.map((item) => String(item));
|
|
490
|
-
if (typeof input === "string") {
|
|
491
|
-
try {
|
|
492
|
-
const parsed = JSON.parse(input);
|
|
493
|
-
if (Array.isArray(parsed)) return parsed.map((item) => String(item));
|
|
494
|
-
} catch {
|
|
495
|
-
return input
|
|
496
|
-
.split(",")
|
|
497
|
-
.map((item) => item.trim())
|
|
498
|
-
.filter(Boolean);
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
return ["*"];
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
private buildWhere(resource: ResourceConfig, query: Record<string, unknown>) {
|
|
505
|
-
const clauses: Record<string, unknown>[] = [];
|
|
506
|
-
if (query.search) {
|
|
507
|
-
const searchable = Object.entries(resource.fields).filter(([, field]) => field.searchable);
|
|
508
|
-
clauses.push({ OR: searchable.map(([field]) => ({ [field]: { contains: String(query.search), mode: "insensitive" } })) });
|
|
509
|
-
}
|
|
510
|
-
for (const [key, value] of Object.entries(query)) {
|
|
511
|
-
const opMatch = key.match(/^filter\[([^\]]+)]\[(\w+)]$/);
|
|
512
|
-
if (opMatch?.[1] && opMatch[2]) {
|
|
513
|
-
const clause = this.buildOperatorClause(resource, opMatch[1], opMatch[2], value);
|
|
514
|
-
if (clause) clauses.push(clause);
|
|
515
|
-
continue;
|
|
516
|
-
}
|
|
517
|
-
const legacy = key.match(/^filter\[([^\]]+)]$/);
|
|
518
|
-
if (legacy?.[1]) {
|
|
519
|
-
const clause = this.buildOperatorClause(resource, legacy[1], "eq", value);
|
|
520
|
-
if (clause) clauses.push(clause);
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
return clauses.length ? { AND: clauses } : undefined;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
private buildOperatorClause(resource: ResourceConfig, fieldName: string, op: string, raw: unknown): Record<string, unknown> | null {
|
|
527
|
-
const field = resource.fields[fieldName];
|
|
528
|
-
if (!field?.filterable) {
|
|
529
|
-
throw new BadRequestException({ message: `Field "${fieldName}" is not filterable`, code: "FILTER_NOT_ALLOWED" });
|
|
530
|
-
}
|
|
531
|
-
const str = raw == null ? "" : String(raw);
|
|
532
|
-
switch (op) {
|
|
533
|
-
case "eq":
|
|
534
|
-
return { [fieldName]: this.coerceFilterScalar(field, str) };
|
|
535
|
-
case "ne":
|
|
536
|
-
return { [fieldName]: { not: this.coerceFilterScalar(field, str) } };
|
|
537
|
-
case "in": {
|
|
538
|
-
const parts = str
|
|
539
|
-
.split(",")
|
|
540
|
-
.map((s) => s.trim())
|
|
541
|
-
.filter(Boolean)
|
|
542
|
-
.map((p) => this.coerceFilterScalar(field, p));
|
|
543
|
-
return { [fieldName]: { in: parts } };
|
|
544
|
-
}
|
|
545
|
-
case "gt":
|
|
546
|
-
return { [fieldName]: { gt: this.coerceFilterComparable(field, str) } };
|
|
547
|
-
case "gte":
|
|
548
|
-
return { [fieldName]: { gte: this.coerceFilterComparable(field, str) } };
|
|
549
|
-
case "lt":
|
|
550
|
-
return { [fieldName]: { lt: this.coerceFilterComparable(field, str) } };
|
|
551
|
-
case "lte":
|
|
552
|
-
return { [fieldName]: { lte: this.coerceFilterComparable(field, str) } };
|
|
553
|
-
case "contains": {
|
|
554
|
-
if (!this.isStringFilterField(field)) {
|
|
555
|
-
throw new BadRequestException({ message: `Operator "contains" is only for string-like fields`, code: "FILTER_OP_INVALID" });
|
|
556
|
-
}
|
|
557
|
-
return { [fieldName]: { contains: str, mode: "insensitive" } };
|
|
558
|
-
}
|
|
559
|
-
default:
|
|
560
|
-
throw new BadRequestException({ message: `Unknown filter operator "${op}"`, code: "FILTER_OP_UNKNOWN" });
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
private isStringFilterField(field: ResourceField): boolean {
|
|
565
|
-
return ["text", "textarea", "email", "url", "slug", "markdown", "code", "richtext", "badge", "select"].includes(field.type);
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
private coerceFilterScalar(field: ResourceField, value: string): string | number | boolean {
|
|
569
|
-
if (field.type === "number" || field.type === "money") {
|
|
570
|
-
const n = Number(value);
|
|
571
|
-
if (Number.isNaN(n)) {
|
|
572
|
-
throw new BadRequestException({ message: `Invalid number for filter`, code: "FILTER_VALUE_INVALID" });
|
|
573
|
-
}
|
|
574
|
-
return n;
|
|
575
|
-
}
|
|
576
|
-
if (field.type === "boolean") return value === "true" || value === "1";
|
|
577
|
-
return value;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
private coerceFilterComparable(field: ResourceField, value: string): Date | number | string | boolean {
|
|
581
|
-
if (field.type === "datetime" || field.type === "date") {
|
|
582
|
-
const d = new Date(value);
|
|
583
|
-
if (Number.isNaN(d.getTime())) {
|
|
584
|
-
throw new BadRequestException({ message: `Invalid date for filter`, code: "FILTER_VALUE_INVALID" });
|
|
585
|
-
}
|
|
586
|
-
return d;
|
|
587
|
-
}
|
|
588
|
-
return this.coerceFilterScalar(field, value);
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
private buildOrderBy(resource: ResourceConfig, sort: string) {
|
|
592
|
-
const [field, dirRaw] = sort.split(":");
|
|
593
|
-
const direction = dirRaw === "asc" ? "asc" : "desc";
|
|
594
|
-
const candidate = field ? resource.fields[field] : undefined;
|
|
595
|
-
if (field && candidate?.sortable) {
|
|
596
|
-
return { [field]: direction };
|
|
597
|
-
}
|
|
598
|
-
if (resource.fields.createdAt?.sortable) {
|
|
599
|
-
return { createdAt: direction };
|
|
600
|
-
}
|
|
601
|
-
return undefined;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
455
|
/** Write an audit log entry outside a transaction (used by the action handler). */
|
|
605
456
|
private audit(userId: string, resource: string, resourceId: string | undefined, action: string, before: unknown, after: unknown) {
|
|
606
457
|
return this.prisma.auditLog.create({ data: { userId, resource, resourceId, action, before: before as object, after: after as object } });
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { Body, Controller, Delete, Get, Inject, Optional, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
|
|
1
|
+
import { Body, Controller, Delete, ForbiddenException, Get, Inject, Optional, Param, Patch, Post, Query, Res, UseGuards } from "@nestjs/common";
|
|
2
|
+
import type { Response } from "express";
|
|
2
3
|
import { AuthGuard } from "../common/auth.guard";
|
|
3
4
|
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
4
5
|
import { CurrentUser } from "../common/current-user.decorator";
|
|
@@ -68,6 +69,17 @@ export class AdminController {
|
|
|
68
69
|
return this.resources.uploadFile(body, user);
|
|
69
70
|
}
|
|
70
71
|
|
|
72
|
+
@Get("files/:id/download")
|
|
73
|
+
async download(@Param("id") id:string,@CurrentUser() user:UserContext,@Res() res:Response) {
|
|
74
|
+
const file=await this.resources.downloadFile(id,user);
|
|
75
|
+
const name=encodeURIComponent(file.filename).replace(/['()*]/g,c=>"%"+c.charCodeAt(0).toString(16));
|
|
76
|
+
res.setHeader("Content-Disposition","attachment; filename*=UTF-8''"+name);
|
|
77
|
+
res.setHeader("Content-Type","application/octet-stream");
|
|
78
|
+
res.setHeader("Cache-Control","no-store");
|
|
79
|
+
res.setHeader("X-Content-Type-Options","nosniff");
|
|
80
|
+
res.send(file.bytes);
|
|
81
|
+
}
|
|
82
|
+
|
|
71
83
|
@Get(":resource/:id")
|
|
72
84
|
get(@Param("resource") resource: string, @Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
73
85
|
return this.resources.get(resource, id, user);
|
|
@@ -89,9 +101,10 @@ export class AdminController {
|
|
|
89
101
|
}
|
|
90
102
|
|
|
91
103
|
@Post("orders/:id/refund")
|
|
92
|
-
refundOrder(@Param("id") id: string) {
|
|
93
|
-
if (!
|
|
94
|
-
|
|
104
|
+
refundOrder(@Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
105
|
+
if (!user.permissions.includes("orders.refund") && !user.permissions.includes("*")) throw new ForbiddenException("Missing permission");
|
|
106
|
+
if (!this.payments) throw new ForbiddenException("Payments unavailable");
|
|
107
|
+
return this.payments.refundOrder(id,user.id);
|
|
95
108
|
}
|
|
96
109
|
|
|
97
110
|
@Post(":resource/:id/actions/:action")
|