openadminjs 0.1.6 → 0.1.8

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 (216) hide show
  1. package/dist/create-project.js +38 -6
  2. package/dist/create-project.test.js +69 -24
  3. package/dist/index.js +16 -5
  4. package/package.json +4 -2
  5. package/template/.env.example +2 -2
  6. package/template/README.md +24 -3
  7. package/template/apps/admin/app/api/auth/login/route.ts +51 -0
  8. package/template/apps/admin/app/api/auth/logout/route.ts +11 -0
  9. package/template/apps/admin/app/api/auth/refresh/route.ts +46 -0
  10. package/template/apps/admin/app/api-tokens/page.tsx +253 -0
  11. package/template/apps/admin/app/audit-logs/page.tsx +5 -0
  12. package/template/apps/admin/app/dashboard/page.tsx +392 -0
  13. package/template/apps/admin/app/files/page.tsx +5 -0
  14. package/template/apps/admin/app/globals.css +206 -0
  15. package/template/apps/admin/app/jobs/page.tsx +19 -0
  16. package/template/apps/admin/app/layout.tsx +57 -0
  17. package/template/apps/admin/app/login/page.test.tsx +18 -0
  18. package/template/apps/admin/app/login/page.tsx +161 -0
  19. package/template/apps/admin/app/login/safe-next-param.ts +4 -0
  20. package/template/apps/admin/app/notifications/page.tsx +146 -0
  21. package/template/apps/admin/app/page.tsx +5 -0
  22. package/template/apps/admin/app/plugins/page.tsx +407 -0
  23. package/template/apps/admin/app/profile/page.tsx +116 -0
  24. package/template/apps/admin/app/resources/[resource]/[id]/edit/page.tsx +45 -0
  25. package/template/apps/admin/app/resources/[resource]/[id]/page.tsx +449 -0
  26. package/template/apps/admin/app/resources/[resource]/create/page.tsx +34 -0
  27. package/template/apps/admin/app/resources/[resource]/page.tsx +100 -0
  28. package/template/apps/admin/app/settings/page.tsx +233 -0
  29. package/template/apps/admin/components/ai-assistant-widget.tsx +684 -0
  30. package/template/apps/admin/components/app-shell.tsx +305 -0
  31. package/template/apps/admin/components/auth-guard.test.tsx +55 -0
  32. package/template/apps/admin/components/auth-guard.tsx +39 -0
  33. package/template/apps/admin/components/jobs-panel.tsx +103 -0
  34. package/template/apps/admin/components/logo.tsx +30 -0
  35. package/template/apps/admin/components/resource-form.tsx +349 -0
  36. package/template/apps/admin/components/resource-table.tsx +277 -0
  37. package/template/apps/admin/lib/ai-events.ts +23 -0
  38. package/template/apps/admin/lib/api.test.ts +118 -0
  39. package/template/apps/admin/lib/api.ts +135 -0
  40. package/template/apps/admin/lib/auth-flow.e2e.test.ts +79 -0
  41. package/template/apps/admin/lib/brand.ts +14 -0
  42. package/template/apps/admin/lib/locale.ts +49 -0
  43. package/template/apps/admin/lib/tokens.ts +93 -0
  44. package/template/apps/admin/middleware.ts +58 -0
  45. package/template/apps/admin/next-env.d.ts +6 -0
  46. package/template/apps/admin/next.config.mjs +7 -0
  47. package/template/apps/admin/package.json +44 -0
  48. package/template/apps/admin/postcss.config.mjs +6 -0
  49. package/template/apps/admin/public/brand/apple-touch-icon.png +0 -0
  50. package/template/apps/admin/public/brand/favicon.svg +1 -0
  51. package/template/apps/admin/public/brand/og-image.png +0 -0
  52. package/template/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
  53. package/template/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
  54. package/template/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
  55. package/template/apps/admin/tailwind.config.ts +37 -0
  56. package/template/apps/admin/tsconfig.json +23 -0
  57. package/template/apps/admin/vitest.config.ts +7 -0
  58. package/template/apps/api/package.json +56 -0
  59. package/template/apps/api/plugins.manifest.example.json +34 -0
  60. package/template/apps/api/plugins.manifest.json +4 -0
  61. package/template/apps/api/src/access/catalog.ts +112 -0
  62. package/template/apps/api/src/access/derive-permissions.test.ts +26 -0
  63. package/template/apps/api/src/access/derive-permissions.ts +36 -0
  64. package/template/apps/api/src/access/public-catalog.ts +28 -0
  65. package/template/apps/api/src/admin/admin-ai.controller.ts +125 -0
  66. package/template/apps/api/src/admin/admin-ai.events.ts +23 -0
  67. package/template/apps/api/src/admin/admin-ai.service.ts +1271 -0
  68. package/template/apps/api/src/admin/admin-analytics.service.ts +164 -0
  69. package/template/apps/api/src/admin/admin-plugins.controller.ts +32 -0
  70. package/template/apps/api/src/admin/admin-plugins.service.ts +267 -0
  71. package/template/apps/api/src/admin/admin-resource.service.test.ts +118 -0
  72. package/template/apps/api/src/admin/admin-resource.service.ts +375 -0
  73. package/template/apps/api/src/admin/admin.controller.ts +72 -0
  74. package/template/apps/api/src/admin/admin.module.ts +30 -0
  75. package/template/apps/api/src/admin/dto/plugins.dto.ts +55 -0
  76. package/template/apps/api/src/admin/validate-resource-payload.test.ts +44 -0
  77. package/template/apps/api/src/admin/validate-resource-payload.ts +103 -0
  78. package/template/apps/api/src/app.module.ts +45 -0
  79. package/template/apps/api/src/auth/auth.controller.ts +70 -0
  80. package/template/apps/api/src/auth/auth.dto.ts +49 -0
  81. package/template/apps/api/src/auth/auth.module.ts +30 -0
  82. package/template/apps/api/src/auth/auth.service.test.ts +75 -0
  83. package/template/apps/api/src/auth/auth.service.ts +231 -0
  84. package/template/apps/api/src/common/auth-realm.decorator.ts +6 -0
  85. package/template/apps/api/src/common/auth.guard.test.ts +61 -0
  86. package/template/apps/api/src/common/auth.guard.ts +78 -0
  87. package/template/apps/api/src/common/casl-ability.factory.test.ts +33 -0
  88. package/template/apps/api/src/common/casl-ability.factory.ts +41 -0
  89. package/template/apps/api/src/common/current-user.decorator.ts +6 -0
  90. package/template/apps/api/src/common/permission.decorator.ts +7 -0
  91. package/template/apps/api/src/common/permissions.guard.ts +31 -0
  92. package/template/apps/api/src/common/prisma.service.ts +13 -0
  93. package/template/apps/api/src/health/health.controller.ts +25 -0
  94. package/template/apps/api/src/mail/mail.module.ts +9 -0
  95. package/template/apps/api/src/mail/mail.service.ts +115 -0
  96. package/template/apps/api/src/main.ts +37 -0
  97. package/template/apps/api/src/plugins/bootstrap.ts +4 -0
  98. package/template/apps/api/src/plugins/bundled/admin-widget.plugin.ts +25 -0
  99. package/template/apps/api/src/plugins/bundled/hello.plugin.ts +19 -0
  100. package/template/apps/api/src/plugins/bundled/image-optimizer.plugin.ts +22 -0
  101. package/template/apps/api/src/plugins/bundled/registry.ts +13 -0
  102. package/template/apps/api/src/plugins/bundled/seo.plugin.ts +25 -0
  103. package/template/apps/api/src/plugins/manifest-path.ts +35 -0
  104. package/template/apps/api/src/plugins/manifest.schema.test.ts +36 -0
  105. package/template/apps/api/src/plugins/manifest.schema.ts +58 -0
  106. package/template/apps/api/src/plugins/plugin-api.interceptor.ts +47 -0
  107. package/template/apps/api/src/plugins/plugin-loader.ts +134 -0
  108. package/template/apps/api/src/plugins/plugin-runtime.test.ts +24 -0
  109. package/template/apps/api/src/plugins/plugin-runtime.ts +85 -0
  110. package/template/apps/api/src/queue/queue.controller.ts +28 -0
  111. package/template/apps/api/src/queue/queue.module.ts +23 -0
  112. package/template/apps/api/src/queue/queue.processor.ts +47 -0
  113. package/template/apps/api/src/queue/queue.service.ts +50 -0
  114. package/template/apps/api/src/resources/categories.resource.ts +21 -0
  115. package/template/apps/api/src/resources/commerce.resource.ts +157 -0
  116. package/template/apps/api/src/resources/operations.resource.ts +111 -0
  117. package/template/apps/api/src/resources/posts.resource.ts +88 -0
  118. package/template/apps/api/src/resources/registry.ts +27 -0
  119. package/template/apps/api/src/resources/resource-hooks.install.ts +18 -0
  120. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +72 -0
  121. package/template/apps/api/src/resources/resource-hooks.registry.ts +66 -0
  122. package/template/apps/api/src/resources/resource-hooks.runner.ts +93 -0
  123. package/template/apps/api/src/resources/system.resource.ts +51 -0
  124. package/template/apps/api/src/resources/users.resource.ts +19 -0
  125. package/template/apps/api/src/store/payment/payment.controller.ts +98 -0
  126. package/template/apps/api/src/store/payment/payment.module.ts +14 -0
  127. package/template/apps/api/src/store/payment/payment.provider.ts +38 -0
  128. package/template/apps/api/src/store/payment/payment.service.ts +235 -0
  129. package/template/apps/api/src/store/store.controller.ts +26 -0
  130. package/template/apps/api/src/store/store.module.ts +12 -0
  131. package/template/apps/api/src/test-setup.ts +1 -0
  132. package/template/apps/api/tsconfig.json +11 -0
  133. package/template/apps/api/vitest.config.ts +21 -0
  134. package/template/apps/web/lib/openadmin-client.ts +11 -0
  135. package/template/apps/web/lib/seo.test.ts +41 -0
  136. package/template/apps/web/lib/seo.ts +24 -13
  137. package/template/apps/web/next-env.d.ts +4 -0
  138. package/template/apps/web/package.json +2 -1
  139. package/template/apps/web/test/next-stub.ts +7 -0
  140. package/template/apps/web/vitest.config.ts +19 -0
  141. package/template/package.json +18 -11
  142. package/template/packages/auth/package.json +17 -0
  143. package/template/packages/auth/src/index.test.ts +10 -0
  144. package/template/packages/auth/src/index.ts +17 -0
  145. package/template/packages/auth/tsconfig.json +8 -0
  146. package/template/packages/brand/apps/admin/public/brand/apple-touch-icon.png +0 -0
  147. package/template/packages/brand/apps/admin/public/brand/favicon.svg +1 -0
  148. package/template/packages/brand/apps/admin/public/brand/og-image.png +0 -0
  149. package/template/packages/brand/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
  150. package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
  151. package/template/packages/brand/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
  152. package/template/packages/brand/apps/web/public/brand/apple-touch-icon.png +0 -0
  153. package/template/packages/brand/apps/web/public/brand/favicon.svg +1 -0
  154. package/template/packages/brand/apps/web/public/brand/og-image.png +0 -0
  155. package/template/packages/brand/apps/web/public/brand/openadminjs-icon-new.png +0 -0
  156. package/template/packages/brand/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
  157. package/template/packages/brand/apps/web/public/brand/openadminjs-logo-new.png +0 -0
  158. package/template/packages/brand/package.json +19 -0
  159. package/template/packages/brand/site/assets/brand/favicon.svg +1 -0
  160. package/template/packages/brand/site/assets/brand/og-image.svg +1 -0
  161. package/template/packages/brand/site/assets/brand/openadminjs-icon.svg +1 -0
  162. package/template/packages/brand/site/assets/brand/openadminjs-logo-dark.svg +1 -0
  163. package/template/packages/brand/site/assets/brand/openadminjs-logo-horizontal.svg +1 -0
  164. package/template/packages/brand/site/assets/brand/openadminjs-logo-monochrome.svg +1 -0
  165. package/template/packages/brand/site/assets/brand/openadminjs-logo.svg +1 -0
  166. package/template/packages/brand/src/generate-assets.mjs +182 -0
  167. package/template/packages/brand/src/index.test.ts +9 -0
  168. package/template/packages/brand/src/index.ts +7 -0
  169. package/template/packages/brand/tsconfig.json +7 -0
  170. package/template/packages/core/package.json +20 -0
  171. package/template/packages/core/src/index.js +1 -0
  172. package/template/packages/core/src/index.test.ts +27 -0
  173. package/template/packages/core/src/index.ts +61 -0
  174. package/template/packages/core/tsconfig.json +8 -0
  175. package/template/packages/mail/package.json +18 -0
  176. package/template/packages/mail/src/index.test.ts +23 -0
  177. package/template/packages/mail/src/index.ts +246 -0
  178. package/template/packages/mail/tsconfig.json +5 -0
  179. package/template/packages/notifications/package.json +16 -0
  180. package/template/packages/notifications/src/index.test.ts +9 -0
  181. package/template/packages/notifications/src/index.ts +5 -0
  182. package/template/packages/notifications/tsconfig.json +5 -0
  183. package/template/packages/payments/package.json +15 -0
  184. package/template/packages/payments/src/index.ts +256 -0
  185. package/template/packages/payments/tsconfig.json +9 -0
  186. package/template/packages/permissions/package.json +17 -0
  187. package/template/packages/permissions/src/blueprints.js +57 -0
  188. package/template/packages/permissions/src/blueprints.test.ts +62 -0
  189. package/template/packages/permissions/src/blueprints.ts +89 -0
  190. package/template/packages/permissions/src/index.js +11 -0
  191. package/template/packages/permissions/src/index.test.ts +34 -0
  192. package/template/packages/permissions/src/index.ts +22 -0
  193. package/template/packages/permissions/tsconfig.json +8 -0
  194. package/template/packages/plugin-sdk/package.json +26 -0
  195. package/template/packages/plugin-sdk/src/hooks.ts +135 -0
  196. package/template/packages/plugin-sdk/src/index.ts +42 -0
  197. package/template/packages/plugin-sdk/src/sdk.test.ts +13 -0
  198. package/template/packages/plugin-sdk/tsconfig.json +8 -0
  199. package/template/packages/plugin-sdk/vitest.config.ts +5 -0
  200. package/template/packages/queue/package.json +16 -0
  201. package/template/packages/queue/src/index.test.ts +12 -0
  202. package/template/packages/queue/src/index.ts +6 -0
  203. package/template/packages/queue/tsconfig.json +5 -0
  204. package/template/packages/resource/package.json +17 -0
  205. package/template/packages/resource/src/index.js +177 -0
  206. package/template/packages/resource/src/index.test.ts +151 -0
  207. package/template/packages/resource/src/index.ts +344 -0
  208. package/template/packages/resource/tsconfig.json +8 -0
  209. package/template/packages/storage/package.json +16 -0
  210. package/template/packages/storage/src/index.test.ts +10 -0
  211. package/template/packages/storage/src/index.ts +23 -0
  212. package/template/packages/storage/tsconfig.json +5 -0
  213. package/template/prisma/migrations/20260505151751_baseline_init_all_tables/migration.sql +371 -0
  214. package/template/prisma/migrations/migration_lock.toml +3 -0
  215. package/template/prisma/schema.prisma +291 -0
  216. package/template/prisma/seed.ts +217 -0
