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
@@ -0,0 +1,3 @@
1
+ import type { DatabaseDriver } from "./create-project.js";
2
+ export declare function renderSchemaForProvider(schema: string, provider: DatabaseDriver): string;
3
+ export declare function schemaDatasourceProvider(schema: string): string | undefined;
@@ -0,0 +1,33 @@
1
+ /** SQLite (Prisma 6.2+) and MySQL support native JSON, but not scalar lists.
2
+ * Transform only model field type tokens, never values, comments or relations.
3
+ */
4
+ const SCALAR_TYPES = new Set(["String", "Boolean", "Int", "BigInt", "Float", "Decimal", "DateTime", "Bytes", "Json"]);
5
+ export function renderSchemaForProvider(schema, provider) {
6
+ if (provider === "postgresql")
7
+ return schema;
8
+ let model = false;
9
+ let blockComment = false;
10
+ return schema.split(/(\r?\n)/).map(line => {
11
+ if (/^\s*\/\*/.test(line))
12
+ blockComment = true;
13
+ if (blockComment) {
14
+ if (line.includes("*/"))
15
+ blockComment = false;
16
+ return line;
17
+ }
18
+ if (/^\s*(?:model|type)\s+\w+\s*\{/.test(line)) {
19
+ model = true;
20
+ return line;
21
+ }
22
+ if (/^\s*}\s*(?:\/\/.*)?$/.test(line)) {
23
+ model = false;
24
+ return line;
25
+ }
26
+ if (!model)
27
+ return line;
28
+ return line.replace(/^(\s*[A-Za-z_]\w*\s+)([A-Za-z_]\w*)\[\](?=\s|$)/, (match, prefix, type) => SCALAR_TYPES.has(type) ? prefix + "Json" : match);
29
+ }).join("");
30
+ }
31
+ export function schemaDatasourceProvider(schema) {
32
+ return schema.match(/datasource\s+\w+\s*\{[^}]*?provider\s*=\s*"([^"]+)"/m)?.[1];
33
+ }
@@ -1,2 +1,3 @@
1
1
  /** PascalCase model name → kebab segment used for `*.resource.ts` file base. */
2
2
  export declare function modelNameToResourceSlug(modelName: string): string;
3
+ export declare function pluralResourceSlug(slug: string): string;
@@ -2,3 +2,10 @@
2
2
  export function modelNameToResourceSlug(modelName) {
3
3
  return modelName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
4
4
  }
