openadminjs 0.2.0 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +106 -151
  2. package/dist/adapt-package-manager.js +4 -1
  3. package/dist/create-project.d.ts +46 -0
  4. package/dist/create-project.js +417 -150
  5. package/dist/doctor.d.ts +13 -0
  6. package/dist/doctor.js +35 -6
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +257 -39
  9. package/dist/render-schema.d.ts +0 -17
  10. package/dist/render-schema.js +25 -29
  11. package/dist/resource-slug.d.ts +1 -0
  12. package/dist/resource-slug.js +7 -0
  13. package/dist/runtime-mode.d.ts +16 -0
  14. package/dist/runtime-mode.js +138 -0
  15. package/dist/upgrade.d.ts +10 -0
  16. package/dist/upgrade.js +133 -0
  17. package/package.json +14 -11
  18. package/template/.dockerignore +15 -0
  19. package/template/.env.production.example +5 -0
  20. package/template/Dockerfile +12 -0
  21. package/template/README.md +4 -3
  22. package/template/apps/admin/app/api/auth/login/route.ts +9 -9
  23. package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
  24. package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
  25. package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
  26. package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
  27. package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
  28. package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
  29. package/template/apps/admin/app/api-tokens/page.tsx +39 -39
  30. package/template/apps/admin/app/assistant/page.tsx +11 -0
  31. package/template/apps/admin/app/dashboard/page.tsx +45 -462
  32. package/template/apps/admin/app/globals.css +52 -16
  33. package/template/apps/admin/app/layout.tsx +1 -1
  34. package/template/apps/admin/app/login/page.tsx +13 -145
  35. package/template/apps/admin/app/plugins/page.tsx +16 -402
  36. package/template/apps/admin/app/profile/page.tsx +5 -2
  37. package/template/apps/admin/app/settings/page.tsx +14 -265
  38. package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
  39. package/template/apps/admin/components/app-shell.tsx +25 -373
  40. package/template/apps/admin/components/auth-guard.tsx +8 -28
  41. package/template/apps/admin/components/logo.tsx +1 -30
  42. package/template/apps/admin/components/resource-form.tsx +3 -3
  43. package/template/apps/admin/components/resource-table.tsx +12 -8
  44. package/template/apps/admin/lib/api.ts +45 -107
  45. package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
  46. package/template/apps/admin/lib/server-api.ts +7 -0
  47. package/template/apps/admin/lib/tokens.ts +9 -81
  48. package/template/apps/admin/middleware.ts +9 -50
  49. package/template/apps/admin/next.config.mjs +4 -0
  50. package/template/apps/admin/package.json +2 -1
  51. package/template/apps/admin/public/brand/favicon.svg +4 -1
  52. package/template/apps/admin/tailwind.config.ts +9 -8
  53. package/template/apps/api/package.json +10 -6
  54. package/template/apps/api/src/access/catalog.ts +4 -0
  55. package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
  56. package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
  57. package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
  58. package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
  59. package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
  60. package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
  61. package/template/apps/api/src/admin/admin.controller.ts +17 -4
  62. package/template/apps/api/src/admin/admin.module.ts +2 -2
  63. package/template/apps/api/src/admin/resource-policy.ts +1 -0
  64. package/template/apps/api/src/admin/resource-query.ts +1 -0
  65. package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
  66. package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
  67. package/template/apps/api/src/auth/auth.controller.ts +4 -2
  68. package/template/apps/api/src/auth/auth.service.ts +68 -83
  69. package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
  70. package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
  71. package/template/apps/api/src/common/api-exception.filter.ts +1 -0
  72. package/template/apps/api/src/common/auth.guard.ts +66 -39
  73. package/template/apps/api/src/common/json-field-codec.ts +12 -13
  74. package/template/apps/api/src/common/prisma.service.ts +9 -17
  75. package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
  76. package/template/apps/api/src/graphql/graphql.module.ts +5 -4
  77. package/template/apps/api/src/health/health.controller.ts +6 -0
  78. package/template/apps/api/src/main.ts +11 -2
  79. package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
  80. package/template/apps/api/src/resources/commerce.resource.ts +3 -34
  81. package/template/apps/api/src/resources/operations.resource.ts +1 -0
  82. package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
  83. package/template/apps/api/src/store/payment/payment.module.ts +2 -3
  84. package/template/apps/api/src/store/payment/payment.service.ts +121 -227
  85. package/template/apps/api/webpack.config.cjs +2 -1
  86. package/template/apps/web/next.config.mjs +4 -0
  87. package/template/apps/web/public/brand/favicon.svg +4 -1
  88. package/template/compose.yaml +56 -0
  89. package/template/examples/crm-admin/README.md +31 -0
  90. package/template/examples/crm-admin/package.json +17 -0
  91. package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
  92. package/template/examples/crm-admin/src/index.ts +7 -0
  93. package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
  94. package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
  95. package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
  96. package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
  97. package/template/examples/crm-admin/tsconfig.json +7 -0
  98. package/template/package.json +6 -1
  99. package/template/packages/admin-client/package.json +18 -0
  100. package/template/packages/admin-client/src/contracts.ts +29 -0
  101. package/template/packages/admin-client/src/index.ts +2 -0
  102. package/template/packages/admin-client/src/preferences.ts +57 -0
  103. package/template/packages/admin-client/tsconfig.json +12 -0
  104. package/template/packages/auth/package.json +1 -1
  105. package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
  106. package/template/packages/brand/src/generate-assets.mjs +17 -186
  107. package/template/packages/core/package.json +1 -1
  108. package/template/packages/mail/package.json +1 -1
  109. package/template/packages/nest/package.json +22 -0
  110. package/template/packages/nest/src/api-exception.filter.ts +23 -0
  111. package/template/packages/nest/src/index.ts +3 -0
  112. package/template/packages/nest/src/resource-policy.ts +64 -0
  113. package/template/packages/nest/src/resource-query.ts +103 -0
  114. package/template/packages/nest/tsconfig.json +12 -0
  115. package/template/packages/notifications/package.json +1 -1
  116. package/template/packages/payments/package.json +1 -1
  117. package/template/packages/permissions/package.json +1 -1
  118. package/template/packages/permissions/src/index.ts +2 -2
  119. package/template/packages/plugin-sdk/package.json +1 -1
  120. package/template/packages/plugin-sdk/src/index.ts +2 -2
  121. package/template/packages/prisma/package.json +21 -0
  122. package/template/packages/prisma/schema/ai.prisma +36 -0
  123. package/template/packages/prisma/schema/audit.prisma +13 -0
  124. package/template/packages/prisma/schema/commerce.prisma +79 -0
  125. package/template/packages/prisma/schema/content.prisma +27 -0
  126. package/template/packages/prisma/schema/core.prisma +106 -0
  127. package/template/packages/prisma/schema/header.prisma +8 -0
  128. package/template/packages/prisma/schema/jobs.prisma +9 -0
  129. package/template/packages/prisma/schema/media.prisma +9 -0
  130. package/template/packages/prisma/schema/modules.json +47 -0
  131. package/template/packages/prisma/schema/notifications.prisma +9 -0
  132. package/template/packages/prisma/schema/settings.prisma +8 -0
  133. package/template/packages/prisma/schema/tokens.prisma +10 -0
  134. package/template/packages/prisma/src/index.d.ts +12 -0
  135. package/template/packages/prisma/src/index.mjs +138 -0
  136. package/template/packages/queue/package.json +1 -1
  137. package/template/packages/resource/package.json +1 -1
  138. package/template/packages/resource/src/index.ts +1 -0
  139. package/template/packages/storage/package.json +1 -1
  140. package/template/packages/storage/src/index.ts +37 -0
  141. package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
  142. package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
  143. package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
  144. package/template/prisma/schema.prisma +82 -54
  145. package/template/prisma/seed.ts +14 -38
  146. package/template/runtime-versions.json +15 -0
  147. package/template/scripts/db-init.mjs +33 -0
  148. package/template/scripts/install-crm.mjs +50 -0
  149. package/template/scripts/migrate-existing.mjs +65 -0
  150. package/template/scripts/schema.mjs +48 -0
  151. package/template/tsconfig.base.json +23 -5
  152. package/LICENSE +0 -21
  153. package/dist/adapt-package-manager.test.d.ts +0 -1
  154. package/dist/adapt-package-manager.test.js +0 -76
  155. package/dist/cli.e2e.test.d.ts +0 -1
  156. package/dist/cli.e2e.test.js +0 -87
  157. package/dist/create-project.test.d.ts +0 -1
  158. package/dist/create-project.test.js +0 -275
  159. package/dist/database-providers.integration.test.d.ts +0 -1
  160. package/dist/database-providers.integration.test.js +0 -64
  161. package/dist/db-commands.test.d.ts +0 -1
  162. package/dist/db-commands.test.js +0 -27
  163. package/dist/doctor.test.d.ts +0 -1
  164. package/dist/doctor.test.js +0 -102
  165. package/dist/index.test.d.ts +0 -1
  166. package/dist/index.test.js +0 -11
  167. package/dist/render-schema.test.d.ts +0 -1
  168. package/dist/render-schema.test.js +0 -57
  169. package/dist/resource-slug.test.d.ts +0 -1
  170. package/dist/resource-slug.test.js +0 -9
  171. package/dist/secrets.test.d.ts +0 -1
  172. package/dist/secrets.test.js +0 -36
  173. package/dist/security.test.d.ts +0 -1
  174. package/dist/security.test.js +0 -54
  175. package/dist/validate-name.test.d.ts +0 -1
  176. package/dist/validate-name.test.js +0 -63
  177. package/template/apps/admin/.storybook/main.ts +0 -12
  178. package/template/apps/admin/.storybook/preview.ts +0 -10
  179. package/template/apps/admin/app/login/page.test.tsx +0 -18
  180. package/template/apps/admin/components/auth-guard.test.tsx +0 -55
  181. package/template/apps/admin/components/logo.stories.tsx +0 -24
  182. package/template/apps/admin/lib/api.test.ts +0 -118
  183. package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
  184. package/template/apps/admin/vitest.config.ts +0 -7
  185. package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
  186. package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
  187. package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
  188. package/template/apps/api/src/app.module.test.ts +0 -12
  189. package/template/apps/api/src/auth/auth.service.test.ts +0 -78
  190. package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
  191. package/template/apps/api/src/common/auth.guard.test.ts +0 -62
  192. package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
  193. package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
  194. package/template/apps/api/src/common/prisma.service.test.ts +0 -19
  195. package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
  196. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
  197. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
  198. package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
  199. package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
  200. package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
  201. package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
  202. package/template/apps/api/src/queue/queue.service.test.ts +0 -33
  203. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
  204. package/template/apps/api/vitest.config.ts +0 -21
  205. package/template/apps/web/lib/seo.test.ts +0 -41
  206. package/template/apps/web/vitest.config.ts +0 -19
  207. package/template/packages/auth/src/index.test.ts +0 -10
  208. package/template/packages/brand/src/index.test.ts +0 -9
  209. package/template/packages/core/src/index.test.ts +0 -27
  210. package/template/packages/core/vitest.config.ts +0 -9
  211. package/template/packages/mail/src/index.test.ts +0 -23
  212. package/template/packages/notifications/src/index.test.ts +0 -9
  213. package/template/packages/permissions/src/blueprints.test.ts +0 -62
  214. package/template/packages/permissions/src/index.test.ts +0 -34
  215. package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
  216. package/template/packages/plugin-sdk/vitest.config.ts +0 -5
  217. package/template/packages/queue/src/index.test.ts +0 -12
  218. package/template/packages/resource/src/index.test.ts +0 -196
  219. package/template/packages/storage/src/index.test.ts +0 -10