@@ -0,0 +1,118 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ // Helper: encode a JWT-like payload for testing
4
+ function fakeJwt(payload: Record<string, unknown>): string {
5
+ const part = Buffer.from(JSON.stringify(payload)).toString("base64url");
6
+ return `header.${part}.sig`;
7
+ }
8
+
9
+ describe("api client", () => {
10
+ afterEach(() => {
11
+ vi.unstubAllGlobals();
12
+ vi.restoreAllMocks();
13
+ vi.resetModules();
14
+ });
15
+
16
+ it("token returns null without document (SSR context)", async () => {
17
+ const { token } = await import("./tokens");
18
+ expect(token()).toBeNull();
19
+ });
20
+
21
+ it("token reads from document.cookie in browser", async () => {
22
+ const cookieValue = `oajs_at=${encodeURIComponent("my-access-token")}`;
23
+ vi.stubGlobal("document", { cookie: cookieValue });
24
+ const { token } = await import("./tokens");
25
+ expect(token()).toBe("my-access-token");
26
+ });
27
+
28
+ it("api parses JSON on success", async () => {
29
+ vi.stubGlobal(
30
+ "fetch",
31
+ vi.fn().mockResolvedValue({
32
+ ok: true,
33
+ json: vi.fn().mockResolvedValue({ ok: true })
34
+ })
35
+ );
36
+ const { api } = await import("./api");
37
+ const body = await api<{ ok: boolean }>("/test");
38
+ expect(body.ok).toBe(true);
39
+ });
40
+
41
+ it("api throws with message on error response", async () => {
42
+ vi.stubGlobal(
43
+ "fetch",
44
+ vi.fn().mockResolvedValue({
45
+ ok: false,
46
+ statusText: "Bad",
47
+ json: vi.fn().mockResolvedValue({ message: "Nope" })
48
+ })
49
+ );
50
+ const { api } = await import("./api");
51
+ await expect(api("/x")).rejects.toThrow("Nope");
52
+ });
53
+
54
+ it("isAccessTokenFresh returns false for malformed token", async () => {
55
+ const { isTokenFresh } = await import("./tokens");
56
+ expect(isTokenFresh("bad")).toBe(false);
57
+ });
58
+
59
+ it("isAccessTokenFresh returns true for a far-future token", async () => {
60
+ vi.stubGlobal("atob", (v: string) => Buffer.from(v, "base64").toString("utf-8"));
61
+ const { isTokenFresh } = await import("./tokens");
62
+ const jwt = fakeJwt({ exp: 9_999_999_999 });
63
+ expect(isTokenFresh(jwt)).toBe(true);
64
+ });
65
+
66
+ it("api refreshes token on 401 via BFF /api/auth/refresh route", async () => {
67
+ const locationAssign = vi.fn();
68
+ const freshJwt = fakeJwt({ exp: 9_999_999_999 });
69
+
70
+ // Simulate document.cookie returning a fresh access token
71
+ let cookieStore = `oajs_at=${encodeURIComponent(freshJwt)}; oajs_rt=${encodeURIComponent("rt-token")}`;
72
+ const cookieDescriptor = { get: () => cookieStore, set: (v: string) => { cookieStore = v; } };
73
+ vi.stubGlobal("document", Object.defineProperty({}, "cookie", cookieDescriptor));
74
+ vi.stubGlobal("atob", (v: string) => Buffer.from(v, "base64").toString("utf-8"));
75
+ vi.stubGlobal("window", {
76
+ location: { pathname: "/dashboard", assign: locationAssign }
77
+ });
78
+
79
+ const fetchMock = vi
80
+ .fn()
81
+ // First call: original request → 401
82
+ .mockResolvedValueOnce({ ok: false, status: 401, statusText: "Unauthorized", json: vi.fn().mockResolvedValue({ message: "Unauthorized" }) })
83
+ // Second call: BFF /api/auth/refresh → ok
84
+ .mockResolvedValueOnce({ ok: true, status: 200, json: vi.fn().mockResolvedValue({ ok: true }) })
85
+ // Third call: retry original → 200
86
+ .mockResolvedValueOnce({ ok: true, status: 200, json: vi.fn().mockResolvedValue({ data: "result" }) });
87
+ vi.stubGlobal("fetch", fetchMock);
88
+
89
+ const { api } = await import("./api");
90
+ const response = await api<{ data: string }>("/admin/resources/overview");
91
+ expect(response.data).toBe("result");
92
+ expect(locationAssign).not.toHaveBeenCalled();
93
+ });
94
+
95
+ it("api clears cookies and redirects to login when all refresh attempts fail", async () => {
96
+ const locationAssign = vi.fn();
97
+ const freshJwt = fakeJwt({ exp: 9_999_999_999 });
98
+ let cookieStore = `oajs_at=${encodeURIComponent(freshJwt)}; oajs_rt=${encodeURIComponent("rt")}`;
99
+ const cookieDescriptor = { get: () => cookieStore, set: (v: string) => { cookieStore = v; } };
100
+ vi.stubGlobal("document", Object.defineProperty({}, "cookie", cookieDescriptor));
101
+ vi.stubGlobal("atob", (v: string) => Buffer.from(v, "base64").toString("utf-8"));
102
+ vi.stubGlobal("window", { location: { pathname: "/dashboard", assign: locationAssign } });
103
+
104
+ const fetchMock = vi
105
+ .fn()
106
+ // Original request → 401
107
+ .mockResolvedValueOnce({ ok: false, status: 401, statusText: "Unauthorized", json: vi.fn().mockResolvedValue({ message: "Unauthorized" }) })
108
+ // BFF /api/auth/refresh → fails
109
+ .mockResolvedValueOnce({ ok: false, status: 401, json: vi.fn().mockResolvedValue({ message: "No refresh" }) })
110
+ // Direct NestJS /auth/refresh fallback → also fails
111
+ .mockResolvedValueOnce({ ok: false, status: 401, json: vi.fn().mockResolvedValue({ message: "No refresh direct" }) });
112
+ vi.stubGlobal("fetch", fetchMock);
113
+
114
+ const { api } = await import("./api");
115
+ await expect(api("/admin/resources/overview")).rejects.toThrow("Unauthorized");
116
+ expect(locationAssign).toHaveBeenCalledWith("/login");
117
+ });
118
+ });
@@ -0,0 +1,135 @@
1
+ import { getUiLocale } from "./locale";
2
+ import {
3
+ token,
4
+ refreshToken,
5
+ setTokenCookies,
6
+ clearTokenCookies,
7
+ isTokenFresh
8
+ } from "./tokens";
9
+
10
+ const rawApi = process.env.NEXT_PUBLIC_API_URL;
11
+ export const API_URL =
12
+ typeof rawApi === "string" && rawApi.trim().length > 0 ? rawApi.trim() : "http://localhost:4000";
13
+
14
+ export type ResourceMeta = {
15
+ name: string;
16
+ label: string;
17
+ icon?: string;
18
+ titleField?: string;
19
+ permissions: Record<string, string>;
20
+ fields: Record<
21
+ string,
22
+ {
23
+ type: string;
24
+ label?: string;
25
+ list?: boolean;
26
+ create?: boolean;
27
+ edit?: boolean;
28
+ required?: boolean;
29
+ sortable?: boolean;
30
+ searchable?: boolean;
31
+ filterable?: boolean;
32
+ sensitive?: boolean;
33
+ resource?: string;
34
+ displayField?: string;
35
+ options?: string[];
36
+ }
37
+ >;
38
+ actions?: Record<string, { label: string; variant?: string; confirm?: boolean; permission: string }>;
39
+ i18n?: { defaultLocale?: string; locales?: readonly string[] };
40
+ seo?: { public?: boolean; slugField?: string; pathPattern?: string; titleField?: string; descriptionField?: string };
41
+ };
42
+
43
+ // Re-export for backward compat and convenience
44
+ export { token, isTokenFresh as isAccessTokenFresh };
45
+
46
+ /** True when the stored access token exists and has not expired (with 5-second buffer). */
47
+ export function hasUsableAccessToken(): boolean {
48
+ return isTokenFresh(token());
49
+ }
50
+
51
+ // ──────────────────────────────────────────────
52
+ // Locale helper
53
+ // ──────────────────────────────────────────────
54
+
55
+ function withAdminLocale(path: string): string {
56
+ if (!path.startsWith("/admin/resources")) return path;
57
+ const loc = getUiLocale();
58
+ const sep = path.includes("?") ? "&" : "?";
59
+ return `${path}${sep}locale=${encodeURIComponent(loc)}`;
60
+ }
61
+
62
+ // ──────────────────────────────────────────────
63
+ // Refresh flow (server-side BFF or direct fallback)
64
+ // ──────────────────────────────────────────────
65
+
66
+ async function tryRefreshToken(): Promise<boolean> {
67
+ if (typeof window === "undefined") return false;
68
+
69
+ // Prefer the Next.js BFF route (same-origin, handles cookie setting)
70
+ const bffRes = await fetch("/api/auth/refresh", { method: "POST" }).catch(() => null);
71
+ if (bffRes?.ok) return true;
72
+
73
+ // Direct NestJS fallback (e.g. in dev when BFF route is unavailable)
74
+ const rt = refreshToken();
75
+ if (!rt) return false;
76
+ const res = await fetch(`${API_URL}/auth/refresh`, {
77
+ method: "POST",
78
+ headers: { "content-type": "application/json" },
79
+ body: JSON.stringify({ refreshToken: rt, realm: "admin" })
80
+ }).catch(() => null);
81
+ const data = (await res?.json().catch(() => ({}))) as { accessToken?: string; refreshToken?: string };
82
+ if (!res?.ok || !data.accessToken || !data.refreshToken) return false;
83
+ setTokenCookies(data.accessToken, data.refreshToken);
84
+ return true;
85
+ }
86
+
87
+ // ──────────────────────────────────────────────
88
+ // Core fetch wrapper
89
+ // ──────────────────────────────────────────────
90
+
91
+ export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
92
+ const url = `${API_URL}${withAdminLocale(path)}`;
93
+ const response = await requestWithAuthRetry(url, options);
94
+ if (!response.ok) {
95
+ const error = await response.json().catch(() => ({ message: response.statusText }));
96
+ throw new Error((error as { message?: string }).message ?? "Request failed");
97
+ }
98
+ return response.json() as Promise<T>;
99
+ }
100
+
101
+ async function requestWithAuthRetry(url: string, options: RequestInit): Promise<Response> {
102
+ const method = (options.method ?? "GET").toUpperCase();
103
+ const body =
104
+ options.body ??
105
+ (method !== "GET" && method !== "HEAD" && method !== "DELETE" ? "{}" : undefined);
106
+
107
+ const makeRequest = (tok: string | null) =>
108
+ fetch(url, {
109
+ ...options,
110
+ ...(body !== undefined ? { body } : {}),
111
+ headers: {
112
+ "content-type": "application/json",
113
+ ...(tok ? { authorization: `Bearer ${tok}` } : {}),
114
+ ...options.headers
115
+ }
116
+ });
117
+
118
+ const res = await makeRequest(hasUsableAccessToken() ? token() : null);
119
+
120
+ if (
121
+ res.status === 401 &&
122
+ typeof window !== "undefined" &&
123
+ !url.includes("/auth/login") &&
124
+ !url.includes("/auth/refresh")
125
+ ) {
126
+ const refreshed = await tryRefreshToken();
127
+ if (refreshed) return makeRequest(token());
128
+
129
+ clearTokenCookies();
130
+ if (!window.location.pathname.startsWith("/login")) {
131
+ window.location.assign("/login");
132
+ }
133
+ }
134
+ return res;
135
+ }
@@ -0,0 +1,79 @@
1
+ // @vitest-environment jsdom
2
+ import { describe, expect, it, vi, afterEach } from "vitest";
3
+
4
+ function fakeJwt(payload: Record<string, unknown>): string {
5
+ const part = Buffer.from(JSON.stringify(payload)).toString("base64url");
6
+ return `header.${part}.sig`;
7
+ }
8
+
9
+ describe("auth flow e2e-like (cookie-based tokens)", () => {
10
+ afterEach(() => {
11
+ vi.unstubAllGlobals();
12
+ vi.restoreAllMocks();
13
+ vi.resetModules();
14
+ });
15
+
16
+ it("expired token + failed refresh → clears cookies and redirects to login", async () => {
17
+ const locationAssign = vi.fn();
18
+
19
+ // Expired access token (exp in the past)
20
+ const expiredJwt = fakeJwt({ exp: 10 });
21
+
22
+ let cookieStore = `oajs_at=${encodeURIComponent(expiredJwt)}; oajs_rt=${encodeURIComponent("refresh-token")}`;
23
+ const cookieDescriptor = { get: () => cookieStore, set: (v: string) => { cookieStore = v; } };
24
+ vi.stubGlobal("document", Object.defineProperty({}, "cookie", cookieDescriptor));
25
+ vi.stubGlobal("atob", (v: string) => Buffer.from(v, "base64").toString("utf-8"));
26
+ vi.stubGlobal("window", { location: { pathname: "/dashboard", assign: locationAssign } });
27
+
28
+ vi.stubGlobal(
29
+ "fetch",
30
+ vi
31
+ .fn()
32
+ // Original request → 401 (no auth header since token is expired)
33
+ .mockResolvedValueOnce({
34
+ ok: false,
35
+ status: 401,
36
+ statusText: "Unauthorized",
37
+ json: vi.fn().mockResolvedValue({ message: "Unauthorized" })
38
+ })
39
+ // BFF /api/auth/refresh → fails
40
+ .mockResolvedValueOnce({
41
+ ok: false,
42
+ status: 401,
43
+ statusText: "Unauthorized",
44
+ json: vi.fn().mockResolvedValue({ message: "Bad refresh" })
45
+ })
46
+ // Direct NestJS /auth/refresh fallback → also fails
47
+ .mockResolvedValueOnce({
48
+ ok: false,
49
+ status: 401,
50
+ statusText: "Unauthorized",
51
+ json: vi.fn().mockResolvedValue({ message: "Bad refresh direct" })
52
+ })
53
+ );
54
+
55
+ const { api } = await import("./api");
56
+ await expect(api("/admin/resources/overview")).rejects.toThrow("Unauthorized");
57
+ expect(locationAssign).toHaveBeenCalledWith("/login");
58
+ });
59
+
60
+ it("fresh token succeeds without redirect", async () => {
61
+ const freshJwt = fakeJwt({ exp: 9_999_999_999 });
62
+ const cookieStore = `oajs_at=${encodeURIComponent(freshJwt)}`;
63
+ vi.stubGlobal("document", { cookie: cookieStore });
64
+ vi.stubGlobal("atob", (v: string) => Buffer.from(v, "base64").toString("utf-8"));
65
+
66
+ vi.stubGlobal(
67
+ "fetch",
68
+ vi.fn().mockResolvedValue({
69
+ ok: true,
70
+ status: 200,
71
+ json: vi.fn().mockResolvedValue({ rows: [] })
72
+ })
73
+ );
74
+
75
+ const { api } = await import("./api");
76
+ const result = await api<{ rows: unknown[] }>("/admin/resources/posts");
77
+ expect(result.rows).toEqual([]);
78
+ });
79
+ });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Public brand asset paths for the admin app.
3
+ * Assets are generated by `pnpm brand:assets` from `openadminjs-logo-new.png`.
4
+ * To regenerate, run `pnpm brand:assets` from the repo root.
5
+ */
6
+ export const BRAND = {
7
+ /** SVG favicon wrapper generated from logo mark */
8
+ favicon: "/brand/favicon.svg",
9
+ faviconPng: "/brand/openadminjs-icon-new.png",
10
+ appleTouch: "/brand/apple-touch-icon.png",
11
+ ogImage: "/brand/og-image.png",
12
+ logoNew: "/brand/openadminjs-logo-new.png",
13
+ logoMonochromePng: "/brand/openadminjs-logo-monochrome.png"
14
+ } as const;
@@ -0,0 +1,49 @@
1
+ const STORAGE_KEY = "openadminjs.locale";
2
+
3
+ /** BCP-47 locale for admin labels (must match resource `i18n.locales` where defined). */
4
+ export function getUiLocale(): string {
5
+ if (typeof window === "undefined") return "en";
6
+ try {
7
+ return window.localStorage.getItem(STORAGE_KEY) ?? "en";
8
+ } catch {
9
+ return "en";
10
+ }
11
+ }
12
+
13
+ export function setUiLocale(locale: string): void {
14
+ if (typeof window === "undefined") return;
15
+ if (!SUPPORTED_UI_LOCALES.includes(locale as SupportedUiLocale)) return;
16
+ try {
17
+ window.localStorage.setItem(STORAGE_KEY, locale);
18
+ } catch {
19
+ /* storage unavailable in this context */
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Extend this tuple to add more admin UI locales.
25
+ * Each entry must match the `i18n.locales` array in the relevant `defineResource` calls
26
+ * AND have a corresponding translation block in the resource's `i18n.translations` map.
27
+ *
28
+ * Example to add French:
29
+ * 1. Add "fr" here
30
+ * 2. Add `fr: { label: "Articles" }` to each resource's `i18n.translations`
31
+ * 3. Re-export the locale from `packages/core` if you need typed resource translation helpers
32
+ */
33
+ export const SUPPORTED_UI_LOCALES = ["en", "ru"] as const;
34
+ export type SupportedUiLocale = (typeof SUPPORTED_UI_LOCALES)[number];
35
+
36
+ /** Human-readable display names for locale codes. Add an entry when adding a new locale. */
37
+ export const LOCALE_LABELS: Record<string, string> = {
38
+ en: "English",
39
+ ru: "Русский"
40
+ };
41
+
42
+ /**
43
+ * Programmatically register a new locale at runtime (e.g. from a plugin or user settings page).
44
+ * The locale is persisted to localStorage; the page must be refreshed to apply label changes.
45
+ */
46
+ export function registerAndApplyLocale(locale: string): void {
47
+ if (typeof window === "undefined") return;
48
+ window.localStorage.setItem(STORAGE_KEY, locale);
49
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Isomorphic token helpers.
3
+ *
4
+ * Server components / Route Handlers: use `getServerTokens()`.
5
+ * Client components / browser code: use `token()`, `setTokenCookies()`, `clearTokenCookies()`.
6
+ * Middleware: reads cookies via `request.cookies.get()` directly.
7
+ *
8
+ * Tokens are stored as non-HttpOnly Lax-SameSite cookies so they are:
9
+ * - Accessible from Next.js middleware (server-side SSR redirect)
10
+ * - Accessible from server components via `cookies()` from `next/headers`
11
+ * - Readable by client JS to build Authorization headers for cross-origin NestJS calls
12
+ *
13
+ * NOTE: If you switch to a same-origin proxy setup (all API calls through Next.js Route Handlers)
14
+ * you can safely upgrade to `HttpOnly` by removing `token()` from client code and reading
15
+ * from the cookie only server-side.
16
+ */
17
+
18
+ export const TOKEN_COOKIE_AT = "oajs_at";
19
+ export const TOKEN_COOKIE_RT = "oajs_rt";
20
+
21
+ /** Cookie max-age in seconds — 7 days */
22
+ const MAX_AGE = 60 * 60 * 24 * 7;
23
+
24
+ // ──────────────────────────────────────────────
25
+ // Client-side helpers (browser only)
26
+ // ──────────────────────────────────────────────
27
+
28
+ function parseCookieValue(cookieStr: string, key: string): string | null {
29
+ const match = cookieStr.match(new RegExp(`(?:^|; )${key}=([^;]*)`));
30
+ const value = match?.[1];
31
+ return value ? decodeURIComponent(value) : null;
32
+ }
33
+
34
+ /** Read access token from cookie (client-side). */
35
+ export function token(): string | null {
36
+ if (typeof document === "undefined") return null;
37
+ return parseCookieValue(document.cookie, TOKEN_COOKIE_AT);
38
+ }
39
+
40
+ /** Read refresh token from cookie (client-side). */
41
+ export function refreshToken(): string | null {
42
+ if (typeof document === "undefined") return null;
43
+ return parseCookieValue(document.cookie, TOKEN_COOKIE_RT);
44
+ }
45
+
46
+ /** Persist access + refresh tokens to cookies (client-side, called after login/refresh). */
47
+ export function setTokenCookies(accessToken: string, refreshTokenValue: string): void {
48
+ if (typeof document === "undefined") return;
49
+ const opts = `path=/; max-age=${MAX_AGE}; SameSite=Lax`;
50
+ document.cookie = `${TOKEN_COOKIE_AT}=${encodeURIComponent(accessToken)}; ${opts}`;
51
+ document.cookie = `${TOKEN_COOKIE_RT}=${encodeURIComponent(refreshTokenValue)}; ${opts}`;
52
+ }
53
+
54
+ /** Remove tokens (client-side logout or failed refresh). */
55
+ export function clearTokenCookies(): void {
56
+ if (typeof document === "undefined") return;
57
+ document.cookie = `${TOKEN_COOKIE_AT}=; path=/; max-age=0; SameSite=Lax`;
58
+ document.cookie = `${TOKEN_COOKIE_RT}=; path=/; max-age=0; SameSite=Lax`;
59
+ }
60
+
61
+ // ──────────────────────────────────────────────
62
+ // Server-side helpers (Server Components / Route Handlers)
63
+ // ──────────────────────────────────────────────
64
+
65
+ /** Read tokens from cookies in Server Components or Route Handlers. */
66
+ export async function getServerTokens(): Promise<{ accessToken: string | null; refreshToken: string | null }> {
67
+ const { cookies } = await import("next/headers");
68
+ const jar = await cookies();
69
+ return {
70
+ accessToken: jar.get(TOKEN_COOKIE_AT)?.value ?? null,
71
+ refreshToken: jar.get(TOKEN_COOKIE_RT)?.value ?? null
72
+ };
73
+ }
74
+
75
+ // ──────────────────────────────────────────────
76
+ // Shared JWT freshness check (used by both client and middleware Edge runtime)
77
+ // ──────────────────────────────────────────────
78
+
79
+ export function isTokenFresh(value: string | null | undefined): boolean {
80
+ if (!value) return false;
81
+ const [, payloadPart] = value.split(".");
82
+ if (!payloadPart) return false;
83
+ try {
84
+ const base64 = payloadPart.replace(/-/g, "+").replace(/_/g, "/");
85
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
86
+ const json = typeof atob !== "undefined" ? atob(padded) : Buffer.from(padded, "base64").toString("utf-8");
87
+ const payload = JSON.parse(json) as { exp?: number };
88
+ if (typeof payload.exp !== "number") return true;
89
+ return payload.exp > Math.floor(Date.now() / 1000) + 5;
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
@@ -0,0 +1,58 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { TOKEN_COOKIE_AT, isTokenFresh } from "./lib/tokens";
3
+
4
+ /** Paths that don't require authentication */
5
+ const PUBLIC_PREFIXES = ["/login", "/api/auth", "/_next", "/favicon", "/brand"];
6
+
7
+ function isPublic(pathname: string): boolean {
8
+ return PUBLIC_PREFIXES.some((p) => pathname.startsWith(p));
9
+ }
10
+
11
+ export async function middleware(req: NextRequest): Promise<NextResponse> {
12
+ const { pathname } = req.nextUrl;
13
+
14
+ if (isPublic(pathname)) return NextResponse.next();
15
+
16
+ const at = req.cookies.get(TOKEN_COOKIE_AT)?.value;
17
+
18
+ if (isTokenFresh(at)) return NextResponse.next();
19
+
20
+ // Access token missing or expired — try a server-side refresh before redirecting
21
+ const rtCookie = req.cookies.get("oajs_rt")?.value;
22
+ if (rtCookie) {
23
+ const refreshUrl = new URL("/api/auth/refresh", req.url);
24
+ const refreshRes = await fetch(refreshUrl.toString(), {
25
+ method: "POST",
26
+ headers: { cookie: req.headers.get("cookie") ?? "" }
27
+ }).catch(() => null);
28
+
29
+ if (refreshRes?.ok) {
30
+ // Forward the new Set-Cookie from the refresh route to the browser,
31
+ // then let the original request through (the browser will carry new cookies on next request)
32
+ const next = NextResponse.next();
33
+ refreshRes.headers.getSetCookie?.().forEach((c) => next.headers.append("set-cookie", c));
34
+ return next;
35
+ }
36
+ }
37
+
38
+ // No valid token — redirect to /login with the original path as `next`
39
+ const loginUrl = req.nextUrl.clone();
40
+ loginUrl.pathname = "/login";
41
+ loginUrl.searchParams.set("next", pathname);
42
+ const redirect = NextResponse.redirect(loginUrl);
43
+
44
+ // Clear stale cookies on the way out
45
+ redirect.cookies.set(TOKEN_COOKIE_AT, "", { path: "/", maxAge: 0 });
46
+ redirect.cookies.set("oajs_rt", "", { path: "/", maxAge: 0 });
47
+ return redirect;
48
+ }
49
+
50
+ export const config = {
51
+ /**
52
+ * Run middleware on all routes except:
53
+ * - Static assets (_next/static, _next/image)
54
+ * - Public brand/favicon files
55
+ * - API routes are handled separately
56
+ */
57
+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico|brand/|icons/).*)"]
58
+ };
@@ -0,0 +1,6 @@
1
+ /// <reference types="next" />
2
+ /// <reference types="next/image-types/global" />
3
+ /// <reference path="./.next/types/routes.d.ts" />
4
+
5
+ // NOTE: This file should not be edited
6
+ // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
@@ -0,0 +1,7 @@
1
+ const nextConfig = {
2
+ eslint: {
3
+ ignoreDuringBuilds: true
4
+ }
5
+ };
6
+
7
+ export default nextConfig;
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@openadminjs/admin",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "next dev --port 3000",
8
+ "build": "next build",
9
+ "start": "next start --port 3000",
10
+ "lint": "tsc -p tsconfig.json --noEmit",
11
+ "typecheck": "tsc -p tsconfig.json --noEmit",
12
+ "test": "vitest run"
13
+ },
14
+ "dependencies": {
15
+ "@hookform/resolvers": "^3.9.1",
16
+ "@tanstack/react-query": "^5.62.7",
17
+ "@tanstack/react-table": "^8.20.6",
18
+ "clsx": "^2.1.1",
19
+ "lucide-react": "^0.468.0",
20
+ "next": "^15.1.0",
21
+ "next-intl": "^4.11.0",
22
+ "next-themes": "^0.4.4",
23
+ "react": "^19.0.0",
24
+ "react-dom": "^19.0.0",
25
+ "react-hook-form": "^7.54.2",
26
+ "recharts": "^3.8.1",
27
+ "sonner": "^1.7.1",
28
+ "tailwind-merge": "^2.5.5",
29
+ "zod": "^3.24.1"
30
+ },
31
+ "devDependencies": {
32
+ "@testing-library/jest-dom": "^6.9.1",
33
+ "@testing-library/react": "^16.3.2",
34
+ "@types/node": "^22.10.2",
35
+ "@types/react": "^19.0.1",
36
+ "@types/react-dom": "^19.0.2",
37
+ "autoprefixer": "^10.4.20",
38
+ "jsdom": "^29.1.1",
39
+ "postcss": "^8.4.49",
40
+ "tailwindcss": "^3.4.17",
41
+ "typescript": "^5.7.2",
42
+ "vitest": "^2.1.8"
43
+ }
44
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {}
5
+ }
6
+ };
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512" role="img" aria-label="OpenAdminJS"><image xlink:href="openadminjs-icon-new.png" href="openadminjs-icon-new.png" width="512" height="512" preserveAspectRatio="xMidYMid meet"/></svg>
@@ -0,0 +1,37 @@
1
+ import type { Config } from "tailwindcss";
2
+
3
+ const config: Config = {
4
+ darkMode: ["class"],
5
+ content: ["./app/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}", "./lib/**/*.{ts,tsx}"],
6
+ theme: {
7
+ extend: {
8
+ fontFamily: {
9
+ sans: ["Inter", "ui-sans-serif", "system-ui", "-apple-system", "sans-serif"]
10
+ },
11
+ colors: {
12
+ brand: {
13
+ DEFAULT: "#2454FF",
14
+ hover: "#1A3DCC",
15
+ soft: "#EEF3FF",
16
+ border: "#C7D2FE",
17
+ teal: "#0EA5A4",
18
+ "teal-soft": "#E9FBFA"
19
+ }
20
+ },
21
+ boxShadow: {
22
+ card: "0 1px 3px rgba(0,0,0,0.04), 0 8px 24px rgba(0,0,0,0.04)",
23
+ "card-hover": "0 4px 8px rgba(0,0,0,0.06), 0 16px 40px rgba(0,0,0,0.08)",
24
+ "btn-blue": "0 4px 14px rgba(36,84,255,0.28)",
25
+ "btn-blue-hover": "0 6px 20px rgba(36,84,255,0.4)",
26
+ "focus-ring": "0 0 0 3px rgba(36,84,255,0.12)"
27
+ },
28
+ borderRadius: {
29
+ "2xl": "1rem",
30
+ "3xl": "1.25rem"
31
+ }
32
+ }
33
+ },
34
+ plugins: []
35
+ };
36
+
37
+ export default config;