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.
- package/README.md +106 -151
- package/dist/adapt-package-manager.js +4 -1
- package/dist/create-project.d.ts +46 -0
- package/dist/create-project.js +417 -150
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +35 -6
- package/dist/index.d.ts +1 -0
- package/dist/index.js +257 -39
- package/dist/render-schema.d.ts +0 -17
- package/dist/render-schema.js +25 -29
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/package.json +14 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +4 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +10 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +12 -13
- package/template/apps/api/src/common/prisma.service.ts +9 -17
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +5 -4
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +6 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/adapt-package-manager.test.d.ts +0 -1
- package/dist/adapt-package-manager.test.js +0 -76
- package/dist/cli.e2e.test.d.ts +0 -1
- package/dist/cli.e2e.test.js +0 -87
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -275
- package/dist/database-providers.integration.test.d.ts +0 -1
- package/dist/database-providers.integration.test.js +0 -64
- package/dist/db-commands.test.d.ts +0 -1
- package/dist/db-commands.test.js +0 -27
- package/dist/doctor.test.d.ts +0 -1
- package/dist/doctor.test.js +0 -102
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -11
- package/dist/render-schema.test.d.ts +0 -1
- package/dist/render-schema.test.js +0 -57
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/dist/secrets.test.d.ts +0 -1
- package/dist/secrets.test.js +0 -36
- package/dist/security.test.d.ts +0 -1
- package/dist/security.test.js +0 -54
- package/dist/validate-name.test.d.ts +0 -1
- package/dist/validate-name.test.js +0 -63
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
- package/template/apps/api/src/common/prisma.service.test.ts +0 -19
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- 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 {
|
|
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
|
-
|
|
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:
|
|
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: {
|
|
72
|
+
where: { oidcKey },
|
|
73
73
|
include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
-
if (!user) {
|
|
77
|
-
|
|
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.
|
|
147
|
-
|
|
148
|
-
|
|
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
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
164
|
-
if (!
|
|
165
|
-
|
|
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
|
|
170
|
-
|
|
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
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
})
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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,
|
|
2
|
-
import {
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
}
|