openadminjs 0.2.0 → 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.
Files changed (219) hide show
  1. package/README.md +106 -151
  2. package/dist/adapt-package-manager.js +4 -1
  3. package/dist/create-project.d.ts +46 -0
  4. package/dist/create-project.js +417 -150
  5. package/dist/doctor.d.ts +13 -0
  6. package/dist/doctor.js +35 -6
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +257 -39
  9. package/dist/render-schema.d.ts +0 -17
  10. package/dist/render-schema.js +25 -29
  11. package/dist/resource-slug.d.ts +1 -0
  12. package/dist/resource-slug.js +7 -0
  13. package/dist/runtime-mode.d.ts +16 -0
  14. package/dist/runtime-mode.js +138 -0
  15. package/dist/upgrade.d.ts +10 -0
  16. package/dist/upgrade.js +133 -0
  17. package/package.json +14 -11
  18. package/template/.dockerignore +15 -0
  19. package/template/.env.production.example +5 -0
  20. package/template/Dockerfile +12 -0
  21. package/template/README.md +4 -3
  22. package/template/apps/admin/app/api/auth/login/route.ts +9 -9
  23. package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
  24. package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
  25. package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
  26. package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
  27. package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
  28. package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
  29. package/template/apps/admin/app/api-tokens/page.tsx +39 -39
  30. package/template/apps/admin/app/assistant/page.tsx +11 -0
  31. package/template/apps/admin/app/dashboard/page.tsx +45 -462
  32. package/template/apps/admin/app/globals.css +52 -16
  33. package/template/apps/admin/app/layout.tsx +1 -1
  34. package/template/apps/admin/app/login/page.tsx +13 -145
  35. package/template/apps/admin/app/plugins/page.tsx +16 -402
  36. package/template/apps/admin/app/profile/page.tsx +5 -2
  37. package/template/apps/admin/app/settings/page.tsx +14 -265
  38. package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
  39. package/template/apps/admin/components/app-shell.tsx +25 -373
  40. package/template/apps/admin/components/auth-guard.tsx +8 -28
  41. package/template/apps/admin/components/logo.tsx +1 -30
  42. package/template/apps/admin/components/resource-form.tsx +3 -3
  43. package/template/apps/admin/components/resource-table.tsx +12 -8
  44. package/template/apps/admin/lib/api.ts +45 -107
  45. package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
  46. package/template/apps/admin/lib/server-api.ts +7 -0
  47. package/template/apps/admin/lib/tokens.ts +9 -81
  48. package/template/apps/admin/middleware.ts +9 -50
  49. package/template/apps/admin/next.config.mjs +4 -0
  50. package/template/apps/admin/package.json +2 -1
  51. package/template/apps/admin/public/brand/favicon.svg +4 -1
  52. package/template/apps/admin/tailwind.config.ts +9 -8
  53. package/template/apps/api/package.json +10 -6
  54. package/template/apps/api/src/access/catalog.ts +4 -0
  55. package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
  56. package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
  57. package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
  58. package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
  59. package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
  60. package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
  61. package/template/apps/api/src/admin/admin.controller.ts +17 -4
  62. package/template/apps/api/src/admin/admin.module.ts +2 -2
  63. package/template/apps/api/src/admin/resource-policy.ts +1 -0
  64. package/template/apps/api/src/admin/resource-query.ts +1 -0
  65. package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
  66. package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
  67. package/template/apps/api/src/auth/auth.controller.ts +4 -2
  68. package/template/apps/api/src/auth/auth.service.ts +68 -83
  69. package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
  70. package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
  71. package/template/apps/api/src/common/api-exception.filter.ts +1 -0
  72. package/template/apps/api/src/common/auth.guard.ts +66 -39
  73. package/template/apps/api/src/common/json-field-codec.ts +12 -13
  74. package/template/apps/api/src/common/prisma.service.ts +9 -17
  75. package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
  76. package/template/apps/api/src/graphql/graphql.module.ts +5 -4
  77. package/template/apps/api/src/health/health.controller.ts +6 -0
  78. package/template/apps/api/src/main.ts +11 -2
  79. package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
  80. package/template/apps/api/src/resources/commerce.resource.ts +3 -34
  81. package/template/apps/api/src/resources/operations.resource.ts +1 -0
  82. package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
  83. package/template/apps/api/src/store/payment/payment.module.ts +2 -3
  84. package/template/apps/api/src/store/payment/payment.service.ts +121 -227
  85. package/template/apps/api/webpack.config.cjs +2 -1
  86. package/template/apps/web/next.config.mjs +4 -0
  87. package/template/apps/web/public/brand/favicon.svg +4 -1
  88. package/template/compose.yaml +56 -0
  89. package/template/examples/crm-admin/README.md +31 -0
  90. package/template/examples/crm-admin/package.json +17 -0
  91. package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
  92. package/template/examples/crm-admin/src/index.ts +7 -0
  93. package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
  94. package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
  95. package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
  96. package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
  97. package/template/examples/crm-admin/tsconfig.json +7 -0
  98. package/template/package.json +6 -1
  99. package/template/packages/admin-client/package.json +18 -0
  100. package/template/packages/admin-client/src/contracts.ts +29 -0
  101. package/template/packages/admin-client/src/index.ts +2 -0
  102. package/template/packages/admin-client/src/preferences.ts +57 -0
  103. package/template/packages/admin-client/tsconfig.json +12 -0
  104. package/template/packages/auth/package.json +1 -1
  105. package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
  106. package/template/packages/brand/src/generate-assets.mjs +17 -186
  107. package/template/packages/core/package.json +1 -1
  108. package/template/packages/mail/package.json +1 -1
  109. package/template/packages/nest/package.json +22 -0
  110. package/template/packages/nest/src/api-exception.filter.ts +23 -0
  111. package/template/packages/nest/src/index.ts +3 -0
  112. package/template/packages/nest/src/resource-policy.ts +64 -0
  113. package/template/packages/nest/src/resource-query.ts +103 -0
  114. package/template/packages/nest/tsconfig.json +12 -0
  115. package/template/packages/notifications/package.json +1 -1
  116. package/template/packages/payments/package.json +1 -1
  117. package/template/packages/permissions/package.json +1 -1
  118. package/template/packages/permissions/src/index.ts +2 -2
  119. package/template/packages/plugin-sdk/package.json +1 -1
  120. package/template/packages/plugin-sdk/src/index.ts +2 -2
  121. package/template/packages/prisma/package.json +21 -0
  122. package/template/packages/prisma/schema/ai.prisma +36 -0
  123. package/template/packages/prisma/schema/audit.prisma +13 -0
  124. package/template/packages/prisma/schema/commerce.prisma +79 -0
  125. package/template/packages/prisma/schema/content.prisma +27 -0
  126. package/template/packages/prisma/schema/core.prisma +106 -0
  127. package/template/packages/prisma/schema/header.prisma +8 -0
  128. package/template/packages/prisma/schema/jobs.prisma +9 -0
  129. package/template/packages/prisma/schema/media.prisma +9 -0
  130. package/template/packages/prisma/schema/modules.json +47 -0
  131. package/template/packages/prisma/schema/notifications.prisma +9 -0
  132. package/template/packages/prisma/schema/settings.prisma +8 -0
  133. package/template/packages/prisma/schema/tokens.prisma +10 -0
  134. package/template/packages/prisma/src/index.d.ts +12 -0
  135. package/template/packages/prisma/src/index.mjs +138 -0
  136. package/template/packages/queue/package.json +1 -1
  137. package/template/packages/resource/package.json +1 -1
  138. package/template/packages/resource/src/index.ts +1 -0
  139. package/template/packages/storage/package.json +1 -1
  140. package/template/packages/storage/src/index.ts +37 -0
  141. package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
  142. package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
  143. package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
  144. package/template/prisma/schema.prisma +82 -54
  145. package/template/prisma/seed.ts +14 -38
  146. package/template/runtime-versions.json +15 -0
  147. package/template/scripts/db-init.mjs +33 -0
  148. package/template/scripts/install-crm.mjs +50 -0
  149. package/template/scripts/migrate-existing.mjs +65 -0
  150. package/template/scripts/schema.mjs +48 -0
  151. package/template/tsconfig.base.json +23 -5
  152. package/LICENSE +0 -21
  153. package/dist/adapt-package-manager.test.d.ts +0 -1
  154. package/dist/adapt-package-manager.test.js +0 -76
  155. package/dist/cli.e2e.test.d.ts +0 -1
  156. package/dist/cli.e2e.test.js +0 -87
  157. package/dist/create-project.test.d.ts +0 -1
  158. package/dist/create-project.test.js +0 -275
  159. package/dist/database-providers.integration.test.d.ts +0 -1
  160. package/dist/database-providers.integration.test.js +0 -64
  161. package/dist/db-commands.test.d.ts +0 -1
  162. package/dist/db-commands.test.js +0 -27
  163. package/dist/doctor.test.d.ts +0 -1
  164. package/dist/doctor.test.js +0 -102
  165. package/dist/index.test.d.ts +0 -1
  166. package/dist/index.test.js +0 -11
  167. package/dist/render-schema.test.d.ts +0 -1
  168. package/dist/render-schema.test.js +0 -57
  169. package/dist/resource-slug.test.d.ts +0 -1
  170. package/dist/resource-slug.test.js +0 -9
  171. package/dist/secrets.test.d.ts +0 -1
  172. package/dist/secrets.test.js +0 -36
  173. package/dist/security.test.d.ts +0 -1
  174. package/dist/security.test.js +0 -54
  175. package/dist/validate-name.test.d.ts +0 -1
  176. package/dist/validate-name.test.js +0 -63
  177. package/template/apps/admin/.storybook/main.ts +0 -12
  178. package/template/apps/admin/.storybook/preview.ts +0 -10
  179. package/template/apps/admin/app/login/page.test.tsx +0 -18
  180. package/template/apps/admin/components/auth-guard.test.tsx +0 -55
  181. package/template/apps/admin/components/logo.stories.tsx +0 -24
  182. package/template/apps/admin/lib/api.test.ts +0 -118
  183. package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
  184. package/template/apps/admin/vitest.config.ts +0 -7
  185. package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
  186. package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
  187. package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
  188. package/template/apps/api/src/app.module.test.ts +0 -12
  189. package/template/apps/api/src/auth/auth.service.test.ts +0 -78
  190. package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
  191. package/template/apps/api/src/common/auth.guard.test.ts +0 -62
  192. package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
  193. package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
  194. package/template/apps/api/src/common/prisma.service.test.ts +0 -19
  195. package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
  196. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
  197. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
  198. package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
  199. package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
  200. package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
  201. package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
  202. package/template/apps/api/src/queue/queue.service.test.ts +0 -33
  203. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
  204. package/template/apps/api/vitest.config.ts +0 -21
  205. package/template/apps/web/lib/seo.test.ts +0 -41
  206. package/template/apps/web/vitest.config.ts +0 -19
  207. package/template/packages/auth/src/index.test.ts +0 -10
  208. package/template/packages/brand/src/index.test.ts +0 -9
  209. package/template/packages/core/src/index.test.ts +0 -27
  210. package/template/packages/core/vitest.config.ts +0 -9
  211. package/template/packages/mail/src/index.test.ts +0 -23
  212. package/template/packages/notifications/src/index.test.ts +0 -9
  213. package/template/packages/permissions/src/blueprints.test.ts +0 -62
  214. package/template/packages/permissions/src/index.test.ts +0 -34
  215. package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
  216. package/template/packages/plugin-sdk/vitest.config.ts +0 -5
  217. package/template/packages/queue/src/index.test.ts +0 -12
  218. package/template/packages/resource/src/index.test.ts +0 -196
  219. 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, ResourceField } from "@openadminjs/core";
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 bcrypt from "bcryptjs";
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
- type UserContext = { id: string; email?: string; permissions: string[] };
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) => this.has(user, resource.permissions.read))
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 perResourceLimit = Math.min(Math.max(opts?.perResourceLimit ?? 5, 1), 20);
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 (!this.has(user, resource.permissions.read)) continue;
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: this.buildOrderBy(resource, "createdAt:desc")
88
+ orderBy: buildOrderBy(resource, "createdAt:desc", user)
89
89
  });
