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.
Files changed (210) hide show
  1. package/README.md +117 -81
  2. package/dist/adapt-package-manager.d.ts +3 -0
  3. package/dist/adapt-package-manager.js +118 -0
  4. package/dist/create-project.d.ts +77 -2
  5. package/dist/create-project.js +685 -224
  6. package/dist/db-commands.d.ts +20 -0
  7. package/dist/db-commands.js +75 -0
  8. package/dist/detect-package-manager.d.ts +8 -0
  9. package/dist/detect-package-manager.js +37 -0
  10. package/dist/doctor.d.ts +26 -0
  11. package/dist/doctor.js +232 -0
  12. package/dist/index.d.ts +3 -1
  13. package/dist/index.js +476 -166
  14. package/dist/render-schema.d.ts +3 -0
  15. package/dist/render-schema.js +33 -0
  16. package/dist/resource-slug.d.ts +1 -0
  17. package/dist/resource-slug.js +7 -0
  18. package/dist/runtime-mode.d.ts +16 -0
  19. package/dist/runtime-mode.js +138 -0
  20. package/dist/secrets.d.ts +24 -0
  21. package/dist/secrets.js +93 -0
  22. package/dist/security.d.ts +13 -0
  23. package/dist/security.js +168 -0
  24. package/dist/upgrade.d.ts +10 -0
  25. package/dist/upgrade.js +133 -0
  26. package/dist/validate-name.d.ts +33 -0
  27. package/dist/validate-name.js +206 -0
  28. package/package.json +39 -11
  29. package/template/.dockerignore +15 -0
  30. package/template/.env.production.example +5 -0
  31. package/template/Dockerfile +12 -0
  32. package/template/README.md +23 -3
  33. package/template/apps/admin/app/api/auth/login/route.ts +9 -9
  34. package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
  35. package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
  36. package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
  37. package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
  38. package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
  39. package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
  40. package/template/apps/admin/app/api-tokens/page.tsx +39 -39
  41. package/template/apps/admin/app/assistant/page.tsx +11 -0
  42. package/template/apps/admin/app/dashboard/page.tsx +45 -462
  43. package/template/apps/admin/app/globals.css +52 -16
  44. package/template/apps/admin/app/layout.tsx +1 -1
  45. package/template/apps/admin/app/login/page.tsx +13 -145
  46. package/template/apps/admin/app/plugins/page.tsx +16 -402
  47. package/template/apps/admin/app/profile/page.tsx +5 -2
  48. package/template/apps/admin/app/settings/page.tsx +14 -265
  49. package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
  50. package/template/apps/admin/components/app-shell.tsx +25 -373
  51. package/template/apps/admin/components/auth-guard.tsx +8 -28
  52. package/template/apps/admin/components/logo.tsx +1 -30
  53. package/template/apps/admin/components/resource-form.tsx +3 -3
  54. package/template/apps/admin/components/resource-table.tsx +12 -8
  55. package/template/apps/admin/lib/api.ts +45 -107
  56. package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
  57. package/template/apps/admin/lib/server-api.ts +7 -0
  58. package/template/apps/admin/lib/tokens.ts +9 -81
  59. package/template/apps/admin/middleware.ts +9 -50
  60. package/template/apps/admin/next.config.mjs +4 -0
  61. package/template/apps/admin/package.json +2 -1
  62. package/template/apps/admin/public/brand/favicon.svg +4 -1
  63. package/template/apps/admin/tailwind.config.ts +9 -8
  64. package/template/apps/api/package.json +13 -6
  65. package/template/apps/api/src/access/catalog.ts +4 -0
  66. package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
  67. package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
  68. package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
  69. package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
  70. package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
  71. package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
  72. package/template/apps/api/src/admin/admin.controller.ts +17 -4
  73. package/template/apps/api/src/admin/admin.module.ts +2 -2
  74. package/template/apps/api/src/admin/resource-policy.ts +1 -0
  75. package/template/apps/api/src/admin/resource-query.ts +1 -0
  76. package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
  77. package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
  78. package/template/apps/api/src/auth/auth.controller.ts +4 -2
  79. package/template/apps/api/src/auth/auth.service.ts +68 -83
  80. package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
  81. package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
  82. package/template/apps/api/src/common/api-exception.filter.ts +1 -0
  83. package/template/apps/api/src/common/auth.guard.ts +66 -39
  84. package/template/apps/api/src/common/json-field-codec.ts +138 -0
  85. package/template/apps/api/src/common/prisma.service.ts +12 -7
  86. package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
  87. package/template/apps/api/src/graphql/graphql.module.ts +14 -1
  88. package/template/apps/api/src/health/health.controller.ts +6 -0
  89. package/template/apps/api/src/main.ts +11 -2
  90. package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
  91. package/template/apps/api/src/resources/commerce.resource.ts +3 -34
  92. package/template/apps/api/src/resources/operations.resource.ts +1 -0
  93. package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
  94. package/template/apps/api/src/store/payment/payment.module.ts +2 -3
  95. package/template/apps/api/src/store/payment/payment.service.ts +121 -227
  96. package/template/apps/api/webpack.config.cjs +2 -1
  97. package/template/apps/web/next.config.mjs +4 -0
  98. package/template/apps/web/public/brand/favicon.svg +4 -1
  99. package/template/compose.yaml +56 -0
  100. package/template/examples/crm-admin/README.md +31 -0
  101. package/template/examples/crm-admin/package.json +17 -0
  102. package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
  103. package/template/examples/crm-admin/src/index.ts +7 -0
  104. package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
  105. package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
  106. package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
  107. package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
  108. package/template/examples/crm-admin/tsconfig.json +7 -0
  109. package/template/package.json +8 -1
  110. package/template/packages/admin-client/package.json +18 -0
  111. package/template/packages/admin-client/src/contracts.ts +29 -0
  112. package/template/packages/admin-client/src/index.ts +2 -0
  113. package/template/packages/admin-client/src/preferences.ts +57 -0
  114. package/template/packages/admin-client/tsconfig.json +12 -0
  115. package/template/packages/auth/package.json +1 -1
  116. package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
  117. package/template/packages/brand/src/generate-assets.mjs +17 -186
  118. package/template/packages/core/package.json +1 -1
  119. package/template/packages/mail/package.json +1 -1
  120. package/template/packages/nest/package.json +22 -0
  121. package/template/packages/nest/src/api-exception.filter.ts +23 -0
  122. package/template/packages/nest/src/index.ts +3 -0
  123. package/template/packages/nest/src/resource-policy.ts +64 -0
  124. package/template/packages/nest/src/resource-query.ts +103 -0
  125. package/template/packages/nest/tsconfig.json +12 -0
  126. package/template/packages/notifications/package.json +1 -1
  127. package/template/packages/payments/package.json +1 -1
  128. package/template/packages/permissions/package.json +1 -1
  129. package/template/packages/permissions/src/index.ts +2 -2
  130. package/template/packages/plugin-sdk/package.json +1 -1
  131. package/template/packages/plugin-sdk/src/index.ts +2 -2
  132. package/template/packages/prisma/package.json +21 -0
  133. package/template/packages/prisma/schema/ai.prisma +36 -0
  134. package/template/packages/prisma/schema/audit.prisma +13 -0
  135. package/template/packages/prisma/schema/commerce.prisma +79 -0
  136. package/template/packages/prisma/schema/content.prisma +27 -0
  137. package/template/packages/prisma/schema/core.prisma +106 -0
  138. package/template/packages/prisma/schema/header.prisma +8 -0
  139. package/template/packages/prisma/schema/jobs.prisma +9 -0
  140. package/template/packages/prisma/schema/media.prisma +9 -0
  141. package/template/packages/prisma/schema/modules.json +47 -0
  142. package/template/packages/prisma/schema/notifications.prisma +9 -0
  143. package/template/packages/prisma/schema/settings.prisma +8 -0
  144. package/template/packages/prisma/schema/tokens.prisma +10 -0
  145. package/template/packages/prisma/src/index.d.ts +12 -0
  146. package/template/packages/prisma/src/index.mjs +138 -0
  147. package/template/packages/queue/package.json +1 -1
  148. package/template/packages/resource/package.json +1 -1
  149. package/template/packages/resource/src/index.ts +1 -0
  150. package/template/packages/storage/package.json +1 -1
  151. package/template/packages/storage/src/index.ts +37 -0
  152. package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
  153. package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
  154. package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
  155. package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
  156. package/template/prisma/schema.prisma +82 -54
  157. package/template/prisma/seed.ts +14 -38
  158. package/template/runtime-versions.json +15 -0
  159. package/template/scripts/db-init.mjs +33 -0
  160. package/template/scripts/install-crm.mjs +50 -0
  161. package/template/scripts/migrate-existing.mjs +65 -0
  162. package/template/scripts/schema.mjs +48 -0
  163. package/template/tsconfig.base.json +23 -5
  164. package/LICENSE +0 -21
  165. package/dist/create-project.test.d.ts +0 -1
  166. package/dist/create-project.test.js +0 -99
  167. package/dist/index.test.d.ts +0 -1
  168. package/dist/index.test.js +0 -7
  169. package/dist/resource-slug.test.d.ts +0 -1
  170. package/dist/resource-slug.test.js +0 -9
  171. package/template/apps/admin/.storybook/main.ts +0 -12
  172. package/template/apps/admin/.storybook/preview.ts +0 -10
  173. package/template/apps/admin/app/login/page.test.tsx +0 -18
  174. package/template/apps/admin/components/auth-guard.test.tsx +0 -55
  175. package/template/apps/admin/components/logo.stories.tsx +0 -24
  176. package/template/apps/admin/lib/api.test.ts +0 -118
  177. package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
  178. package/template/apps/admin/vitest.config.ts +0 -7
  179. package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
  180. package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
  181. package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
  182. package/template/apps/api/src/app.module.test.ts +0 -12
  183. package/template/apps/api/src/auth/auth.service.test.ts +0 -78
  184. package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
  185. package/template/apps/api/src/common/auth.guard.test.ts +0 -62
  186. package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
  187. package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
  188. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
  189. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
  190. package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
  191. package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
  192. package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
  193. package/template/apps/api/src/queue/queue.service.test.ts +0 -33
  194. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
  195. package/template/apps/api/vitest.config.ts +0 -21
  196. package/template/apps/web/lib/seo.test.ts +0 -41
  197. package/template/apps/web/vitest.config.ts +0 -19
  198. package/template/packages/auth/src/index.test.ts +0 -10
  199. package/template/packages/brand/src/index.test.ts +0 -9
  200. package/template/packages/core/src/index.test.ts +0 -27
  201. package/template/packages/core/vitest.config.ts +0 -9
  202. package/template/packages/mail/src/index.test.ts +0 -23
  203. package/template/packages/notifications/src/index.test.ts +0 -9
  204. package/template/packages/permissions/src/blueprints.test.ts +0 -62
  205. package/template/packages/permissions/src/index.test.ts +0 -34
  206. package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
  207. package/template/packages/plugin-sdk/vitest.config.ts +0 -5
  208. package/template/packages/queue/src/index.test.ts +0 -12
  209. package/template/packages/resource/src/index.test.ts +0 -196
  210. package/template/packages/storage/src/index.test.ts +0 -10