5
+ export function pluralResourceSlug(slug) {
6
+ if (/(?:[^aeiou])y$/i.test(slug))
7
+ return slug.slice(0, -1) + "ies";
8
+ if (/(s|x|z|ch|sh)$/i.test(slug))
9
+ return slug + "es";
10
+ return slug + "s";
11
+ }
@@ -0,0 +1,16 @@
1
+ type Versions = Record<string, string>;
2
+ type Flags = {
3
+ apply?: boolean;
4
+ archives?: string;
5
+ acceptLocalRuntime?: boolean;
6
+ initial?: boolean;
7
+ };
8
+ export declare function migrateRuntime(root: string, template: string, flags?: Flags): {
9
+ mode: string;
10
+ versions: Versions;
11
+ conflicts: string[];
12
+ plannedManifests: string[];
13
+ backup: string;
14
+ applied: boolean;
15
+ };
16
+ export {};
@@ -0,0 +1,138 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, writeFileSync, mkdirSync, renameSync, rmSync, copyFileSync } from "node:fs";
2
+ import { resolve, join, dirname, relative } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ const sha = (data) => createHash("sha256").update(data).digest("hex");
5
+ const json = (path) => JSON.parse(readFileSync(path, "utf8"));
6
+ const write = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + "\n");
7
+ const localName = (name) => name.slice("@openadminjs/".length);
8
+ export function migrateRuntime(root, template, flags = {}) {
9
+ const versions = json(join(template, "runtime-versions.json"));
10
+ const known = Object.keys(versions);
11
+ if (known.some(n => !/^@openadminjs\/[a-z-]+$/.test(n) || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/.test(versions[n])))
12
+ throw Error("Invalid bundled runtime versions");
13
+ const backup = join(root, ".openadminjs-runtime-backup"), archiveDir = join(root, ".openadminjs-runtime");
14
+ if (existsSync(backup) || existsSync(archiveDir))
15
+ throw Error("Runtime migration already performed; preserve or restore the backup before retrying");
16
+ const rootPkg = json(join(root, "package.json")), tsPath = join(root, "tsconfig.base.json"), ts = json(tsPath);
17
+ const conflicts = [];
18
+ const packageDirs = [];
19
+ function compare(local, expected) {
20
+ if (!existsSync(local) || lstatSync(local).isSymbolicLink()) {
21
+ conflicts.push(relative(root, local));
22
+ return;
23
+ }
24
+ for (const e of readdirSync(local, { withFileTypes: true })) {
25
+ if (["dist", "node_modules", "coverage", ".turbo"].includes(e.name) || e.name.endsWith(".tsbuildinfo"))
26
+ continue;
27
+ const a = join(local, e.name), b = join(expected, e.name);
28
+ if (e.isSymbolicLink()) {
29
+ conflicts.push(relative(root, a));
30
+ continue;
31
+ }
32
+ if (e.isDirectory()) {
33
+ if (!existsSync(b))
34
+ conflicts.push(relative(root, a));
35
+ else
36
+ compare(a, b);
37
+ }
38
+ else if (!existsSync(b) || sha(readFileSync(a)) !== sha(readFileSync(b)))
39
+ conflicts.push(relative(root, a));
40
+ }
41
+ }
42
+ for (const name of known) {
43
+ const local = join(root, "packages", localName(name));
44
+ if (existsSync(local)) {
45
+ if (lstatSync(local).isSymbolicLink())
46
+ throw Error("Symlinked runtime directory");
47
+ packageDirs.push(local);
48
+ if (!flags.initial)
49
+ compare(local, join(template, "packages", localName(name)));
50
+ }
51
+ }
52
+ if (!packageDirs.length)
53
+ throw Error("No copied runtime source directories found");
54
+ const manifests = [join(root, "package.json"), ...["apps", "examples"].flatMap(dir => existsSync(join(root, dir)) ? readdirSync(join(root, dir), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => join(root, dir, e.name, "package.json")).filter(existsSync) : [])];
55
+ const updates = new Map();
56
+ for (const file of manifests) {
57
+ const p = json(file);
58
+ for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
59
+ if (!p[section])
60
+ continue;
61
+ for (const name of known)
62
+ if (name in p[section])
63
+ p[section][name] = versions[name];
64
+ }
65
+ if (file === manifests[0]) {
66
+ p.dependencies = { ...p.dependencies, ...versions };
67
+ // Packages are pinned independently; no workspace wildcard for these dependencies.
68
+ if (flags.archives) {
69
+ if (!existsSync(join(root, "pnpm-workspace.yaml")))
70
+ throw Error("Candidate archive mode requires pnpm");
71
+ p.pnpm = { ...p.pnpm, overrides: { ...p.pnpm?.overrides, ...Object.fromEntries(known.map(name => [name, "file:./.openadminjs-runtime/" + localName(name) + ".tgz"])) } };
72
+ }
73
+ }
74
+ updates.set(file, p);
75
+ }
76
+ if (ts.compilerOptions?.paths)
77
+ for (const name of known)
78
+ delete ts.compilerOptions.paths[name];
79
+ updates.set(tsPath, ts);
80
+ const files = [];
81
+ if (flags.archives) {
82
+ const dir = resolve(flags.archives), manifest = json(join(dir, "runtime-manifest.json"));
83
+ for (const name of known) {
84
+ const entry = manifest[name];
85
+ if (!entry || entry.version !== versions[name] || entry.archive !== name.replace(/^@/, "").replace("/", "-") + "-" + entry.version + ".tgz" || !/^\w[\w.-]*\.tgz$/.test(entry.archive))
86
+ throw Error("Missing/mismatched archive " + name);
87
+ const source = join(dir, entry.archive);
88
+ if (sha(readFileSync(source)) !== entry.sha256)
89
+ throw Error("Archive checksum mismatch " + name);
90
+ files.push({ source, target: join(archiveDir, localName(name) + ".tgz") });
91
+ }
92
+ }
93
+ const result = { mode: flags.archives ? "archives" : "registry", versions, conflicts, plannedManifests: [...updates.keys()].map(p => relative(root, p)), backup: relative(root, backup), applied: false };
94
+ if (!flags.apply || conflicts.length && !flags.acceptLocalRuntime)
95
+ return result;
96
+ // All paths are constrained to known bundled package names. No DB or dependency installation.
97
+ mkdirSync(backup, { mode: 0o700 });
98
+ const saved = [], moved = [];
99
+ try {
100
+ for (const [file, data] of updates) {
101
+ const content = readFileSync(file);
102
+ const dest = join(backup, "manifests", relative(root, file));
103
+ mkdirSync(dirname(dest), { recursive: true });
104
+ writeFileSync(dest, content);
105
+ saved.push({ file, content });
106
+ write(file, data);
107
+ }
108
+ for (const from of packageDirs) {
109
+ const to = join(backup, "sources", relative(root, from));
110
+ mkdirSync(dirname(to), { recursive: true });
111
+ renameSync(from, to);
112
+ moved.push({ from, to });
113
+ }
114
+ if (files.length) {
115
+ mkdirSync(archiveDir);
116
+ for (const f of files)
117
+ copyFileSync(f.source, f.target);
118
+ }
119
+ write(join(backup, "migration.json"), { ...result, applied: true });
120
+ // Keep this backup out of Git and avoid accidental workspace discovery.
121
+ const ignore = join(root, ".gitignore");
122
+ if (existsSync(ignore) && !readFileSync(ignore, "utf8").includes(".openadminjs-runtime-backup/"))
123
+ writeFileSync(ignore, readFileSync(ignore, "utf8") + "\n.openadminjs-runtime-backup/\n");
124
+ if (flags.initial)
125
+ rmSync(backup, { recursive: true, force: true });
126
+ result.applied = true;
127
+ return result;
128
+ }
129
+ catch (e) {
130
+ for (const { from, to } of moved.reverse())
131
+ renameSync(to, from);
132
+ for (const { file, content } of saved)
133
+ writeFileSync(file, content);
134
+ rmSync(archiveDir, { recursive: true, force: true });
135
+ rmSync(backup, { recursive: true, force: true });
136
+ throw e;
137
+ }
138
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Generates a cryptographically secure secret suitable for JWT signing keys.
3
+ * Returns a URL-safe base64 string. 48 bytes → 64 base64url chars (~384 bits).
4
+ */
5
+ export declare function generateSecret(bytes?: number): string;
6
+ /** Minimum acceptable secret length (characters). */
7
+ export declare const MIN_SECRET_LENGTH = 32;
8
+ /**
9
+ * Estimates Shannon entropy (bits) of a string. Used to flag low-entropy
10
+ * secrets such as `aaaaaaaa...` that pass a naive length check.
11
+ */
12
+ export declare function shannonEntropyBits(value: string): number;
13
+ export type SecretWeakness = {
14
+ weak: boolean;
15
+ reason?: string;
16
+ };
17
+ /**
18
+ * Returns whether a secret is weak/predictable and why. A secret is weak when
19
+ * it is empty, a known placeholder, too short, or has insufficient entropy.
20
+ */
21
+ export declare function inspectSecret(value: string | undefined, label?: string): SecretWeakness;
22
+ export declare function isWeakSecret(value: string | undefined): boolean;
23
+ export declare const MIN_PASSWORD_LENGTH = 8;
24
+ export declare function inspectPassword(value: string | undefined): SecretWeakness;
@@ -0,0 +1,93 @@
1
+ import { randomBytes } from "node:crypto";
2
+ /**
3
+ * Generates a cryptographically secure secret suitable for JWT signing keys.
4
+ * Returns a URL-safe base64 string. 48 bytes → 64 base64url chars (~384 bits).
5
+ */
6
+ export function generateSecret(bytes = 48) {
7
+ return randomBytes(bytes).toString("base64url");
8
+ }
9
+ const WEAK_SECRET_VALUES = new Set([
10
+ "secret",
11
+ "changeme",
12
+ "change-me",
13
+ "change-me-to-a-long-random-secret",
14
+ "change-me-too",
15
+ "password",
16
+ "jwt",
17
+ "jwt-secret",
18
+ "test",
19
+ "test-jwt-secret",
20
+ "test-jwt-refresh-secret",
21
+ "dev",
22
+ "development"
23
+ ]);
24
+ /** Minimum acceptable secret length (characters). */
25
+ export const MIN_SECRET_LENGTH = 32;
26
+ /**
27
+ * Estimates Shannon entropy (bits) of a string. Used to flag low-entropy
28
+ * secrets such as `aaaaaaaa...` that pass a naive length check.
29
+ */
30
+ export function shannonEntropyBits(value) {
31
+ if (!value)
32
+ return 0;
33
+ const counts = new Map();
34
+ for (const ch of value)
35
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
36
+ let bitsPerChar = 0;
37
+ for (const count of counts.values()) {
38
+ const p = count / value.length;
39
+ bitsPerChar -= p * Math.log2(p);
40
+ }
41
+ return bitsPerChar * value.length;
42
+ }
43
+ /**
44
+ * Returns whether a secret is weak/predictable and why. A secret is weak when
45
+ * it is empty, a known placeholder, too short, or has insufficient entropy.
46
+ */
47
+ export function inspectSecret(value, label = "secret") {
48
+ const v = (value ?? "").trim();
49
+ if (!v)
50
+ return { weak: true, reason: `${label} is empty` };
51
+ if (WEAK_SECRET_VALUES.has(v.toLowerCase())) {
52
+ return { weak: true, reason: `${label} is a well-known default/placeholder value` };
53
+ }
54
+ if (v.length < MIN_SECRET_LENGTH) {
55
+ return { weak: true, reason: `${label} is shorter than ${MIN_SECRET_LENGTH} characters` };
56
+ }
57
+ if (shannonEntropyBits(v) < 64) {
58
+ return { weak: true, reason: `${label} has insufficient entropy` };
59
+ }
60
+ return { weak: false };
61
+ }
62
+ export function isWeakSecret(value) {
63
+ return inspectSecret(value).weak;
64
+ }
65
+ const COMMON_WEAK_PASSWORDS = new Set([
66
+ "admin",
67
+ "administrator",
68
+ "password",
69
+ "passw0rd",
70
+ "123456",
71
+ "12345678",
72
+ "changeme",
73
+ "change-me",
74
+ "letmein",
75
+ "welcome",
76
+ "qwerty",
77
+ "root",
78
+ "test",
79
+ "secret"
80
+ ]);
81
+ export const MIN_PASSWORD_LENGTH = 8;
82
+ export function inspectPassword(value) {
83
+ const v = value ?? "";
84
+ if (!v)
85
+ return { weak: true, reason: "password is empty" };
86
+ if (COMMON_WEAK_PASSWORDS.has(v.toLowerCase())) {
87
+ return { weak: true, reason: "password is a common/guessable value" };
88
+ }
89
+ if (v.length < MIN_PASSWORD_LENGTH) {
90
+ return { weak: true, reason: `password is shorter than ${MIN_PASSWORD_LENGTH} characters` };
91
+ }
92
+ return { weak: false };
93
+ }
@@ -0,0 +1,13 @@
1
+ export type Severity = "info" | "warning" | "critical";
2
+ export type Finding = {
3
+ id: string;
4
+ severity: Severity;
5
+ message: string;
6
+ };
7
+ export type SecurityReport = {
8
+ findings: Finding[];
9
+ ok: boolean;
10
+ };
11
+ export declare function runSecurityChecks(cwd: string, opts?: {
12
+ skipNetwork?: boolean;
13
+ }): SecurityReport;
@@ -0,0 +1,168 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+ import { inspectPassword, inspectSecret } from "./secrets.js";
5
+ function readFileSafe(path) {
6
+ try {
7
+ return readFileSync(path, "utf8");
8
+ }
9
+ catch {
10
+ return undefined;
11
+ }
12
+ }
13
+ function parseEnv(content) {
14
+ const env = {};
15
+ for (const line of content.split(/\r?\n/)) {
16
+ const trimmed = line.trim();
17
+ if (!trimmed || trimmed.startsWith("#"))
18
+ continue;
19
+ const eq = trimmed.indexOf("=");
20
+ if (eq < 0)
21
+ continue;
22
+ const key = trimmed.slice(0, eq).trim();
23
+ let value = trimmed.slice(eq + 1).trim();
24
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
25
+ value = value.slice(1, -1);
26
+ }
27
+ env[key] = value;
28
+ }
29
+ return env;
30
+ }
31
+ function gitignoreIgnoresEnv(cwd) {
32
+ const gi = readFileSafe(join(cwd, ".gitignore"));
33
+ if (!gi)
34
+ return false;
35
+ const lines = gi.split(/\r?\n/).map((l) => l.trim());
36
+ return lines.includes(".env") || lines.includes(".env.*") || lines.includes("*.env");
37
+ }
38
+ function scanForHardcodedSecrets(cwd) {
39
+ const hits = [];
40
+ const roots = [join(cwd, "apps"), join(cwd, "packages")].filter((d) => existsSync(d));
41
+ const patterns = [
42
+ [/(?:jwt[_-]?secret|refresh[_-]?secret)\s*[:=]\s*["'][^"']{6,}["']/i, "hardcoded JWT secret"],
43
+ [/(?:password|passwd)\s*[:=]\s*["'][^"']{4,}["']/i, "hardcoded password"],
44
+ [/(?:api[_-]?key|secret[_-]?key|access[_-]?token)\s*[:=]\s*["'][^"']{8,}["']/i, "hardcoded API key/token"]
45
+ ];
46
+ const stack = [...roots];
47
+ let scanned = 0;
48
+ while (stack.length && scanned < 4000) {
49
+ const current = stack.pop();
50
+ let entries;
51
+ try {
52
+ entries = readdirSync(current, { withFileTypes: true });
53
+ }
54
+ catch {
55
+ continue;
56
+ }
57
+ for (const entry of entries) {
58
+ const path = join(current, entry.name);
59
+ if (entry.isDirectory()) {
60
+ if (["node_modules", ".next", "dist", ".turbo", ".git", "storybook-static", "coverage", "build", "out"].includes(entry.name)) {
61
+ continue;
62
+ }
63
+ stack.push(path);
64
+ }
65
+ else if (/\.(ts|tsx|js|jsx|mts|cts)$/.test(entry.name) &&
66
+ !/\.(test|spec)\./.test(entry.name) &&
67
+ !/\.min\.js$/.test(entry.name)) {
68
+ scanned++;
69
+ const content = readFileSafe(path);
70
+ if (!content)
71
+ continue;
72
+ for (const [re, label] of patterns) {
73
+ if (re.test(content) && !/process\.env/.test(content.match(re)?.[0] ?? "")) {
74
+ hits.push(`${label} in ${path.replace(cwd + "/", "")}`);
75
+ break;
76
+ }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ return hits;
82
+ }
83
+ export function runSecurityChecks(cwd, opts = {}) {
84
+ const findings = [];
85
+ const add = (id, severity, message) => findings.push({ id, severity, message });
86
+ const envRaw = readFileSafe(join(cwd, "apps", "api", ".env"));
87
+ const env = envRaw ? parseEnv(envRaw) : undefined;
88
+ if (!env) {
89
+ add("env-missing", "warning", "apps/api/.env not found — cannot assess runtime secrets.");
90
+ }
91
+ else {
92
+ const jwt = inspectSecret(env.JWT_SECRET, "JWT_SECRET");
93
+ if (jwt.weak)
94
+ add("jwt-secret", "critical", jwt.reason);
95
+ const jwtR = inspectSecret(env.JWT_REFRESH_SECRET, "JWT_REFRESH_SECRET");
96
+ if (jwtR.weak)
97
+ add("jwt-refresh-secret", "critical", jwtR.reason);
98
+ if (env.JWT_SECRET && env.JWT_SECRET === env.JWT_REFRESH_SECRET) {
99
+ add("jwt-identical", "critical", "JWT_SECRET and JWT_REFRESH_SECRET must not be identical.");
100
+ }
101
+ if (env.SUPERADMIN_PASSWORD) {
102
+ const pw = inspectPassword(env.SUPERADMIN_PASSWORD);
103
+ if (pw.weak)
104
+ add("admin-password", "critical", pw.reason);
105
+ }
106
+ if (!jwt.weak && !jwtR.weak)
107
+ add("jwt-ok", "info", "JWT secrets have sufficient length and entropy.");
108
+ }
109
+ // .env handling
110
+ if (!gitignoreIgnoresEnv(cwd)) {
111
+ add("gitignore-env", "critical", ".env is not excluded by .gitignore.");
112
+ }
113
+ else {
114
+ add("gitignore-env-ok", "info", ".env is excluded by .gitignore.");
115
+ }
116
+ if (existsSync(join(cwd, ".git"))) {
117
+ const tracked = spawnSync("git", ["ls-files", "--error-unmatch", "apps/api/.env"], { cwd, stdio: "ignore" });
118
+ if (tracked.status === 0)
119
+ add("env-tracked", "critical", "apps/api/.env is tracked by Git. Untrack it and rotate all secrets.");
120
+ }
121
+ // npm tarball exposure — only relevant if the package is publishable
122
+ const rootPkgRaw = readFileSafe(join(cwd, "package.json"));
123
+ if (rootPkgRaw) {
124
+ try {
125
+ const pkg = JSON.parse(rootPkgRaw);
126
+ if (pkg.private !== true && pkg.files && pkg.files.some((f) => f.includes(".env"))) {
127
+ add("npm-env", "critical", "package.json `files` would publish a .env file.");
128
+ }
129
+ }
130
+ catch {
131
+ /* ignore */
132
+ }
133
+ }
134
+ // production config scans
135
+ const mainCandidates = [join(cwd, "apps", "api", "src", "main.ts")];
136
+ for (const file of mainCandidates) {
137
+ const content = readFileSafe(file);
138
+ if (!content)
139
+ continue;
140
+ if (/origin\s*:\s*["']\*["']/.test(content) && /credentials\s*:\s*true/.test(content)) {
141
+ add("cors-credentials", "critical", "CORS is configured with origin '*' together with credentials.");
142
+ }
143
+ }
144
+ const hardcoded = scanForHardcodedSecrets(cwd);
145
+ for (const hit of hardcoded)
146
+ add("hardcoded-secret", "warning", hit);
147
+ // dependency audit (best-effort, network-dependent)
148
+ if (!opts.skipNetwork && existsSync(join(cwd, "node_modules"))) {
149
+ const audit = spawnSync("npm", ["audit", "--production", "--audit-level=high", "--json"], { cwd, encoding: "utf8" });
150
+ if (audit.stdout) {
151
+ try {
152
+ const parsed = JSON.parse(audit.stdout);
153
+ const vulns = parsed.metadata?.vulnerabilities ?? {};
154
+ const high = (vulns.high ?? 0) + (vulns.critical ?? 0);
155
+ if (high > 0)
156
+ add("dependency-audit", "warning", `${high} high/critical dependency vulnerabilities reported by npm audit.`);
157
+ else
158
+ add("dependency-audit", "info", "No high/critical dependency vulnerabilities reported.");
159
+ }
160
+ catch {
161
+ /* ignore audit parse errors */
162
+ }
163
+ }
164
+ }
165
+ add("https-guidance", "info", "In production, terminate TLS at a reverse proxy and set secure cookie flags + trust proxy.");
166
+ const ok = !findings.some((f) => f.severity === "critical");
167
+ return { findings, ok };
168
+ }
@@ -0,0 +1,10 @@
1
+ type Change = {
2
+ path: string;
3
+ status: "update" | "conflict" | "manual" | "restored";
4
+ };
5
+ export declare function writeManagedBaseline(root: string): void;
6
+ export declare function upgradeManaged(root: string, template: string, flags?: {
7
+ apply?: boolean;
8
+ rollback?: boolean;
9
+ }): Change[];
10
+ export {};
@@ -0,0 +1,133 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join, dirname, resolve, relative } from "node:path";
4
+ const BASELINE = ".openadminjs-managed.json", BACKUP = ".openadminjs-patch-backup";
5
+ const roots = ["packages/resource/src", "packages/core/src", "packages/permissions/src", "packages/plugin-sdk/src", "packages/storage/src", "apps/admin/components", "apps/admin/lib"];
6
+ function permitted(path) {
7
+ return roots.some(root => path.startsWith(root + "/")) && /\.(ts|tsx|css)$/.test(path) && !/\.(test|spec|stories)\.[^.]+$/.test(path) && !path.split("/").some(x => !x || x === "." || x === ".." || x.startsWith("."));
8
+ }
9
+ function safe(root, path) {
10
+ if (!permitted(path))
11
+ throw Error("Not a managed file: " + path);
12
+ let p = resolve(root);
13
+ for (const segment of path.split("/")) {
14
+ p = join(p, segment);
15
+ if (existsSync(p) && lstatSync(p).isSymbolicLink())
16
+ throw Error("Symlink not allowed: " + path);
17
+ }
18
+ return p;
19
+ }
20
+ function digest(data) { return createHash("sha256").update(data).digest("hex"); }
21
+ function hashes(root) {
22
+ const out = {};
23
+ function walk(dir) {
24
+ if (!existsSync(dir))
25
+ return;
26
+ if (lstatSync(dir).isSymbolicLink())
27
+ throw Error("Managed root cannot be a symlink");
28
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
29
+ if (e.isSymbolicLink())
30
+ throw Error("Symlink in managed directory");
31
+ const p = join(dir, e.name);
32
+ if (e.isDirectory()) {
33
+ walk(p);
34
+ continue;
35
+ }
36
+ const path = relative(root, p).replaceAll("\\", "/");
37
+ if (e.isFile() && permitted(path))
38
+ out[path] = digest(readFileSync(safe(root, path)));
39
+ }
40
+ }
41
+ for (const dir of roots)
42
+ walk(join(root, dir));
43
+ return out;
44
+ }
45
+ function readManifest(path) {
46
+ if (lstatSync(path).isSymbolicLink())
47
+ throw Error("Symlinked manifest");
48
+ const data = JSON.parse(readFileSync(path, "utf8"));
49
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.entries(data).some(([p, h]) => !permitted(p) || typeof h !== "string" || !/^[a-f0-9]{64}$/.test(h)))
50
+ throw Error("Invalid managed baseline");
51
+ return data;
52
+ }
53
+ function atomic(path, bytes) {
54
+ const temporary = path + ".oajs-" + randomBytes(8).toString("hex");
55
+ writeFileSync(temporary, bytes, { flag: "wx", mode: 0o600 });
56
+ try {
57
+ renameSync(temporary, path);
58
+ }
59
+ catch (e) {
60
+ rmSync(temporary, { force: true });
61
+ throw e;
62
+ }
63
+ }
64
+ export function writeManagedBaseline(root) {
65
+ atomic(join(root, BASELINE), JSON.stringify(hashes(root), null, 2) + "\n");
66
+ }
67
+ export function upgradeManaged(root, template, flags = {}) {
68
+ if (flags.apply && flags.rollback)
69
+ throw Error("Choose apply or rollback");
70
+ const manifestPath = join(root, BASELINE), backup = join(root, BACKUP);
71
+ if (!existsSync(manifestPath))
72
+ throw Error("No baseline: use a manual reviewed upgrade for this project");
73
+ const baseline = readManifest(manifestPath);
74
+ if (flags.rollback) {
75
+ if (!existsSync(backup) || lstatSync(backup).isSymbolicLink())
76
+ throw Error("No valid patch backup");
77
+ const previous = readManifest(join(backup, "baseline.json")), applied = readManifest(join(backup, "applied.json"));
78
+ const entries = Object.keys(applied).filter(p => previous[p] !== applied[p]);
79
+ const changes = entries.map(p => ({ path: p, status: existsSync(safe(root, p)) && digest(readFileSync(safe(root, p))) === applied[p] ? "restored" : "conflict" }));
80
+ if (changes.some(p => p.status === "conflict"))
81
+ return changes;
82
+ const old = entries.map(p => { const content = readFileSync(safe(backup, p)); if (digest(content) !== previous[p])
83
+ throw Error("Backup checksum mismatch"); return { p, content }; });
84
+ for (const { p, content } of old)
85
+ atomic(safe(root, p), content);
86
+ atomic(manifestPath, JSON.stringify(previous, null, 2) + "\n");
87
+ rmSync(backup, { recursive: true, force: true });
88
+ return changes;
89
+ }
90
+ const candidate = hashes(template), plan = [];
91
+ for (const p of new Set([...Object.keys(baseline), ...Object.keys(candidate)])) {
92
+ if (candidate[p] === baseline[p])
93
+ continue;
94
+ if (!candidate[p] || !baseline[p]) {
95
+ plan.push({ path: p, status: "manual" });
96
+ continue;
97
+ }
98
+ const dest = safe(root, p);
99
+ plan.push({ path: p, status: existsSync(dest) && digest(readFileSync(dest)) === baseline[p] ? "update" : "conflict" });
100
+ }
101
+ if (!flags.apply || plan.some(p => p.status === "conflict" || p.status === "manual"))
102
+ return plan;
103
+ if (!plan.length)
104
+ return plan;
105
+ if (existsSync(backup))
106
+ throw Error("Previous patch backup exists; keep or roll it back before another patch");
107
+ mkdirSync(backup, { mode: 0o700 });
108
+ const next = { ...baseline };
109
+ const changed = [];
110
+ try {
111
+ for (const { path: p } of plan) {
112
+ const dest = safe(root, p), before = readFileSync(dest), after = readFileSync(safe(template, p));
113
+ if (digest(before) !== baseline[p] || digest(after) !== candidate[p])
114
+ throw Error("File changed during patch");
115
+ const saved = safe(backup, p);
116
+ mkdirSync(dirname(saved), { recursive: true });
117
+ writeFileSync(saved, before, { flag: "wx", mode: 0o600 });
118
+ changed.push({ p, before });
119
+ atomic(dest, after);
120
+ next[p] = candidate[p];
121
+ }
122
+ writeFileSync(join(backup, "baseline.json"), JSON.stringify(baseline), { mode: 0o600 });
123
+ writeFileSync(join(backup, "applied.json"), JSON.stringify(next), { mode: 0o600 });
124
+ atomic(manifestPath, JSON.stringify(next, null, 2) + "\n");
125
+ return plan;
126
+ }
127
+ catch (e) {
128
+ for (const { p, before } of changed.reverse())
129
+ atomic(safe(root, p), before);
130
+ rmSync(backup, { recursive: true, force: true });
131
+ throw e;
132
+ }
133
+ }