90
90
  for (const row of rows) {
91
- const safe = this.sanitizeRecord(resource, row) as Record<string, unknown>;
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 limit = Math.min(Number(query.limit ?? 20), 100);
108
- const baseWhere = this.buildWhere(resource, query);
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 = this.buildOrderBy(resource, String(query.sort ?? "createdAt:desc"));
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) => this.sanitizeRecord(resource, row)), meta: { page, limit, total, pages: Math.ceil(total / limit) || 1 } };
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 (this.isOutOfListScope(resource, user, record)) {
126
+ if (isOutOfListScope(resource, user, record)) {
124
127
  throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
125
128
  }
126
- return this.sanitizeRecord(resource, record);
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 rawToken = randomBytes(32).toString("base64url");
134
- const scopes = this.normalizeScopes(data.scopes);
135
- const record = await this.prisma.$transaction(async (tx) => {
136
- const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
137
- if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
138
- const created = await txDelegate.create({
139
- data: {
140
- name: String(data.name ?? "Token"),
141
- scopes,
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
- const safeRecord = this.sanitizeRecord(resource, record) as Record<string, unknown>;
153
- return { ...safeRecord, plainToken: rawToken };
151
+ return {...sanitizeRecord(resource,created,user) as object,plainToken};
154
152
  }
155
153
 
156
- const payload = this.safeData(resource, data, "create");
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 this.sanitizeRecord(resource, record);
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 (this.isOutOfListScope(resource, user, before)) {
179
+ if (isOutOfListScope(resource, user, before)) {
182
180
  throw new NotFoundException({ message: "Record not found", code: "NOT_FOUND" });
183
181
  }
184
- const payload = this.safeData(resource, data, "edit");
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 this.sanitizeRecord(resource, record);
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 (this.isOutOfListScope(resource, user, before)) {
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
- await txDelegate.delete({ where: { id } });
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 = getResource(name);
229
- const config = resource?.actions?.[action];
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 (!this.has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
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 (this.isOutOfListScope(resource, user, existing)) {
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 this.sanitizeRecord(resource, result);
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 (!this.has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
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: "No ids provided", code: "REORDER_EMPTY" });
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 (this.isOutOfListScope(resource, user, row)) {
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
- const filesResource = this.authorizedResource("files", user, "create");
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 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
- );
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
- * 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, "/");
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 || !this.has(user, permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
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 (!this.payments) throw new Error("PaymentService not available");
94
- return this.payments.refundOrder(id);
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")