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
@@ -11,7 +11,7 @@ import { AdminPluginsController } from "./admin-plugins.controller";
11
11
  import { AdminPluginsService } from "./admin-plugins.service";
12
12
  import { AdminResourceService } from "./admin-resource.service";
13
13
  import { AdminAnalyticsService } from "./admin-analytics.service";
14
- import { AdminAiService } from "./admin-ai.service";
14
+ import { SafeAiService } from "./safe-ai.service";
15
15
  import { PaymentModule } from "../store/payment/payment.module";
16
16
  import { LoggingModule } from "../common/logging.module";
17
17
 
@@ -21,7 +21,7 @@ import { LoggingModule } from "../common/logging.module";
21
21
  providers: [
22
22
  AdminResourceService,
23
23
  AdminAnalyticsService,
24
- AdminAiService,
24
+ SafeAiService,
25
25
  AdminPluginsService,
26
26
  PrismaService,
27
27
  AuthGuard,
@@ -0,0 +1 @@
1
+ export { isOutOfListScope, has, systemScope, canReadField, safeData, redact, auditSnapshot, sanitizeRecord, type UserContext } from "@openadminjs/nest";
@@ -0,0 +1 @@
1
+ export { buildWhere, buildOperatorClause, isStringFilterField, coerceFilterScalar, coerceFilterComparable, buildOrderBy } from "@openadminjs/nest";
@@ -0,0 +1,43 @@
1
+ import { Injectable, BadRequestException, ForbiddenException, BadGatewayException } from "@nestjs/common";
2
+ import { lookup } from "node:dns/promises";
3
+ import { request } from "node:https";
4
+ import { isIP } from "node:net";
5
+
6
+ export function publicIPv4(ip:string){
7
+ if(isIP(ip)!==4)return false;
8
+ const [a,b,c]=ip.split(".").map(Number) as [number,number,number,number];
9
+ return !(a===0||a===10||a===127||a>=224||a===169&&b===254||a===172&&b>=16&&b<=31||a===192&&(b===168||b===0||b===2||b===88&&c===99)||a===100&&b>=64&&b<=127||a===198&&(b===18||b===19||b===51&&c===100)||a===203&&b===0&&c===113);
10
+ }
11
+ const HOST="api.openai.com";
12
+ const PATH="/v1/chat/completions";
13
+ const LIMIT=1024*1024;
14
+ async function complete(token:string,model:string,message:string){
15
+ const addresses=await lookup(HOST,{family:4,all:true});
16
+ if(!addresses.length||addresses.some(x=>!publicIPv4(x.address)))throw new Error("Provider DNS denied");
17
+ const address=addresses[0]!.address;
18
+ const body=JSON.stringify({model,messages:[{role:"system",content:"You are a read-only OpenAdminJS documentation consultant. Explain concepts; never claim to have executed actions or accessed user data."},{role:"user",content:message}],max_completion_tokens:800});
19
+ return new Promise<string>((resolve,reject)=>{
20
+ const req=request({hostname:address,servername:HOST,path:PATH,method:"POST",headers:{host:HOST,authorization:"Bearer "+token,"content-type":"application/json","content-length":Buffer.byteLength(body)},timeout:20000},res=>{
21
+ if(res.statusCode!==200){res.resume();reject(new Error("Provider response rejected"));return;}
22
+ let size=0;const chunks:Buffer[]=[];
23
+ res.on("data",(chunk:Buffer)=>{size+=chunk.length;if(size>LIMIT){req.destroy(new Error("Provider response too large"));return;}chunks.push(chunk);});
24
+ res.on("end",()=>{try{const data=JSON.parse(Buffer.concat(chunks).toString("utf8")) as {choices?:{message?:{content?:string}}[]};const text=data.choices?.[0]?.message?.content;if(typeof text!=="string")throw Error("Missing text");resolve(text);}catch(e){reject(e);}});
25
+ res.on("error",reject);
26
+ });
27
+ const timer=setTimeout(()=>req.destroy(new Error("Provider deadline exceeded")),25000);
28
+ req.on("close",()=>clearTimeout(timer));req.on("timeout",()=>req.destroy(new Error("Provider timeout")));req.on("error",reject);req.end(body);
29
+ });
30
+ }
31
+ @Injectable()
32
+ export class SafeAiService {
33
+ enabled(){return process.env.OPENADMIN_AI_ENABLED==="1"&&Boolean(process.env.OPENAI_API_KEY?.trim());}
34
+ config(){return {enabled:this.enabled(),provider:"openai",model:process.env.OPENADMIN_AI_MODEL||"gpt-4o-mini",credentialConfigured:Boolean(process.env.OPENAI_API_KEY)};}
35
+ async chat(raw:unknown){
36
+ if(!this.enabled())throw new ForbiddenException("AI is disabled");
37
+ if(typeof raw!=="string"||!raw.trim()||raw.length>8000)throw new BadRequestException("Message must contain 1–8000 characters");
38
+ const model=process.env.OPENADMIN_AI_MODEL||"gpt-4o-mini";
39
+ if(!/^[a-zA-Z0-9._-]{1,100}$/.test(model))throw new BadRequestException("Invalid model configuration");
40
+ try{return {reply:await complete(process.env.OPENAI_API_KEY!,model,raw.trim()),actionResult:null,requiresConfirmation:false};}
41
+ catch{throw new BadGatewayException("AI provider unavailable");}
42
+ }
43
+ }
@@ -7,6 +7,8 @@ function fieldSchema(field: ResourceField, mode: "create" | "edit"): z.ZodTypeAn
7
7
  const optionalize = <T extends z.ZodTypeAny>(schema: T) => (required ? schema : schema.optional()) as z.ZodTypeAny;
8
8
 
9
9
  switch (field.type) {
10
+ case "decimal":
11
+ return optionalize(z.string().regex(/^-?\d+(?:\.\d+)?$/, "Invalid decimal value"));
10
12
  case "number":
11
13
  case "money": {
12
14
  let num = z.coerce.number();
@@ -27,6 +27,7 @@ export class AuthController {
27
27
  );
28
28
  }
29
29
 
30
+ @Throttle({ default: { limit: 20, ttl: 60000 } })
30
31
  @Post("refresh")
31
32
  refresh(@Body() dto: RefreshDto) {
32
33
  const realm = dto.realm ?? DEFAULT_AUTH_REALM;
@@ -35,8 +36,8 @@ export class AuthController {
35
36
 
36
37
  @UseGuards(AuthGuard)
37
38
  @Post("logout")
38
- logout(@CurrentUser() user: { id: string }, @Req() req: Request & { ip?: string; headers: Record<string, string> }) {
39
- return this.auth.logout(user.id, { ipAddress: req.ip, userAgent: req.headers["user-agent"] });
39
+ logout(@CurrentUser() user: RequestUser, @Req() req: Request & { ip?: string; headers: Record<string, string> }) {
40
+ return this.auth.logout(user.id, user.sessionId, { ipAddress: req.ip, userAgent: req.headers["user-agent"] });
40
41
  }
41
42
 
42
43
  @UseGuards(AuthGuard)
@@ -53,6 +54,7 @@ export class AuthController {
53
54
  return this.auth.membershipSummary(user.id);
54
55
  }
55
56
 
57
+ @Throttle({ default: { limit: 5, ttl: 60000 } })
56
58
  @Post("password/forgot")
57
59
  forgotPassword(@Body() dto: ForgotPasswordDto) {
58
60
  return this.auth.forgotPassword(dto.email);
@@ -26,7 +26,7 @@ export class AuthService {
26
26
  where: { email },
27
27
  include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
28
28
  });
29
- if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
29
+ if (!user || user.status !== "active" || !(await bcrypt.compare(password, user.passwordHash))) {
30
30
  throw new UnauthorizedException({ message: "Invalid email or password", code: "AUTH_INVALID" });
31
31
  }
32
32
  const assignments = user.roles.filter((ur) => ur.role.realm === realm);
@@ -69,44 +69,12 @@ export class AuthService {
69
69
  const oidcKey = `${issuer}::${profile.sub}`;
70
70
  const emailNorm = profile.email.toLowerCase().trim();
71
71
  let user = await this.prisma.user.findFirst({
72
- where: { OR: [{ oidcKey }, { email: emailNorm }] },
72
+ where: { oidcKey },
73
73
  include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
74
74
  });
75
75
 
76
- if (!user) {
77
- const randomPass = randomBytes(48).toString("hex");
78
- const created = await this.prisma.user.create({
79
- data: {
80
- email: emailNorm,
81
- name: profile.name ?? null,
82
- avatarUrl: profile.picture ?? null,
83
- passwordHash: await bcrypt.hash(randomPass, 12),
84
- oidcKey
85
- }
86
- });
87
- const roleName = this.config.get<string>("OIDC_DEFAULT_ROLE")?.trim() ?? "viewer";
88
- const role = await this.prisma.role.findUnique({
89
- where: { name_realm: { name: roleName, realm } }
90
- });
91
- if (role) {
92
- await this.prisma.userRole.create({ data: { userId: created.id, roleId: role.id } });
93
- }
94
- user = await this.prisma.user.findUniqueOrThrow({
95
- where: { id: created.id },
96
- include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
97
- });
98
- } else {
99
- const updates: { oidcKey?: string; avatarUrl?: string | null; name?: string | null } = {};
100
- if (!user.oidcKey) updates.oidcKey = oidcKey;
101
- if (profile.picture && !user.avatarUrl) updates.avatarUrl = profile.picture;
102
- if (profile.name && !user.name) updates.name = profile.name;
103
- if (Object.keys(updates).length) {
104
- await this.prisma.user.update({ where: { id: user.id }, data: updates });
105
- user = await this.prisma.user.findUniqueOrThrow({
106
- where: { id: user.id },
107
- include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
108
- });
109
- }
76
+ if (!user || user.status !== "active" || user.email.toLowerCase().trim() !== emailNorm) {
77
+ throw new UnauthorizedException({message:"A verified, pre-linked account is required",code:"OIDC_LINK_REQUIRED"});
110
78
  }
111
79
 
112
80
  const assignments = user.roles.filter((ur) => ur.role.realm === realm);
@@ -143,39 +111,68 @@ export class AuthService {
143
111
 
144
112
  async issueSession(userId: string, realm: string = DEFAULT_AUTH_REALM) {
145
113
  const refreshToken = randomBytes(48).toString("base64url");
146
- await this.prisma.user.update({
147
- where: { id: userId },
148
- data: { refreshTokenHash: await bcrypt.hash(refreshToken, 12) }
114
+ const session = await this.prisma.session.create({
115
+ data: {
116
+ userId, realm,
117
+ expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
118
+ tokens: { create: { tokenHash: this.hashToken(refreshToken) } }
119
+ }
149
120
  });
121
+ return this.sessionResponse(userId, realm, session.id, refreshToken);
122
+ }
123
+
124
+ private async sessionResponse(userId: string, realm: string, sessionId: string, refreshToken: string) {
150
125
  return {
151
- accessToken: await this.jwt.signAsync({ sub: userId, realm }),
126
+ accessToken: await this.jwt.signAsync({ sub: userId, realm, sid: sessionId }),
152
127
  refreshToken,
153
128
  expiresIn: 900
154
129
  };
155
130
  }
156
131
 
157
132
  async refresh(refreshToken: string, realm: string = DEFAULT_AUTH_REALM) {
158
- const users = await this.prisma.user.findMany({ where: { refreshTokenHash: { not: null } } });
159
- const user = await users.reduce<Promise<(typeof users)[number] | undefined>>(async (match, candidate) => {
160
- const found = await match;
161
- if (found) return found;
162
- return candidate.refreshTokenHash && (await bcrypt.compare(refreshToken, candidate.refreshTokenHash)) ? candidate : undefined;
163
- }, Promise.resolve(undefined));
164
- if (!user) throw new UnauthorizedException({ message: "Invalid refresh token", code: "REFRESH_INVALID" });
165
- return this.issueSession(user.id, realm);
133
+ const denied = () => new UnauthorizedException({ message: "Invalid refresh token", code: "REFRESH_INVALID" });
134
+ if (!/^[A-Za-z0-9_-]{64}$/.test(refreshToken)) throw denied();
135
+ const token = await this.prisma.sessionToken.findUnique({
136
+ where: { tokenHash: this.hashToken(refreshToken) },
137
+ include: { session: { include: { user: { include: { roles: { include: { role: true } } } } } } }
138
+ });
139
+ if (!token || token.session.realm !== realm || token.session.revokedAt || token.session.expiresAt <= new Date()) throw denied();
140
+ if (token.session.user.status !== "active" || !token.session.user.roles.some(r => r.role.realm === realm)) throw denied();
141
+ const nextToken = randomBytes(48).toString("base64url");
142
+ const rotated = await this.prisma.$transaction(async tx => {
143
+ // Lock/claim the family row first so refresh/logout/reuse are serialized.
144
+ const locked = await tx.session.updateMany({
145
+ where: { id: token.sessionId, realm, revokedAt: null, expiresAt: { gt: new Date() } },
146
+ data: { lastUsedAt: new Date() }
147
+ });
148
+ if (locked.count !== 1) return false;
149
+ const claimed = await tx.sessionToken.updateMany({
150
+ where: { id: token.id, usedAt: null },
151
+ data: { usedAt: new Date() }
152
+ });
153
+ if (claimed.count !== 1) {
154
+ // Commit revocation even when a rotated token is replayed.
155
+ await tx.session.update({ where: { id: token.sessionId }, data: { revokedAt: new Date() } });
156
+ return false;
157
+ }
158
+ await tx.sessionToken.create({ data: { sessionId: token.sessionId, tokenHash: this.hashToken(nextToken) } });
159
+ return true;
160
+ });
161
+ if (!rotated) throw denied();
162
+ return this.sessionResponse(token.session.userId, realm, token.sessionId, nextToken);
166
163
  }
167
164
 
168
- async logout(userId: string, meta: { ipAddress?: string; userAgent?: string }) {
169
- await this.prisma.user.update({ where: { id: userId }, data: { refreshTokenHash: null } });
170
- await this.prisma.auditLog.create({
171
- data: { userId, action: "logout", ipAddress: meta.ipAddress, userAgent: meta.userAgent }
165
+ async logout(userId: string, sessionId: string, meta: { ipAddress?: string; userAgent?: string }) {
166
+ await this.prisma.$transaction(async tx => {
167
+ await tx.session.updateMany({ where: { id: sessionId, userId, revokedAt: null }, data: { revokedAt: new Date() } });
168
+ await tx.auditLog.create({ data: { userId, action: "logout", ipAddress: meta.ipAddress, userAgent: meta.userAgent } });
172
169
  });
173
170
  return { ok: true };
174
171
  }
175
172
 
176
173
  async forgotPassword(email: string) {
177
174
  const user = await this.prisma.user.findUnique({ where: { email } });
178
- if (!user) return { ok: true, message: "If the email exists, reset instructions will be sent." };
175
+ if (!user || user.status !== "active") return { ok: true, message: "If the email exists, reset instructions will be sent." };
179
176
 
180
177
  const rawToken = randomBytes(32).toString("base64url");
181
178
  const tokenHash = this.hashToken(rawToken);
@@ -199,7 +196,6 @@ export class AuthService {
199
196
  });
200
197
  }
201
198
 
202
- if (process.env.NODE_ENV !== "production") return { ok: true, message: "Reset token generated", token: rawToken };
203
199
  return { ok: true, message: "If the email exists, reset instructions will be sent." };
204
200
  }
205
201
 
@@ -215,22 +211,17 @@ export class AuthService {
215
211
  include: { user: true }
216
212
  });
217
213
 
218
- if (!resetToken) throw new BadRequestException({ message: "Invalid or expired reset token", code: "RESET_TOKEN_INVALID" });
214
+ if (!resetToken || resetToken.user.status !== "active") throw new BadRequestException({ message: "Invalid or expired reset token", code: "RESET_TOKEN_INVALID" });
219
215
 
220
216
  const nextPasswordHash = await bcrypt.hash(password, 12);
221
- await this.prisma.$transaction([
222
- this.prisma.user.update({
223
- where: { id: resetToken.userId },
224
- data: { passwordHash: nextPasswordHash, refreshTokenHash: null }
225
- }),
226
- this.prisma.passwordResetToken.update({
227
- where: { id: resetToken.id },
228
- data: { usedAt: now }
229
- }),
230
- this.prisma.auditLog.create({
231
- data: { userId: resetToken.userId, action: "password.reset.completed", resource: "auth" }
232
- })
233
- ]);
217
+ await this.prisma.$transaction(async (tx) => {
218
+ const claimed = await tx.passwordResetToken.updateMany({ where: { id: resetToken.id, usedAt: null, expiresAt: { gt: new Date() } }, data: { usedAt: new Date() } });
219
+ if (claimed.count !== 1) throw new BadRequestException({ message: "Invalid or expired reset token", code: "RESET_TOKEN_INVALID" });
220
+ await tx.user.update({ where: { id: resetToken.userId }, data: { passwordHash: nextPasswordHash, refreshTokenHash: null } });
221
+ await tx.session.updateMany({ where: { userId: resetToken.userId, revokedAt: null }, data: { revokedAt: new Date() } });
222
+ await tx.passwordResetToken.updateMany({ where: { userId: resetToken.userId, usedAt: null }, data: { usedAt: new Date() } });
223
+ await tx.auditLog.create({ data: { userId: resetToken.userId, action: "password.reset.completed", resource: "auth" } });
224
+ });
234
225
 
235
226
  return { ok: true };
236
227
  }
@@ -247,19 +238,13 @@ export class AuthService {
247
238
  });
248
239
  if (!verification) throw new BadRequestException({ message: "Invalid or expired verification token", code: "VERIFY_TOKEN_INVALID" });
249
240
 
250
- await this.prisma.$transaction([
251
- this.prisma.emailVerificationToken.update({
252
- where: { id: verification.id },
253
- data: { usedAt: now }
254
- }),
255
- this.prisma.user.update({
256
- where: { id: verification.userId },
257
- data: { status: "active" }
258
- }),
259
- this.prisma.auditLog.create({
260
- data: { userId: verification.userId, action: "email.verified", resource: "auth" }
261
- })
262
- ]);
241
+ await this.prisma.$transaction(async tx => {
242
+ const claimed = await tx.emailVerificationToken.updateMany({ where: { id: verification.id, usedAt: null, expiresAt: { gt: new Date() } }, data: { usedAt: new Date() } });
243
+ if (claimed.count !== 1) throw new BadRequestException("Invalid or expired verification token");
244
+ const activated = await tx.user.updateMany({ where: { id: verification.userId, status: { in: ["pending", "unverified"] } }, data: { status: "active" } });
245
+ if (activated.count !== 1) throw new BadRequestException("Account is not awaiting verification");
246
+ await tx.auditLog.create({ data: { userId: verification.userId, action: "email.verified", resource: "auth" } });
247
+ });
263
248
 
264
249
  return { ok: true };
265
250
  }
@@ -269,7 +254,7 @@ export class AuthService {
269
254
  where: { id: userId },
270
255
  include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
271
256
  });
272
- if (!user) throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
257
+ if (!user || user.status !== "active") throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
273
258
  const assignments = user.roles.filter((ur) => ur.role.realm === realm);
274
259
  return {
275
260
  id: user.id,
@@ -289,7 +274,7 @@ export class AuthService {
289
274
  where: { id: userId },
290
275
  include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
291
276
  });
292
- if (!user) throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
277
+ if (!user || user.status !== "active") throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
293
278
  const byRealm = new Map<string, { roles: string[]; permissions: string[] }>();
294
279
  for (const ur of user.roles) {
295
280
  const r = ur.role.realm;
@@ -1,78 +1,16 @@
1
- import { Controller, Get, Inject, Query, Req, Res } from "@nestjs/common";
2
- import { SkipThrottle } from "@nestjs/throttler";
3
- import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
4
- import type { Request, Response } from "express";
1
+ import { Body,Controller,Get,Post,Inject,BadRequestException } from "@nestjs/common";
2
+ import { Throttle } from "@nestjs/throttler";
5
3
  import { SsoOidcService } from "./sso-oidc.service";
6
-
7
- @SkipThrottle({ default: true, perUser: true })
8
4
  @Controller("auth/sso/oidc")
9
5
  export class SsoOidcController {
10
- constructor(@Inject(SsoOidcService) private readonly sso: SsoOidcService) {}
11
-
12
- @Get("status")
13
- status() {
14
- return { enabled: this.sso.isEnabled() };
15
- }
16
-
17
- @Get("login")
18
- async login(
19
- @Query("realm") realm: string | undefined,
20
- @Res({ passthrough: false }) res: Response
21
- ) {
22
- const { authorizeUrl, setCookie } = await this.sso.startLogin(realm?.trim() || DEFAULT_AUTH_REALM);
23
- const secure = process.env.NODE_ENV === "production";
24
- res.cookie(setCookie.name, setCookie.value, {
25
- httpOnly: true,
26
- secure,
27
- sameSite: "lax",
28
- maxAge: setCookie.maxAge * 1000,
29
- path: "/"
30
- });
31
- return res.redirect(302, authorizeUrl);
32
- }
33
-
34
- @Get("callback")
35
- async callback(
36
- @Req() req: Request,
37
- @Query("code") code: string | undefined,
38
- @Query("state") state: string | undefined,
39
- @Res({ passthrough: false }) res: Response
40
- ) {
41
- const adminOrigin =
42
- (process.env.ADMIN_ORIGIN ?? "http://localhost:3000")
43
- .split(",")
44
- .map((s) => s.trim())
45
- .filter(Boolean)[0] ?? "http://localhost:3000";
46
- try {
47
- const session = await this.sso.handleCallback(req, code, state);
48
- res.clearCookie(this.sso.clearCookieName(), { path: "/" });
49
- const frag = new URLSearchParams({
50
- sso: "1",
51
- access_token: session.accessToken,
52
- refresh_token: session.refreshToken,
53
- realm: session.realm ?? "admin"
54
- });
55
- return res.redirect(302, `${adminOrigin}/login#${frag.toString()}`);
56
- } catch (error: unknown) {
57
- res.clearCookie(this.sso.clearCookieName(), { path: "/" });
58
- const payload =
59
- typeof error === "object" && error !== null && "getResponse" in error
60
- ? (error as { getResponse?: () => unknown }).getResponse?.()
61
- : null;
62
- const code =
63
- payload && typeof payload === "object" && "code" in payload
64
- ? String((payload as { code?: unknown }).code ?? "OIDC_CALLBACK")
65
- : "OIDC_CALLBACK";
66
- const message =
67
- payload && typeof payload === "object" && "message" in payload
68
- ? String((payload as { message?: unknown }).message ?? "Single Sign-On failed")
69
- : "Single Sign-On failed";
70
- const params = new URLSearchParams({
71
- sso_error: "1",
72
- sso_code: code,
73
- sso_message: message.slice(0, 180)
74
- });
75
- return res.redirect(302, `${adminOrigin}/login?${params.toString()}`);
76
- }
77
- }
6
+ constructor(@Inject(SsoOidcService) private readonly service:SsoOidcService){}
7
+ @Get("status") status(){return {enabled:this.service.isEnabled()};}
8
+ @Throttle({default:{limit:10,ttl:60000}})
9
+ @Post("start") start(){return this.service.startLogin();}
10
+ @Throttle({default:{limit:10,ttl:60000}})
11
+ @Post("exchange") exchange(@Body() body:Record<string,unknown>){
12
+ const {code,state,transaction,iss}=body??{};
13
+ if(typeof code!=="string"||!code||code.length>4096||typeof state!=="string"||!state||state.length>256||typeof transaction!=="string"||transaction.length>4096||(iss!==undefined&&typeof iss!=="string"))throw new BadRequestException("Invalid OIDC callback");
14
+ return this.service.handleCallback(code,state,transaction,iss as string|undefined);
15
+ }
78
16
  }