@@ -0,0 +1,47 @@
1
+ {
2
+ "modules": {
3
+ "core": [],
4
+ "audit": [
5
+ "core"
6
+ ],
7
+ "settings": [
8
+ "core"
9
+ ],
10
+ "media": [
11
+ "core"
12
+ ],
13
+ "content": [
14
+ "core",
15
+ "media"
16
+ ],
17
+ "tokens": [
18
+ "core"
19
+ ],
20
+ "notifications": [
21
+ "core"
22
+ ],
23
+ "jobs": [
24
+ "core"
25
+ ],
26
+ "commerce": [
27
+ "core"
28
+ ],
29
+ "ai": [
30
+ "core"
31
+ ]
32
+ },
33
+ "optionalRelations": {
34
+ "User": {
35
+ "posts": "content",
36
+ "auditLogs": "audit",
37
+ "apiTokens": "tokens",
38
+ "notifications": "notifications",
39
+ "orders": "commerce",
40
+ "aiConversations": "ai",
41
+ "aiArtifacts": "ai"
42
+ },
43
+ "FileAsset": {
44
+ "posts": "content"
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,9 @@
1
+ model Notification {
2
+ id String @id @default(cuid())
3
+ userId String
4
+ title String
5
+ body String?
6
+ readAt DateTime?
7
+ createdAt DateTime @default(now())
8
+ user User @relation(fields: [userId], references: [id])
9
+ }
@@ -0,0 +1,8 @@
1
+ model Setting {
2
+ id String @id @default(cuid())
3
+ key String @unique
4
+ group String
5
+ type String
6
+ value Json
7
+ updatedAt DateTime @updatedAt
8
+ }
@@ -0,0 +1,10 @@
1
+ model ApiToken {
2
+ id String @id @default(cuid())
3
+ name String
4
+ tokenHash String @unique
5
+ scopes String[]
6
+ revokedAt DateTime?
7
+ createdAt DateTime @default(now())
8
+ userId String
9
+ user User @relation(fields: [userId], references: [id])
10
+ }
@@ -0,0 +1,12 @@
1
+ export type Provider="postgresql"|"mysql"|"sqlite";
2
+ export type SchemaModule="core"|"audit"|"settings"|"media"|"content"|"tokens"|"notifications"|"jobs"|"commerce"|"ai";
3
+ export const moduleNames:readonly SchemaModule[];
4
+ export const providers:readonly Provider[];
5
+ export function resolveModules(requested?:readonly SchemaModule[]):SchemaModule[];
6
+ export function renderProvider(schema:string,provider:Provider):string;
7
+ export function composeSchema(options?:{provider?:Provider;modules?:readonly SchemaModule[];customFragments?:readonly string[]}):string;
8
+ export function splitSchema(schema:string):{name:string;content:string}[];
9
+ export const legacySqliteJsonFields:Readonly<Record<string,readonly string[]>>;
10
+ export function legacySqliteNormalizationSql():string;
11
+ export function mergeLegacySchema(schema:string,provider:Provider):{schema:string;changes:string[];normalizations:{table:string;field:string}[];clearLegacyRefresh:boolean;revokeLegacyKeys:boolean};
12
+ export function schemaProvider(schema:string):string;
@@ -0,0 +1,138 @@
1
+ import {readFileSync} from "node:fs";
2
+ const load=name=>readFileSync(new URL("../schema/"+name,import.meta.url),"utf8");
3
+ const spec=JSON.parse(load("modules.json"));
4
+ export const moduleNames=Object.freeze(Object.keys(spec.modules));
5
+ export const providers=Object.freeze(["postgresql","mysql","sqlite"]);
6
+ export function resolveModules(requested=moduleNames){
7
+ if(!Array.isArray(requested))throw Error("Modules must be an array");
8
+ const enabled=new Set();
9
+ function add(name){if(!Object.hasOwn(spec.modules,name))throw Error("Unknown schema module: "+name);if(enabled.has(name))return;enabled.add(name);for(const dep of spec.modules[name])add(dep);}
10
+ add("core");for(const name of requested)add(name);
11
+ return moduleNames.filter(name=>enabled.has(name));
12
+ }
13
+ // Locate the provider in a single pass over formatted Prisma lines. Do not
14
+ // use an unbounded, unanchored regex over library-supplied schema text.
15
+ function locateProvider(schema){
16
+ if(typeof schema!=="string")throw Error("Schema must be a string");
17
+ let inside=false,offset=0,found;
18
+ for(const line of schema.split(/(\r?\n)/)){
19
+ if(/^[ \t]*datasource[ \t]+[A-Za-z_]\w*[ \t]*\{[ \t]*(?:\/\/.*)?$/.test(line))inside=true;
20
+ else if(inside&&/^[ \t]*\}/.test(line))inside=false;
21
+ else if(inside){
22
+ const m=line.match(/^[ \t]*provider[ \t]*=[ \t]*"([^"\r\n]+)"[ \t]*(?:\/\/.*)?$/);
23
+ if(m){
24
+ if(found)throw Error("Multiple datasource providers are not supported");
25
+ const start=offset+line.indexOf('"')+1;
26
+ found={provider:m[1],start,end:start+m[1].length};
27
+ }
28
+ }
29
+ offset+=line.length;
30
+ }
31
+ if(!found)throw Error("Format schema with a datasource provider on its own line");
32
+ return found;
33
+ }
34
+ export function schemaProvider(schema){return locateProvider(schema).provider;}
35
+ const scalars=new Set(["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Bytes","Json"]);
36
+ export function renderProvider(schema,provider){
37
+ if(!providers.includes(provider))throw Error("Unsupported provider: "+provider);
38
+ const location=locateProvider(schema);
39
+ let result=schema.slice(0,location.start)+provider+schema.slice(location.end);
40
+ if(provider==="postgresql")return result;
41
+ let model=false,comment=false;
42
+ return result.split(/(\r?\n)/).map(line=>{
43
+ if(/^\s*\/\*/.test(line))comment=true;
44
+ if(comment){if(line.includes("*/"))comment=false;return line;}
45
+ if(/^\s*(model|type)\s+\w+\s*\{/.test(line)){model=true;return line;}
46
+ if(/^\s*}\s*(?:\/\/.*)?$/.test(line)){model=false;return line;}
47
+ if(!model)return line;
48
+ return line.replace(/^(\s*\w+\s+)(\w+)\[\](?=\s|$)/,(match,prefix,type)=>scalars.has(type)?prefix+"Json":match);
49
+ }).join("");
50
+ }
51
+ /** Built-in feature fragments, with explicit inverse relations for disabled features. */
52
+ export function composeSchema({provider="postgresql",modules=moduleNames,customFragments=[]}={}){
53
+ const enabled=resolveModules(modules),names=new Set(enabled);
54
+ const chunks=[load("header.prisma").trim()];
55
+ for(const name of enabled){
56
+ let model="";
57
+ const content=load(name+".prisma").trim().split("\n").filter(line=>{
58
+ const start=line.match(/^model\s+(\w+)/);if(start)model=start[1];
59
+ const field=line.match(/^\s+(\w+)\s+/)?.[1];
60
+ const feature=field&&spec.optionalRelations[model]?.[field];
61
+ return !feature||names.has(feature);
62
+ }).join("\n");
63
+ chunks.push(content);
64
+ }
65
+ for(const fragment of customFragments){
66
+ if(typeof fragment!=="string"||/^\s*(generator|datasource)\s+/m.test(fragment))throw Error("Custom fragments cannot redefine generator or datasource");
67
+ if(fragment.trim())chunks.push(fragment.trim());
68
+ }
69
+ const schema=chunks.join("\n\n")+"\n";
70
+ const declarations=new Set();
71
+ for(const m of schema.matchAll(/^\s*(model|enum|type|view)\s+(\w+)\s*\{/gm)){
72
+ if(declarations.has(m[2]))throw Error("Duplicate schema declaration: "+m[2]);declarations.add(m[2]);
73
+ }
74
+ return renderProvider(schema,provider);
75
+ }
76
+ /** Lossless adoption of an existing monolithic schema; custom declarations are never replaced. */
77
+ export function splitSchema(schema){
78
+ if(typeof schema!=="string"||!schema.trim())throw Error("Empty schema");
79
+ const starts=[...schema.matchAll(/^(generator|datasource|model|enum|type|view)\s+(\w+)\s*\{/gm)];
80
+ if(!starts.length)throw Error("No supported Prisma declarations");
81
+ const chunks=[];
82
+ if(starts[0].index>0)chunks.push({name:"000-preamble",content:schema.slice(0,starts[0].index)});
83
+ for(let i=0;i<starts.length;i++){
84
+ const m=starts[i],end=starts[i+1]?.index??schema.length;
85
+ chunks.push({name:String(i+1).padStart(3,"0")+"-"+m[1]+"-"+m[2],content:schema.slice(m.index,end)});
86
+ }
87
+ if(chunks.map(x=>x.content).join("")!==schema)throw Error("Schema split is not lossless");
88
+ return chunks;
89
+ }
90
+ export const legacySqliteJsonFields=Object.freeze({AuditLog:["before","after"],Setting:["value"],ApiToken:["scopes"],JobLog:["payload"],Product:["metadata"],Order:["metadata"],Transaction:["metadata"],WebhookLog:["payload"],AiMessage:["meta"],AiArtifact:["meta"]});
91
+ /** Legacy codec parsed valid JSON and returned invalid JSON text verbatim. Preserve that meaning. */
92
+ export function legacySqliteNormalizationSql(){
93
+ return Object.entries(legacySqliteJsonFields).flatMap(([table,fields])=>fields.map(field=>'UPDATE "'+table+'" SET "'+field+'" = json_quote("'+field+'") WHERE "'+field+'" IS NOT NULL AND NOT json_valid("'+field+'");')).join("\n")+"\n";
94
+ }
95
+
96
+ /** Prepare an upgrade target from the existing schema, keeping custom models/fields.
97
+ * Only known type changes are applied. Incompatible customizations fail closed.
98
+ * No database connection or filesystem mutation occurs here.
99
+ */
100
+ export function mergeLegacySchema(schema,provider){
101
+ const actual=schemaProvider(schema);
102
+ if(actual!==provider||!providers.includes(provider))throw Error("Provider mismatch; cross-provider migration is not supported");
103
+ const canonical=composeSchema({provider});
104
+ const models=text=>[...text.matchAll(/^model\s+(\w+)\s*\{[\s\S]*?^}/gm)];
105
+ const before=new Map(models(schema).map(m=>[m[1],m[0]]));
106
+ const after=new Map(models(canonical).map(m=>[m[1],m[0]]));
107
+ const changes=[],normalizations=[];
108
+ const fieldMap=block=>new Map(block.split("\n").flatMap(line=>{const m=line.match(/^\s+(\w+)\s+([A-Za-z][\w]*(?:\[\]|\?)?)(?=\s|$)/);return m?[[m[1],{type:m[2],line}]]:[];}));
109
+ let result=schema;
110
+ for(const [model,target] of after){
111
+ const old=before.get(model);
112
+ if(!old){result=result.trimEnd()+"\n\n"+target+"\n";changes.push("Add model "+model);continue;}
113
+ let next=old;const existing=fieldMap(old),fields=fieldMap(target),additions=[];
114
+ for(const [name,field] of fields){
115
+ const prior=existing.get(name);
116
+ if(!prior){additions.push(field.line);changes.push("Add "+model+"."+name);continue;}
117
+ if(prior.type!==field.type){
118
+ if(provider==="sqlite"&&legacySqliteJsonFields[model]?.includes(name)&&prior.type.replace("?","")==="String"&&field.type.replace("?","")==="Json"&&prior.type.endsWith("?")===field.type.endsWith("?")){
119
+ next=next.replace(prior.line,prior.line.replace(/^(\s+\w+\s+)String(\??)/,(_,prefix,suffix)=>prefix+"Json"+suffix));
120
+ normalizations.push({table:model,field:name});changes.push("Convert "+model+"."+name+" from legacy JSON text");
121
+ }else throw Error("Incompatible customized field "+model+"."+name+": "+prior.type+" vs "+field.type);
122
+ }
123
+ if(model==="ApiToken"&&name==="tokenHash"&&!/\s@unique\b/.test(prior.line)){
124
+ if(/\s\/\//.test(prior.line))throw Error("Review custom ApiToken.tokenHash declaration manually");
125
+ next=next.replace(prior.line,prior.line+" @unique");changes.push("Add ApiToken.tokenHash unique constraint");
126
+ }
127
+ }
128
+ const attrs=target.split("\n").filter(l=>/^\s*@@/.test(l));
129
+ const normalize=l=>l.replace(/\s+/g,"");
130
+ for(const attr of attrs)if(!old.split("\n").some(l=>normalize(l)===normalize(attr))){additions.push(attr);changes.push("Add "+model+" "+attr.trim());}
131
+ if(additions.length)next=next.slice(0,next.lastIndexOf("}")).trimEnd()+"\n\n"+additions.join("\n")+"\n}";
132
+ result=result.replace(old,()=>next);
133
+ }
134
+ // Unformatted built-in definitions must not accidentally be added twice.
135
+ const duplicates=new Set();
136
+ for(const m of result.matchAll(/^\s*(?:model|enum|type|view)\s+(\w+)\s*\{/gm)){if(duplicates.has(m[1]))throw Error("Duplicate declaration; format original schema before merging: "+m[1]);duplicates.add(m[1]);}
137
+ return {schema:result,changes,normalizations,clearLegacyRefresh:!before.has("Session"),revokeLegacyKeys:!(/\s@unique\b/.test(fieldMap(before.get("ApiToken")||"").get("tokenHash")?.line||""))};
138
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openadminjs/queue",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-rc.1",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "scripts": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openadminjs/resource",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-rc.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -5,6 +5,7 @@ export type FieldType =
5
5
  | "text"
6
6
  | "textarea"
7
7
  | "number"
8
+ | "decimal"
8
9
  | "boolean"
9
10
  | "select"
10
11
  | "multiselect"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openadminjs/storage",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-rc.1",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "scripts": {
@@ -1,3 +1,7 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, mkdir, open, unlink } from "node:fs/promises";
3
+ import { resolve, join } from "node:path";
4
+ import { randomBytes } from "node:crypto";
1
5
  export type FileValidation = {
2
6
  maxSizeBytes: number;
3
7
  mimeTypes: string[];
@@ -21,3 +25,36 @@ export const defaultFileValidation: FileValidation = {
21
25
  mimeTypes: ["image/png", "image/jpeg", "image/webp", "application/pdf", "text/plain"],
22
26
  extensions: [".png", ".jpg", ".jpeg", ".webp", ".pdf", ".txt"]
23
27
  };
28
+
29
+ /** Local private storage; only opaque generated keys are accepted. */
30
+ export class LocalStorage implements StorageDriver {
31
+ constructor(private readonly root = resolve(process.env.UPLOADS_ROOT || "uploads")) {}
32
+ private async location(path: string) {
33
+ if (!/^uploads\/[a-f0-9]{48}$/.test(path)) throw new Error("Invalid storage key");
34
+ await mkdir(this.root, {recursive:true,mode:0o700});
35
+ const stat = await lstat(this.root);
36
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Invalid storage root");
37
+ return join(this.root,path.slice(8));
38
+ }
39
+ async put(file: Buffer, meta: StoredFile): Promise<StoredFile> {
40
+ if (file.length > defaultFileValidation.maxSizeBytes) throw new Error("File too large");
41
+ const path = "uploads/" + randomBytes(24).toString("hex");
42
+ const target = await this.location(path);
43
+ const handle = await open(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
44
+ try { await handle.writeFile(file); } catch(e) { await handle.close(); await unlink(target).catch(()=>undefined); throw e; }
45
+ await handle.close();
46
+ return {...meta,path,size:file.length};
47
+ }
48
+ async read(path: string): Promise<Buffer> {
49
+ const handle = await open(await this.location(path), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
50
+ try {
51
+ const stat = await handle.stat();
52
+ if (!stat.isFile() || stat.size > defaultFileValidation.maxSizeBytes) throw new Error("Invalid stored object");
53
+ return await handle.readFile();
54
+ } finally { await handle.close(); }
55
+ }
56
+ async delete(path: string): Promise<void> {
57
+ const target = await this.location(path);
58
+ await unlink(target).catch(e=>{if(e.code!=="ENOENT") throw e;});
59
+ }
60
+ }
@@ -0,0 +1,26 @@
1
+ -- Legacy refresh tokens and access JWTs without sid become invalid.
2
+ UPDATE "User" SET "refreshTokenHash" = NULL;
3
+ CREATE TABLE "Session" (
4
+ "id" TEXT NOT NULL,
5
+ "userId" TEXT NOT NULL,
6
+ "realm" TEXT NOT NULL,
7
+ "expiresAt" TIMESTAMP(3) NOT NULL,
8
+ "revokedAt" TIMESTAMP(3),
9
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+ "lastUsedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
11
+ CONSTRAINT "Session_pkey" PRIMARY KEY ("id"),
12
+ CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE
13
+ );
14
+ CREATE TABLE "SessionToken" (
15
+ "id" TEXT NOT NULL,
16
+ "sessionId" TEXT NOT NULL,
17
+ "tokenHash" TEXT NOT NULL,
18
+ "usedAt" TIMESTAMP(3),
19
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
20
+ CONSTRAINT "SessionToken_pkey" PRIMARY KEY ("id"),
21
+ CONSTRAINT "SessionToken_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "Session"("id") ON DELETE CASCADE ON UPDATE CASCADE
22
+ );
23
+ CREATE INDEX "Session_userId_realm_idx" ON "Session"("userId", "realm");
24
+ CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");
25
+ CREATE UNIQUE INDEX "SessionToken_tokenHash_key" ON "SessionToken"("tokenHash");
26
+ CREATE INDEX "SessionToken_sessionId_idx" ON "SessionToken"("sessionId");
@@ -0,0 +1,3 @@
1
+ -- Revoke all legacy bcrypt tokens (their plaintext is unavailable).
2
+ UPDATE "ApiToken" SET "revokedAt"=CURRENT_TIMESTAMP WHERE "revokedAt" IS NULL;
3
+ CREATE UNIQUE INDEX "ApiToken_tokenHash_key" ON "ApiToken"("tokenHash");
@@ -0,0 +1,6 @@
1
+ ALTER TABLE "Order" ADD COLUMN "checkoutKey" TEXT, ADD COLUMN "checkoutRequestHash" TEXT, ADD COLUMN "checkoutSessionId" TEXT, ADD COLUMN "paymentIntentId" TEXT;
2
+ ALTER TABLE "WebhookLog" ADD COLUMN "providerEventId" TEXT;
3
+ CREATE UNIQUE INDEX "Order_checkoutKey_key" ON "Order"("checkoutKey");
4
+ CREATE UNIQUE INDEX "Order_checkoutSessionId_key" ON "Order"("checkoutSessionId");
5
+ CREATE UNIQUE INDEX "Order_paymentIntentId_key" ON "Order"("paymentIntentId");
6
+ CREATE UNIQUE INDEX "WebhookLog_providerEventId_key" ON "WebhookLog"("providerEventId");
@@ -13,7 +13,9 @@ model User {
13
13
  passwordHash String
14
14
  /** Stable IdP subject, format `issuerNormalized::sub` — set when user signs in via OIDC. */
15
15
  oidcKey String? @unique
16
+ /// Legacy refresh hash; invalidated by session migration.
16
17
  refreshTokenHash String?
18
+ sessions Session[]
17
19
  name String?
18
20
  avatarUrl String?
19
21
  status String @default("active")
@@ -68,42 +70,48 @@ model RolePermission {
68
70
  @@id([roleId, permissionId])
69
71
  }
70
72
 
71
- model Category {
73
+ model PasswordResetToken {
72
74
  id String @id @default(cuid())
73
- name String
74
- slug String @unique
75
- order Int @default(0)
76
- createdAt DateTime @default(now())
77
- updatedAt DateTime @updatedAt
78
- posts Post[]
75
+ tokenHash String
76
+ expiresAt DateTime
77
+ usedAt DateTime?
78
+ userId String
79
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
80
+ }
79
81
 
80
- @@index([order])
82
+ model EmailVerificationToken {
83
+ id String @id @default(cuid())
84
+ tokenHash String
85
+ expiresAt DateTime
86
+ usedAt DateTime?
87
+ userId String
88
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
81
89
  }
82
90
 
83
- model Post {
84
- id String @id @default(cuid())
85
- title String
86
- slug String @unique
87
- status String @default("draft")
88
- content String?
89
- categoryId String?
90
- coverImageId String?
91
- authorId String?
92
- createdAt DateTime @default(now())
93
- updatedAt DateTime @updatedAt
94
- category Category? @relation(fields: [categoryId], references: [id])
95
- coverImage FileAsset? @relation(fields: [coverImageId], references: [id])
96
- author User? @relation(fields: [authorId], references: [id])
91
+ model Session {
92
+ id String @id @default(cuid())
93
+ userId String
94
+ realm String
95
+ expiresAt DateTime
96
+ revokedAt DateTime?
97
+ createdAt DateTime @default(now())
98
+ lastUsedAt DateTime @default(now())
99
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
100
+ tokens SessionToken[]
101
+
102
+ @@index([userId, realm])
103
+ @@index([expiresAt])
97
104
  }
98
105
 
99
- model FileAsset {
100
- id String @id @default(cuid())
101
- filename String
102
- path String
103
- mimeType String
104
- size Int
105
- createdAt DateTime @default(now())
106
- posts Post[]
106
+ model SessionToken {
107
+ id String @id @default(cuid())
108
+ sessionId String
109
+ tokenHash String @unique
110
+ usedAt DateTime?
111
+ createdAt DateTime @default(now())
112
+ session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
113
+
114
+ @@index([sessionId])
107
115
  }
108
116
 
109
117
  model AuditLog {
@@ -129,10 +137,48 @@ model Setting {
129
137
  updatedAt DateTime @updatedAt
130
138
  }
131
139
 
140
+ model FileAsset {
141
+ id String @id @default(cuid())
142
+ filename String
143
+ path String
144
+ mimeType String
145
+ size Int
146
+ createdAt DateTime @default(now())
147
+ posts Post[]
148
+ }
149
+
150
+ model Category {
151
+ id String @id @default(cuid())
152
+ name String
153
+ slug String @unique
154
+ order Int @default(0)
155
+ createdAt DateTime @default(now())
156
+ updatedAt DateTime @updatedAt
157
+ posts Post[]
158
+
159
+ @@index([order])
160
+ }
161
+
162
+ model Post {
163
+ id String @id @default(cuid())
164
+ title String
165
+ slug String @unique
166
+ status String @default("draft")
167
+ content String?
168
+ categoryId String?
169
+ coverImageId String?
170
+ authorId String?
171
+ createdAt DateTime @default(now())
172
+ updatedAt DateTime @updatedAt
173
+ category Category? @relation(fields: [categoryId], references: [id])
174
+ coverImage FileAsset? @relation(fields: [coverImageId], references: [id])
175
+ author User? @relation(fields: [authorId], references: [id])
176
+ }
177
+
132
178
  model ApiToken {
133
179
  id String @id @default(cuid())
134
180
  name String
135
- tokenHash String
181
+ tokenHash String @unique
136
182
  scopes String[]
137
183
  revokedAt DateTime?
138
184
  createdAt DateTime @default(now())
@@ -160,28 +206,6 @@ model JobLog {
160
206
  updatedAt DateTime @updatedAt
161
207
  }
162
208
 
163
- model PasswordResetToken {
164
- id String @id @default(cuid())
165
- tokenHash String
166
- expiresAt DateTime
167
- usedAt DateTime?
168
- userId String
169
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
170
- }
171
-
172
- model EmailVerificationToken {
173
- id String @id @default(cuid())
174
- tokenHash String
175
- expiresAt DateTime
176
- usedAt DateTime?
177
- userId String
178
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
179
- }
180
-
181
- // ──────────────────────────────────────────────
182
- // Commerce / Payments
183
- // ──────────────────────────────────────────────
184
-
185
209
  model Product {
186
210
  id String @id @default(cuid())
187
211
  name String
@@ -209,6 +233,10 @@ model Order {
209
233
  /** Total in smallest currency unit */
210
234
  total Int
211
235
  notes String?
236
+ checkoutKey String? @unique
237
+ checkoutRequestHash String?
238
+ checkoutSessionId String? @unique
239
+ paymentIntentId String? @unique
212
240
  metadata Json?
213
241
  createdAt DateTime @default(now())
214
242
  updatedAt DateTime @updatedAt
@@ -250,6 +278,7 @@ model WebhookLog {
250
278
  id String @id @default(cuid())
251
279
  provider String
252
280
  eventType String
281
+ providerEventId String? @unique
253
282
  payload Json
254
283
  /** pending | processed | failed */
255
284
  status String @default("pending")
@@ -293,4 +322,3 @@ model AiArtifact {
293
322
 
294
323
  @@index([userId, createdAt])
295
324
  }
296
-
@@ -85,6 +85,7 @@ async function askForSuperadminCredentials(): Promise<SeedCredentials> {
85
85
 
86
86
  async function main() {
87
87
  const superadmin = await askForSuperadminCredentials();
88
+ if (["viewer@example.com", "shopper@example.com"].includes(superadmin.email.toLowerCase()) || superadmin.password.length < 12) throw new Error("Use a non-demo administrator email and a password of at least 12 characters");
88
89
 
89
90
  const mergedCatalog: { name: string; label: { en: string; ru: string } }[] = [...permissionCatalog];
90
91
  for (const p of publicPermissionCatalog) {
@@ -144,10 +145,7 @@ async function main() {
144
145
 
145
146
  const user = await prisma.user.upsert({
146
147
  where: { email: superadmin.email },
147
- update: {
148
- name: "Admin",
149
- passwordHash: await bcrypt.hash(superadmin.password, 12)
150
- },
148
+ update: {},
151
149
  create: {
152
150
  email: superadmin.email,
153
151
  name: "Admin",
@@ -167,41 +165,18 @@ async function main() {
167
165
  create: { userId: user.id, roleId: publicMemberRole.id }
168
166
  });
169
167
 
170
- const viewerRole = await prisma.role.findUnique({
171
- where: { name_realm: { name: "viewer", realm: "admin" } }
172
- });
173
- if (viewerRole) {
174
- const viewerUser = await prisma.user.upsert({
175
- where: { email: "viewer@example.com" },
176
- update: {},
177
- create: {
178
- email: "viewer@example.com",
179
- name: "Viewer",
180
- passwordHash: await bcrypt.hash("password", 12)
181
- }
182
- });
183
- await prisma.userRole.upsert({
184
- where: { userId_roleId: { userId: viewerUser.id, roleId: viewerRole.id } },
185
- update: {},
186
- create: { userId: viewerUser.id, roleId: viewerRole.id }
187
- });
188
- }
189
-
190
- const shopper = await prisma.user.upsert({
191
- where: { email: "shopper@example.com" },
192
- update: {},
193
- create: {
194
- email: "shopper@example.com",
195
- name: "Shopper",
196
- passwordHash: await bcrypt.hash("password", 12)
168
+ // Previous releases seeded known credentials. Disable only unchanged demo accounts.
169
+ for (const email of ["viewer@example.com", "shopper@example.com"]) {
170
+ const legacy = await prisma.user.findUnique({ where: { email } });
171
+ if (legacy && await bcrypt.compare("password", legacy.passwordHash)) {
172
+ await prisma.$transaction(async tx => {
173
+ const updated = await tx.user.updateMany({ where: { id: legacy.id, passwordHash: legacy.passwordHash }, data: { status: "blocked", refreshTokenHash: null } });
174
+ if (updated.count) await tx.session.updateMany({ where: { userId: legacy.id, revokedAt: null }, data: { revokedAt: new Date() } });
175
+ });
197
176
  }
198
- });
199
- await prisma.userRole.upsert({
200
- where: { userId_roleId: { userId: shopper.id, roleId: publicMemberRole.id } },
201
- update: {},
202
- create: { userId: shopper.id, roleId: publicMemberRole.id }
203
- });
204
-
177
+ }
178
+ // No fixed demo accounts are created by normal seed.
179
+ if (process.env.NODE_ENV !== "production" && process.env.SEED_DEMO_DATA === "1") {
205
180
  const category = await prisma.category.upsert({
206
181
  where: { slug: "announcements" },
207
182
  update: {},
@@ -241,6 +216,7 @@ async function main() {
241
216
  create: { ...product, active: true }
242
217
  });
243
218
  }
219
+ }
244
220
  }
245
221
 
246
222
  main().finally(async () => prisma.$disconnect());
@@ -0,0 +1,15 @@
1
+ {
2
+ "@openadminjs/resource": "0.2.0-rc.1",
3
+ "@openadminjs/core": "0.2.0-rc.1",
4
+ "@openadminjs/auth": "0.2.0-rc.1",
5
+ "@openadminjs/permissions": "0.2.0-rc.1",
6
+ "@openadminjs/plugin-sdk": "0.2.0-rc.1",
7
+ "@openadminjs/storage": "0.2.0-rc.1",
8
+ "@openadminjs/queue": "0.2.0-rc.1",
9
+ "@openadminjs/notifications": "0.2.0-rc.1",
10
+ "@openadminjs/mail": "0.2.0-rc.1",
11
+ "@openadminjs/payments": "0.2.0-rc.1",
12
+ "@openadminjs/nest": "0.2.0-rc.1",
13
+ "@openadminjs/admin-client": "0.2.0-rc.1",
14
+ "@openadminjs/prisma": "0.2.0-rc.1"
15
+ }