@@ -1,44 +0,0 @@
1
- import { UnprocessableEntityException } from "@nestjs/common";
2
- import { describe, expect, it } from "vitest";
3
- import { defineResource } from "@openadminjs/core";
4
- import { parseWritePayload } from "./validate-resource-payload";
5
-
6
- describe("parseWritePayload", () => {
7
- const widget = defineResource({
8
- name: "widgets",
9
- label: "Widgets",
10
- model: "Widget",
11
- permissions: { read: "w.read", create: "w.create", update: "w.update" },
12
- fields: {
13
- id: { type: "id", list: true },
14
- title: { type: "text", required: true, list: true },
15
- count: { type: "number", list: true },
16
- mode: { type: "select", options: ["a", "b"], list: true },
17
- published: { type: "boolean", required: true, list: true }
18
- }
19
- });
20
-
21
- it("accepts valid create payload", () => {
22
- const out = parseWritePayload(widget, "create", { title: "Hi", count: "3", mode: "a", published: true });
23
- expect(out.title).toBe("Hi");
24
- expect(out.count).toBe(3);
25
- expect(out.mode).toBe("a");
26
- expect(out.published).toBe(true);
27
- });
28
-
29
- it("rejects missing required field on create", () => {
30
- expect(() => parseWritePayload(widget, "create", { count: 1 })).toThrow(UnprocessableEntityException);
31
- });
32
-
33
- it("rejects missing required boolean on create (does not default to false)", () => {
34
- expect(() => parseWritePayload(widget, "create", { title: "x", count: 0, mode: "a" })).toThrow(
35
- UnprocessableEntityException
36
- );
37
- });
38
-
39
- it("rejects unknown keys (strict)", () => {
40
- expect(() =>
41
- parseWritePayload(widget, "create", { title: "x", mode: "a", published: false, extra: 1 })
42
- ).toThrow(UnprocessableEntityException);
43
- });
44
- });
@@ -1,12 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { throttleIpTracker } from "./app.module";
3
-
4
- describe("app throttling", () => {
5
- it("handles GraphQL requests without an HTTP request object", () => {
6
- expect(throttleIpTracker(undefined)).toBe("unknown");
7
- });
8
-
9
- it("uses the request IP for HTTP requests", () => {
10
- expect(throttleIpTracker({ ip: "127.0.0.1" })).toBe("127.0.0.1");
11
- });
12
- });
@@ -1,78 +0,0 @@
1
- import { UnauthorizedException } from "@nestjs/common";
2
- import { describe, expect, it, vi } from "vitest";
3
-
4
- vi.mock("bcryptjs", () => ({
5
- default: {
6
- compare: vi.fn(),
7
- hash: vi.fn().mockResolvedValue("hashed")
8
- }
9
- }));
10
-
11
- import bcrypt from "bcryptjs";
12
- import { AuthService } from "./auth.service";
13
-
14
- const bcryptCompareMock = bcrypt.compare as unknown as ReturnType<typeof vi.fn>;
15
-
16
- function createPrismaMock() {
17
- return {
18
- user: {
19
- findUnique: vi.fn(),
20
- findMany: vi.fn(),
21
- update: vi.fn()
22
- },
23
- auditLog: {
24
- create: vi.fn()
25
- }
26
- };
27
- }
28
-
29
- describe("AuthService", () => {
30
- it("login succeeds for valid credentials and admin realm", async () => {
31
- const prisma = createPrismaMock();
32
- const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
33
- prisma.user.findUnique.mockResolvedValue({
34
- id: "u1",
35
- email: "openadminjs@proton.me",
36
- name: "Admin",
37
- passwordHash: "hash",
38
- roles: [{ role: { name: "admin", realm: "admin", permissions: [{ permission: { name: "*" } }] } }]
39
- });
40
- bcryptCompareMock.mockResolvedValue(true);
41
-
42
- const config = { get: vi.fn().mockReturnValue(undefined) };
43
- const service = new AuthService(prisma as never, jwt as never, config as never);
44
- const result = await service.login("openadminjs@proton.me", "password", {}, "admin");
45
-
46
- expect(result.accessToken).toBe("jwt");
47
- expect(result.user.email).toBe("openadminjs@proton.me");
48
- expect(prisma.auditLog.create).toHaveBeenCalled();
49
- });
50
-
51
- it("login fails for wrong realm", async () => {
52
- const prisma = createPrismaMock();
53
- const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
54
- prisma.user.findUnique.mockResolvedValue({
55
- id: "u1",
56
- email: "openadminjs@proton.me",
57
- name: "Admin",
58
- passwordHash: "hash",
59
- roles: [{ role: { name: "admin", realm: "public", permissions: [] } }]
60
- });
61
- bcryptCompareMock.mockResolvedValue(true);
62
-
63
- const config = { get: vi.fn().mockReturnValue(undefined) };
64
- const service = new AuthService(prisma as never, jwt as never, config as never);
65
- await expect(service.login("openadminjs@proton.me", "password", {}, "admin")).rejects.toBeInstanceOf(UnauthorizedException);
66
- });
67
-
68
- it("refresh fails when token does not match any user", async () => {
69
- const prisma = createPrismaMock();
70
- const jwt = { signAsync: vi.fn().mockResolvedValue("jwt") };
71
- prisma.user.findMany.mockResolvedValue([{ id: "u1", refreshTokenHash: "hash-1" }]);
72
- bcryptCompareMock.mockResolvedValue(false);
73
-
74
- const config = { get: vi.fn().mockReturnValue(undefined) };
75
- const service = new AuthService(prisma as never, jwt as never, config as never);
76
- await expect(service.refresh("bad-token", "admin")).rejects.toBeInstanceOf(UnauthorizedException);
77
- });
78
- });
@@ -1,84 +0,0 @@
1
- import { BadRequestException, UnauthorizedException } from "@nestjs/common";
2
- import { describe, expect, it, vi } from "vitest";
3
- import { SsoOidcService } from "./sso-oidc.service";
4
-
5
- function configMock(values: Record<string, string | undefined>) {
6
- return {
7
- get: vi.fn((key: string) => values[key])
8
- };
9
- }
10
-
11
- describe("SsoOidcService", () => {
12
- it("isEnabled uses provider preset issuer", () => {
13
- const cfg = configMock({
14
- OIDC_PROVIDER: "google",
15
- OIDC_CLIENT_ID: "cid",
16
- OIDC_CLIENT_SECRET: "sec",
17
- OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback"
18
- });
19
- const auth = { loginWithOidcProfile: vi.fn() };
20
- const service = new SsoOidcService(cfg as never, auth as never);
21
- expect(service.isEnabled()).toBe(true);
22
- });
23
-
24
- it("startLogin fails without issuer or known preset", async () => {
25
- const cfg = configMock({
26
- OIDC_PROVIDER: "custom",
27
- OIDC_CLIENT_ID: "cid",
28
- OIDC_CLIENT_SECRET: "sec",
29
- OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
30
- JWT_SECRET: "jwt-secret"
31
- });
32
- const auth = { loginWithOidcProfile: vi.fn() };
33
- const service = new SsoOidcService(cfg as never, auth as never);
34
- await expect(service.startLogin("admin")).rejects.toBeInstanceOf(BadRequestException);
35
- });
36
-
37
- it("handleCallback rejects malformed state", async () => {
38
- const cfg = configMock({
39
- OIDC_ISSUER: "https://accounts.google.com",
40
- OIDC_CLIENT_ID: "cid",
41
- OIDC_CLIENT_SECRET: "sec",
42
- OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
43
- JWT_SECRET: "jwt-secret"
44
- });
45
- const auth = { loginWithOidcProfile: vi.fn() };
46
- const service = new SsoOidcService(cfg as never, auth as never);
47
- const req = { cookies: { oajs_oidc: "x.y" }, headers: {}, ip: "127.0.0.1", path: "/auth/sso/oidc/callback" };
48
- await expect(service.handleCallback(req as never, "code", "bad")).rejects.toBeInstanceOf(UnauthorizedException);
49
- });
50
-
51
- it("handleCallback rejects callback host mismatch", async () => {
52
- vi.stubGlobal(
53
- "fetch",
54
- vi.fn().mockResolvedValue({
55
- ok: true,
56
- json: async () => ({
57
- authorization_endpoint: "https://accounts.google.com/o/oauth2/v2/auth",
58
- token_endpoint: "https://oauth2.googleapis.com/token",
59
- userinfo_endpoint: "https://openidconnect.googleapis.com/v1/userinfo"
60
- })
61
- })
62
- );
63
- const cfg = configMock({
64
- OIDC_ISSUER: "https://accounts.google.com",
65
- OIDC_CLIENT_ID: "cid",
66
- OIDC_CLIENT_SECRET: "sec",
67
- OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
68
- JWT_SECRET: "jwt-secret"
69
- });
70
- const auth = { loginWithOidcProfile: vi.fn() };
71
- const service = new SsoOidcService(cfg as never, auth as never);
72
- const started = await service.startLogin("admin");
73
- const state = new URL(started.authorizeUrl).searchParams.get("state") ?? "";
74
- const req = {
75
- cookies: { oajs_oidc: started.setCookie.value },
76
- headers: { host: "evil.example.com" },
77
- ip: "127.0.0.1",
78
- path: "/auth/sso/oidc/callback"
79
- };
80
- await expect(service.handleCallback(req as never, "code", state)).rejects.toBeInstanceOf(UnauthorizedException);
81
- vi.unstubAllGlobals();
82
- });
83
- });
84
-
@@ -1,62 +0,0 @@
1
- import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
2
- import { describe, expect, it, vi } from "vitest";
3
- import { AuthGuard } from "./auth.guard";
4
-
5
- function createContext(authHeader?: string, requiredRealm?: string) {
6
- const request: { headers: Record<string, string>; user?: unknown } = { headers: {} };
7
- if (authHeader) request.headers.authorization = authHeader;
8
- return {
9
- request,
10
- ctx: {
11
- getType: () => "http",
12
- switchToHttp: () => ({ getRequest: () => request }),
13
- getHandler: () => "handler",
14
- getClass: () => "class"
15
- },
16
- reflector: {
17
- getAllAndOverride: vi.fn().mockReturnValue(requiredRealm)
18
- }
19
- };
20
- }
21
-
22
- const mockConfig = { get: vi.fn().mockReturnValue("test-secret") };
23
-
24
- describe("AuthGuard", () => {
25
- it("rejects missing token", async () => {
26
- const { ctx, reflector } = createContext(undefined);
27
- const guard = new AuthGuard({ verifyAsync: vi.fn() } as never, { user: { findUnique: vi.fn() } } as never, reflector as never, mockConfig as never);
28
- await expect(guard.canActivate(ctx as never)).rejects.toBeInstanceOf(UnauthorizedException);
29
- });
30
-
31
- it("rejects realm mismatch", async () => {
32
- const { ctx, reflector } = createContext("Bearer token", "public");
33
- const guard = new AuthGuard(
34
- { verifyAsync: vi.fn().mockResolvedValue({ sub: "u1", realm: "admin" }) } as never,
35
- { user: { findUnique: vi.fn() } } as never,
36
- reflector as never,
37
- mockConfig as never
38
- );
39
- await expect(guard.canActivate(ctx as never)).rejects.toBeInstanceOf(ForbiddenException);
40
- });
41
-
42
- it("attaches request.user for valid token", async () => {
43
- const { ctx, reflector, request } = createContext("Bearer token", "admin");
44
- const guard = new AuthGuard(
45
- { verifyAsync: vi.fn().mockResolvedValue({ sub: "u1", realm: "admin" }) } as never,
46
- {
47
- user: {
48
- findUnique: vi.fn().mockResolvedValue({
49
- id: "u1",
50
- email: "openadminjs@proton.me",
51
- name: "Admin",
52
- roles: [{ role: { name: "admin", realm: "admin", permissions: [{ permission: { name: "*" } }] } }]
53
- })
54
- }
55
- } as never,
56
- reflector as never,
57
- mockConfig as never
58
- );
59
- await expect(guard.canActivate(ctx as never)).resolves.toBe(true);
60
- expect((request.user as { id: string }).id).toBe("u1");
61
- });
62
- });
@@ -1,33 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { CaslAbilityFactory } from "./casl-ability.factory";
3
-
4
- describe("CaslAbilityFactory", () => {
5
- const factory = new CaslAbilityFactory();
6
-
7
- it("maps dotted permissions to CASL rules", () => {
8
- const ability = factory.createForUser({ permissions: ["posts.read", "users.update"] });
9
- expect(ability.can("read", "posts")).toBe(true);
10
- expect(ability.can("update", "users")).toBe(true);
11
- expect(ability.can("delete", "posts")).toBe(false);
12
- });
13
-
14
- it("uses the last dot for namespaced slugs", () => {
15
- const ability = factory.createForUser({ permissions: ["public.orders.read_own"] });
16
- expect(ability.can("manage", "public.orders")).toBe(true);
17
- });
18
-
19
- it("grants manage all for star permission", () => {
20
- const ability = factory.createForUser({ permissions: ["*"] });
21
- expect(ability.can("manage", "all")).toBe(true);
22
- });
23
-
24
- it("maps unknown actions to manage", () => {
25
- const ability = factory.createForUser({ permissions: ["reports.export"] });
26
- expect(ability.can("manage", "reports")).toBe(true);
27
- });
28
-
29
- it("ignores malformed permission strings", () => {
30
- const ability = factory.createForUser({ permissions: ["noparts", ".", "ok.read"] });
31
- expect(ability.can("read", "ok")).toBe(true);
32
- });
33
- });
@@ -1,39 +0,0 @@
1
- import { CallHandler, ExecutionContext } from "@nestjs/common";
2
- import { throwError } from "rxjs";
3
- import { describe, expect, it, vi } from "vitest";
4
- import { AppLoggerService } from "./app-logger.service";
5
- import { RequestLoggingInterceptor } from "./request-logging.interceptor";
6
-
7
- function httpContext(): ExecutionContext {
8
- return {
9
- getType: () => "http",
10
- switchToHttp: () => ({
11
- getRequest: () => ({ method: "POST", url: "/auth/login", ip: "127.0.0.1" }),
12
- getResponse: () => ({ statusCode: 200 })
13
- })
14
- } as ExecutionContext;
15
- }
16
-
17
- describe("RequestLoggingInterceptor", () => {
18
- it("logs failed requests without throwing when the handler errors", async () => {
19
- const logger = {
20
- info: vi.fn(),
21
- error: vi.fn()
22
- } as unknown as AppLoggerService;
23
- const interceptor = new RequestLoggingInterceptor(logger);
24
-
25
- const handler: CallHandler = {
26
- handle: () => throwError(() => new Error("db down"))
27
- };
28
-
29
- await expect(interceptor.intercept(httpContext(), handler).toPromise()).rejects.toThrow("db down");
30
- expect(logger.error).toHaveBeenCalledWith(
31
- "request.failed",
32
- expect.objectContaining({
33
- method: "POST",
34
- path: "/auth/login",
35
- errorMessage: "db down"
36
- })
37
- );
38
- });
39
- });
@@ -1,45 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { AdminResourcesResolver } from "./admin-resources.resolver";
3
-
4
- describe("AdminResourcesResolver", () => {
5
- it("maps GraphQL filter input to REST-style filter query keys", async () => {
6
- const adminResources = {
7
- list: vi.fn().mockResolvedValue({ data: [], meta: { page: 1, limit: 20, total: 0, pages: 1 } })
8
- };
9
- const resolver = new AdminResourcesResolver(adminResources as never);
10
- const user = { id: "u1", permissions: ["*"] };
11
-
12
- await resolver.adminResourceList(
13
- {
14
- name: "posts",
15
- page: 2,
16
- limit: 15,
17
- search: "hello",
18
- sort: "createdAt:desc",
19
- locale: "en",
20
- filter: {
21
- status: { eq: "published" },
22
- views: { gte: 10, lte: 100 },
23
- authorId: "u1"
24
- }
25
- },
26
- { req: { user } } as never
27
- );
28
-
29
- expect(adminResources.list).toHaveBeenCalledWith(
30
- "posts",
31
- {
32
- page: 2,
33
- limit: 15,
34
- search: "hello",
35
- sort: "createdAt:desc",
36
- locale: "en",
37
- "filter[status][eq]": "published",
38
- "filter[views][gte]": 10,
39
- "filter[views][lte]": 100,
40
- "filter[authorId]": "u1"
41
- },
42
- user
43
- );
44
- });
45
- });
@@ -1,44 +0,0 @@
1
- import "reflect-metadata";
2
- import { describe, expect, it } from "vitest";
3
- import { ensureGqlFieldTypes, ensureGqlParamTypes } from "./ensure-gql-paramtypes";
4
-
5
- describe("ensureGqlParamTypes", () => {
6
- it("defines design:paramtypes when missing", () => {
7
- class Sample {
8
- handler(_a: string, _b: number) {}
9
- }
10
- ensureGqlParamTypes(Sample.prototype, "handler", [String, Number]);
11
- expect(Reflect.getMetadata("design:paramtypes", Sample.prototype, "handler")).toEqual([
12
- String,
13
- Number
14
- ]);
15
- });
16
-
17
- it("does not overwrite existing metadata", () => {
18
- class Sample {
19
- handler() {}
20
- }
21
- Reflect.defineMetadata("design:paramtypes", [Date], Sample.prototype, "handler");
22
- ensureGqlParamTypes(Sample.prototype, "handler", [String]);
23
- expect(Reflect.getMetadata("design:paramtypes", Sample.prototype, "handler")).toEqual([Date]);
24
- });
25
-
26
- it("defines missing design:type metadata for GraphQL fields", () => {
27
- class Sample {
28
- name!: string;
29
- count!: number;
30
- }
31
- ensureGqlFieldTypes(Sample.prototype, { name: String, count: Number });
32
- expect(Reflect.getMetadata("design:type", Sample.prototype, "name")).toBe(String);
33
- expect(Reflect.getMetadata("design:type", Sample.prototype, "count")).toBe(Number);
34
- });
35
-
36
- it("does not overwrite existing field metadata", () => {
37
- class Sample {
38
- createdAt!: Date;
39
- }
40
- Reflect.defineMetadata("design:type", Date, Sample.prototype, "createdAt");
41
- ensureGqlFieldTypes(Sample.prototype, { createdAt: String });
42
- expect(Reflect.getMetadata("design:type", Sample.prototype, "createdAt")).toBe(Date);
43
- });
44
- });
@@ -1,26 +0,0 @@
1
- import "reflect-metadata";
2
- import { describe, expect, it } from "vitest";
3
- import { AdminResourceListArgs, AdminResourceRecordArgs } from "./admin-resources.args";
4
- import { AdminResourcesResolver } from "./admin-resources.resolver";
5
-
6
- describe("GraphQL schema (admin resources)", () => {
7
- it("exposes design:type metadata for args fields when the compiler does not emit it", () => {
8
- expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "name")).toBe(String);
9
- expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "page")).toBe(Number);
10
- expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "filter")).toBeTruthy();
11
- expect(Reflect.getMetadata("design:type", AdminResourceRecordArgs.prototype, "id")).toBe(String);
12
- });
13
-
14
- it("exposes design:paramtypes for Nest GraphQL when the compiler does not emit it", () => {
15
- expect(
16
- Reflect.getMetadata("design:paramtypes", AdminResourcesResolver.prototype, "adminResourceList")
17
- ).toEqual([AdminResourceListArgs, Object]);
18
- expect(
19
- Reflect.getMetadata("design:paramtypes", AdminResourcesResolver.prototype, "adminResourceRecord")
20
- ).toEqual([AdminResourceRecordArgs, Object]);
21
- expect(
22
- Reflect.getMetadata("design:paramtypes", AdminResourcesResolver.prototype, "adminRegisteredResourceNames")
23
- ).toEqual([Object]);
24
- });
25
-
26
- });
@@ -1,36 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { pluginManifestSchema } from "./manifest.schema";
3
-
4
- describe("pluginManifestSchema", () => {
5
- it("accepts bundled-only entry", () => {
6
- const r = pluginManifestSchema.safeParse({
7
- version: 1,
8
- plugins: [{ id: "a.b", bundled: "hello", enabled: true, config: { x: 1 }, capabilities: ["resource.hooks"], trustMode: "sandboxed" }]
9
- });
10
- expect(r.success).toBe(true);
11
- });
12
-
13
- it("rejects unknown capability", () => {
14
- const r = pluginManifestSchema.safeParse({
15
- version: 1,
16
- plugins: [{ id: "a.b", bundled: "hello", capabilities: ["unknown.cap"] }]
17
- });
18
- expect(r.success).toBe(false);
19
- });
20
-
21
- it("rejects both bundled and package", () => {
22
- const r = pluginManifestSchema.safeParse({
23
- version: 1,
24
- plugins: [{ id: "x", bundled: "hello", package: "@x/y" }]
25
- });
26
- expect(r.success).toBe(false);
27
- });
28
-
29
- it("rejects neither bundled nor package", () => {
30
- const r = pluginManifestSchema.safeParse({
31
- version: 1,
32
- plugins: [{ id: "x" }]
33
- });
34
- expect(r.success).toBe(false);
35
- });
36
- });
@@ -1,24 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { pluginRuntime } from "./plugin-runtime";
3
-
4
- describe("pluginRuntime", () => {
5
- it("registers and removes surfaces by source", () => {
6
- pluginRuntime.register(
7
- "test.plugin",
8
- {
9
- seo: {
10
- metadata: () => ({ title: "x" })
11
- },
12
- jobs: [{ name: "test-job", handler: () => "ok" }]
13
- },
14
- "posts"
15
- );
16
- expect(pluginRuntime.getSeoHooks().length).toBeGreaterThan(0);
17
- expect(pluginRuntime.getJobs().some((job) => job.name === "test-job")).toBe(true);
18
-
19
- pluginRuntime.removeBySource("test.plugin");
20
-
21
- expect(pluginRuntime.getSeoHooks().length).toBe(0);
22
- expect(pluginRuntime.getJobs().some((job) => job.name === "test-job")).toBe(false);
23
- });
24
- });
@@ -1,33 +0,0 @@
1
- import { ServiceUnavailableException } from "@nestjs/common";
2
- import { afterEach, describe, expect, it } from "vitest";
3
- import { QueueService } from "./queue.service";
4
-
5
- const originalRedisUrl = process.env.REDIS_URL;
6
-
7
- describe("QueueService", () => {
8
- afterEach(() => {
9
- process.env.REDIS_URL = originalRedisUrl;
10
- });
11
-
12
- it("degrades gracefully when Redis is not configured", async () => {
13
- delete process.env.REDIS_URL;
14
- const recent = [{ id: "job_1", name: "maintenance.sync", status: "completed" }];
15
- const service = new QueueService({
16
- jobLog: {
17
- findMany: async () => recent
18
- }
19
- } as never);
20
-
21
- await expect(service.getStats()).resolves.toEqual({
22
- counts: {
23
- active: 0,
24
- waiting: 0,
25
- completed: 0,
26
- failed: 0,
27
- delayed: 0
28
- },
29
- recent
30
- });
31
- await expect(service.dispatch("user_1")).rejects.toBeInstanceOf(ServiceUnavailableException);
32
- });
33
- });
@@ -1,72 +0,0 @@
1
- import { describe, expect, it, beforeEach } from "vitest";
2
- import { runBeforeCreate } from "./resource-hooks.runner";
3
- import {
4
- registerResourceHooks,
5
- resetResourceHookRegistryForTests,
6
- unregisterResourceHooksBySource
7
- } from "./resource-hooks.registry";
8
- import type { ResourceConfig } from "@openadminjs/core";
9
-
10
- const stubResource = { name: "x", label: "X", model: "M", permissions: { read: "x.read", create: "x.c" }, fields: {} } as unknown as ResourceConfig;
11
-
12
- describe("resource hook registry", () => {
13
- beforeEach(() => resetResourceHookRegistryForTests());
14
-
15
- it("stacks hooks in registration order", async () => {
16
- const order: string[] = [];
17
- registerResourceHooks("posts", {
18
- beforeCreate() {
19
- order.push("a");
20
- }
21
- });
22
- registerResourceHooks("posts", {
23
- beforeCreate() {
24
- order.push("b");
25
- }
26
- });
27
- await runBeforeCreate("posts", stubResource, { id: "1", email: "e", permissions: [] }, {}, {});
28
- expect(order).toEqual(["a", "b"]);
29
- });
30
-
31
- it("replace clears prior hooks for that resource", async () => {
32
- const order: string[] = [];
33
- registerResourceHooks("posts", {
34
- beforeCreate() {
35
- order.push("first");
36
- }
37
- });
38
- registerResourceHooks(
39
- "posts",
40
- {
41
- beforeCreate() {
42
- order.push("only");
43
- }
44
- },
45
- { replace: true }
46
- );
47
- await runBeforeCreate("posts", stubResource, { id: "1", email: "e", permissions: [] }, {}, {});
48
- expect(order).toEqual(["only"]);
49
- });
50
-
51
- it("unregisterResourceHooksBySource removes only matching source", async () => {
52
- const order: string[] = [];
53
- registerResourceHooks(
54
- "posts",
55
- { beforeCreate() { order.push("core"); } },
56
- { source: "core" }
57
- );
58
- registerResourceHooks(
59
- "posts",
60
- { beforeCreate() { order.push("p1"); } },
61
- { source: "plugin-a" }
62
- );
63
- registerResourceHooks(
64
- "posts",
65
- { beforeCreate() { order.push("p2"); } },
66
- { source: "plugin-b" }
67
- );
68
- unregisterResourceHooksBySource("plugin-a");
69
- await runBeforeCreate("posts", stubResource, { id: "1", email: "e", permissions: [] }, {}, {});
70
- expect(order).toEqual(["core", "p2"]);
71
- });
72
- });
@@ -1,21 +0,0 @@
1
- import { dirname, resolve } from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import { defineConfig } from "vitest/config";
4
-
5
- const __dirname = dirname(fileURLToPath(import.meta.url));
6
- const repoRoot = resolve(__dirname, "../..");
7
-
8
- export default defineConfig({
9
- test: {
10
- environment: "node",
11
- setupFiles: [resolve(__dirname, "src/test-setup.ts")]
12
- },
13
- resolve: {
14
- alias: {
15
- "@openadminjs/core": resolve(repoRoot, "packages/core/src/index.ts"),
16
- "@openadminjs/resource": resolve(repoRoot, "packages/resource/src/index.ts"),
17
- "@openadminjs/permissions": resolve(repoRoot, "packages/permissions/src/index.ts"),
18
- "@openadminjs/plugin-sdk": resolve(repoRoot, "packages/plugin-sdk/src/index.ts")
19
- }
20
- }
21
- });