openadminjs 0.1.16 → 0.1.18

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/dist/create-project.js +4 -1
  3. package/dist/index.js +127 -0
  4. package/package.json +10 -11
  5. package/template/apps/admin/.storybook/main.ts +12 -0
  6. package/template/apps/admin/.storybook/preview.ts +10 -0
  7. package/template/apps/admin/app/dashboard/page.tsx +357 -277
  8. package/template/apps/admin/app/layout.tsx +5 -1
  9. package/template/apps/admin/app/login/page.tsx +38 -0
  10. package/template/apps/admin/app/resources/[resource]/page.tsx +15 -1
  11. package/template/apps/admin/app/settings/page.tsx +40 -2
  12. package/template/apps/admin/app/system-logs/page.tsx +212 -0
  13. package/template/apps/admin/components/api-error-banner.tsx +26 -0
  14. package/template/apps/admin/components/app-shell.tsx +92 -18
  15. package/template/apps/admin/components/logo.stories.tsx +24 -0
  16. package/template/apps/admin/components/resource-form.tsx +47 -0
  17. package/template/apps/admin/components/resource-table.tsx +417 -44
  18. package/template/apps/admin/lib/api.ts +44 -1
  19. package/template/apps/admin/lib/resource-table-prefs.ts +57 -0
  20. package/template/apps/admin/package.json +8 -2
  21. package/template/apps/api/package.json +28 -15
  22. package/template/apps/api/plugins.manifest.example.json +12 -0
  23. package/template/apps/api/prisma.config.ts +6 -0
  24. package/template/apps/api/src/admin/admin-ai.controller.ts +3 -2
  25. package/template/apps/api/src/admin/admin-logs.controller.ts +31 -0
  26. package/template/apps/api/src/admin/admin-plugins.controller.ts +5 -0
  27. package/template/apps/api/src/admin/admin-plugins.service.ts +11 -0
  28. package/template/apps/api/src/admin/admin-resource.service.ts +235 -1
  29. package/template/apps/api/src/admin/admin.controller.ts +35 -0
  30. package/template/apps/api/src/admin/admin.module.ts +6 -3
  31. package/template/apps/api/src/admin/dto/resource-bulk.dto.ts +17 -0
  32. package/template/apps/api/src/admin/dto/resource-reorder.dto.ts +17 -0
  33. package/template/apps/api/src/admin/dto/resource-upload.dto.ts +20 -0
  34. package/template/apps/api/src/app.module.ts +45 -5
  35. package/template/apps/api/src/auth/auth.module.ts +4 -2
  36. package/template/apps/api/src/auth/auth.service.test.ts +6 -3
  37. package/template/apps/api/src/auth/auth.service.ts +84 -0
  38. package/template/apps/api/src/auth/sso-oidc.controller.ts +78 -0
  39. package/template/apps/api/src/auth/sso-oidc.service.test.ts +84 -0
  40. package/template/apps/api/src/auth/sso-oidc.service.ts +281 -0
  41. package/template/apps/api/src/common/app-logger.service.ts +138 -0
  42. package/template/apps/api/src/common/auth.guard.test.ts +1 -0
  43. package/template/apps/api/src/common/auth.guard.ts +15 -1
  44. package/template/apps/api/src/common/current-user.decorator.ts +6 -2
  45. package/template/apps/api/src/common/logging.module.ts +10 -0
  46. package/template/apps/api/src/common/request-logging.interceptor.ts +70 -0
  47. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +44 -0
  48. package/template/apps/api/src/graphql/admin-resources.resolver.ts +65 -0
  49. package/template/apps/api/src/graphql/graphql.module.ts +26 -0
  50. package/template/apps/api/src/main.ts +2 -0
  51. package/template/apps/api/src/plugins/bundled/registry.ts +3 -1
  52. package/template/apps/api/src/plugins/bundled/webhook.plugin.ts +64 -0
  53. package/template/apps/api/src/resources/categories.resource.ts +1 -0
  54. package/template/apps/api/src/resources/system.resource.ts +1 -0
  55. package/template/apps/web/package.json +2 -2
  56. package/template/package.json +1 -1
  57. package/template/packages/auth/package.json +1 -1
  58. package/template/packages/brand/package.json +1 -1
  59. package/template/packages/brand/src/generate-assets.mjs +12 -5
  60. package/template/packages/core/package.json +1 -1
  61. package/template/packages/core/src/index.ts +5 -0
  62. package/template/packages/core/vitest.config.ts +9 -0
  63. package/template/packages/mail/package.json +3 -3
  64. package/template/packages/notifications/package.json +1 -1
  65. package/template/packages/permissions/package.json +1 -1
  66. package/template/packages/plugin-sdk/package.json +1 -1
  67. package/template/packages/queue/package.json +1 -1
  68. package/template/packages/resource/package.json +12 -1
  69. package/template/packages/resource/src/index.test.ts +45 -0
  70. package/template/packages/resource/src/index.ts +63 -0
  71. package/template/packages/storage/package.json +1 -1
  72. package/template/prisma/schema.prisma +5 -0
  73. package/template/packages/core/src/index.js +0 -1
  74. package/template/packages/permissions/src/blueprints.js +0 -57
  75. package/template/packages/permissions/src/index.js +0 -11
  76. package/template/packages/resource/src/index.js +0 -177
@@ -6,16 +6,18 @@ import { PermissionsGuard } from "../common/permissions.guard";
6
6
  import { CaslAbilityFactory } from "../common/casl-ability.factory";
7
7
  import { AdminController } from "./admin.controller";
8
8
  import { AdminAiController } from "./admin-ai.controller";
9
+ import { AdminLogsController } from "./admin-logs.controller";
9
10
  import { AdminPluginsController } from "./admin-plugins.controller";
10
11
  import { AdminPluginsService } from "./admin-plugins.service";
11
12
  import { AdminResourceService } from "./admin-resource.service";
12
13
  import { AdminAnalyticsService } from "./admin-analytics.service";
13
14
  import { AdminAiService } from "./admin-ai.service";
14
15
  import { PaymentModule } from "../store/payment/payment.module";
16
+ import { LoggingModule } from "../common/logging.module";
15
17
 
16
18
  @Module({
17
- imports: [JwtModule.register({}), PaymentModule],
18
- controllers: [AdminController, AdminPluginsController, AdminAiController],
19
+ imports: [JwtModule.register({}), PaymentModule, LoggingModule],
20
+ controllers: [AdminController, AdminPluginsController, AdminAiController, AdminLogsController],
19
21
  providers: [
20
22
  AdminResourceService,
21
23
  AdminAnalyticsService,
@@ -25,6 +27,7 @@ import { PaymentModule } from "../store/payment/payment.module";
25
27
  AuthGuard,
26
28
  PermissionsGuard,
27
29
  CaslAbilityFactory
28
- ]
30
+ ],
31
+ exports: [AdminResourceService]
29
32
  })
30
33
  export class AdminModule {}
@@ -0,0 +1,17 @@
1
+ import { ArrayMaxSize, ArrayMinSize, IsArray, IsObject, IsOptional, IsString } from "class-validator";
2
+
3
+ export class ResourceBulkDto {
4
+ /** Use `"delete"` for bulk delete, or a key from `resource.actions`. */
5
+ @IsString()
6
+ action!: string;
7
+
8
+ @IsArray()
9
+ @ArrayMinSize(1)
10
+ @ArrayMaxSize(200)
11
+ @IsString({ each: true })
12
+ ids!: string[];
13
+
14
+ @IsOptional()
15
+ @IsObject()
16
+ input?: Record<string, unknown>;
17
+ }
@@ -0,0 +1,17 @@
1
+ import { ArrayMaxSize, ArrayMinSize, IsArray, IsInt, IsOptional, IsString, Max, Min } from "class-validator";
2
+
3
+ export class ResourceReorderDto {
4
+ /** Ids in desired order (first = lowest `order` value). */
5
+ @IsArray()
6
+ @ArrayMinSize(1)
7
+ @ArrayMaxSize(500)
8
+ @IsString({ each: true })
9
+ ids!: string[];
10
+
11
+ /** When reordering a single page, pass `(page - 1) * pageSize` so `order` stays globally consistent. */
12
+ @IsOptional()
13
+ @IsInt()
14
+ @Min(0)
15
+ @Max(1_000_000)
16
+ baseIndex?: number;
17
+ }
@@ -0,0 +1,20 @@
1
+ import { IsOptional, IsString, MaxLength } from "class-validator";
2
+
3
+ export class ResourceUploadDto {
4
+ @IsString()
5
+ @MaxLength(260)
6
+ filename!: string;
7
+
8
+ @IsString()
9
+ @MaxLength(120)
10
+ mimeType!: string;
11
+
12
+ /** Base64 body without data-uri prefix. */
13
+ @IsString()
14
+ contentBase64!: string;
15
+
16
+ @IsOptional()
17
+ @IsString()
18
+ @MaxLength(260)
19
+ targetPath?: string;
20
+ }
@@ -3,12 +3,16 @@ import "./plugins/bootstrap";
3
3
  import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { Module } from "@nestjs/common";
6
- import { APP_INTERCEPTOR } from "@nestjs/core";
7
- import { ConfigModule } from "@nestjs/config";
8
- import { ThrottlerModule } from "@nestjs/throttler";
6
+ import { APP_GUARD, APP_INTERCEPTOR } from "@nestjs/core";
7
+ import { ConfigModule, ConfigService } from "@nestjs/config";
8
+ import { JwtService } from "@nestjs/jwt";
9
+ import { ThrottlerGuard, ThrottlerModule } from "@nestjs/throttler";
9
10
  import { PrismaService } from "./common/prisma.service";
11
+ import { LoggingModule } from "./common/logging.module";
12
+ import { RequestLoggingInterceptor } from "./common/request-logging.interceptor";
10
13
  import { AuthModule } from "./auth/auth.module";
11
14
  import { AdminModule } from "./admin/admin.module";
15
+ import { GraphqlApiModule } from "./graphql/graphql.module";
12
16
  import { HealthController } from "./health/health.controller";
13
17
  import { QueueModule } from "./queue/queue.module";
14
18
  import { StoreModule } from "./store/store.module";
@@ -25,9 +29,43 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
25
29
  isGlobal: true,
26
30
  envFilePath: envFilePath.length > 0 ? envFilePath : [".env"]
27
31
  }),
28
- ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]),
29
- MailModule,
32
+ LoggingModule,
30
33
  AuthModule,
34
+ ThrottlerModule.forRootAsync({
35
+ imports: [AuthModule],
36
+ inject: [JwtService, ConfigService],
37
+ useFactory: (jwt: JwtService, config: ConfigService) => [
38
+ {
39
+ name: "default",
40
+ ttl: 60_000,
41
+ limit: 100,
42
+ getTracker: (req: { ip?: string }) => req.ip ?? "unknown"
43
+ },
44
+ {
45
+ name: "perUser",
46
+ ttl: 60_000,
47
+ limit: Number(config.get("RATE_LIMIT_USER_PER_MIN") ?? 120),
48
+ getTracker: async (req: { headers?: { authorization?: string }; ip?: string }) => {
49
+ const h = req.headers?.authorization;
50
+ const t = h?.startsWith("Bearer ") ? h.slice(7) : undefined;
51
+ if (t) {
52
+ try {
53
+ const secret = config.get<string>("JWT_SECRET")?.trim();
54
+ if (secret) {
55
+ const p = await jwt.verifyAsync<{ sub?: string }>(t, { secret });
56
+ if (p.sub) return `user:${p.sub}`;
57
+ }
58
+ } catch {
59
+ /* use IP bucket for invalid JWT */
60
+ }
61
+ }
62
+ return `ip:${req.ip ?? "anon"}`;
63
+ }
64
+ }
65
+ ]
66
+ }),
67
+ GraphqlApiModule,
68
+ MailModule,
31
69
  AdminModule,
32
70
  QueueModule,
33
71
  StoreModule
@@ -35,6 +73,8 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
35
73
  controllers: [HealthController],
36
74
  providers: [
37
75
  PrismaService,
76
+ { provide: APP_GUARD, useClass: ThrottlerGuard },
77
+ { provide: APP_INTERCEPTOR, useClass: RequestLoggingInterceptor },
38
78
  {
39
79
  provide: APP_INTERCEPTOR,
40
80
  useClass: PluginApiInterceptor
@@ -6,6 +6,8 @@ import { PrismaService } from "../common/prisma.service";
6
6
  import { MailModule } from "../mail/mail.module";
7
7
  import { AuthController } from "./auth.controller";
8
8
  import { AuthService } from "./auth.service";
9
+ import { SsoOidcController } from "./sso-oidc.controller";
10
+ import { SsoOidcService } from "./sso-oidc.service";
9
11
 
10
12
  @Module({
11
13
  imports: [
@@ -24,8 +26,8 @@ import { AuthService } from "./auth.service";
24
26
  }
25
27
  })
26
28
  ],
27
- controllers: [AuthController],
28
- providers: [AuthService, PrismaService, AuthGuard],
29
+ controllers: [AuthController, SsoOidcController],
30
+ providers: [AuthService, SsoOidcService, PrismaService, AuthGuard],
29
31
  exports: [AuthService, AuthGuard, JwtModule]
30
32
  })
31
33
  export class AuthModule {}
@@ -39,7 +39,8 @@ describe("AuthService", () => {
39
39
  });
40
40
  bcryptCompareMock.mockResolvedValue(true);
41
41
 
42
- const service = new AuthService(prisma as never, jwt as never);
42
+ const config = { get: vi.fn().mockReturnValue(undefined) };
43
+ const service = new AuthService(prisma as never, jwt as never, config as never);
43
44
  const result = await service.login("openadminjs@proton.me", "password", {}, "admin");
44
45
 
45
46
  expect(result.accessToken).toBe("jwt");
@@ -59,7 +60,8 @@ describe("AuthService", () => {
59
60
  });
60
61
  bcryptCompareMock.mockResolvedValue(true);
61
62
 
62
- const service = new AuthService(prisma as never, jwt as never);
63
+ const config = { get: vi.fn().mockReturnValue(undefined) };
64
+ const service = new AuthService(prisma as never, jwt as never, config as never);
63
65
  await expect(service.login("openadminjs@proton.me", "password", {}, "admin")).rejects.toBeInstanceOf(UnauthorizedException);
64
66
  });
65
67
 
@@ -69,7 +71,8 @@ describe("AuthService", () => {
69
71
  prisma.user.findMany.mockResolvedValue([{ id: "u1", refreshTokenHash: "hash-1" }]);
70
72
  bcryptCompareMock.mockResolvedValue(false);
71
73
 
72
- const service = new AuthService(prisma as never, jwt as never);
74
+ const config = { get: vi.fn().mockReturnValue(undefined) };
75
+ const service = new AuthService(prisma as never, jwt as never, config as never);
73
76
  await expect(service.refresh("bad-token", "admin")).rejects.toBeInstanceOf(UnauthorizedException);
74
77
  });
75
78
  });
@@ -1,4 +1,5 @@
1
1
  import { BadRequestException, Inject, Injectable, Optional, UnauthorizedException } from "@nestjs/common";
2
+ import { ConfigService } from "@nestjs/config";
2
3
  import { JwtService } from "@nestjs/jwt";
3
4
  import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
4
5
  import bcrypt from "bcryptjs";
@@ -11,6 +12,7 @@ export class AuthService {
11
12
  constructor(
12
13
  @Inject(PrismaService) private readonly prisma: PrismaService,
13
14
  @Inject(JwtService) private readonly jwt: JwtService,
15
+ @Inject(ConfigService) private readonly config: ConfigService,
14
16
  @Optional() @Inject(MailService) private readonly mail?: MailService
15
17
  ) {}
16
18
 
@@ -57,6 +59,88 @@ export class AuthService {
57
59
  };
58
60
  }
59
61
 
62
+ /** OIDC / OAuth2 Authorization Code + PKCE — link by `oidcKey` or existing email. */
63
+ async loginWithOidcProfile(
64
+ profile: { sub: string; issuer: string; email: string; name?: string | null; picture?: string | null },
65
+ meta: { ipAddress?: string; userAgent?: string },
66
+ realm: string = DEFAULT_AUTH_REALM
67
+ ) {
68
+ const issuer = profile.issuer.replace(/\/$/, "");
69
+ const oidcKey = `${issuer}::${profile.sub}`;
70
+ const emailNorm = profile.email.toLowerCase().trim();
71
+ let user = await this.prisma.user.findFirst({
72
+ where: { OR: [{ oidcKey }, { email: emailNorm }] },
73
+ include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
74
+ });
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
+ }
110
+ }
111
+
112
+ const assignments = user.roles.filter((ur) => ur.role.realm === realm);
113
+ if (assignments.length === 0) {
114
+ throw new UnauthorizedException({
115
+ message: "OIDC account has no role in this realm. Ask an admin to assign a role.",
116
+ code: "AUTH_REALM_EMPTY"
117
+ });
118
+ }
119
+
120
+ const session = await this.issueSession(user.id, realm);
121
+ await this.prisma.auditLog.create({
122
+ data: {
123
+ userId: user.id,
124
+ action: "login.sso",
125
+ ipAddress: meta.ipAddress,
126
+ userAgent: meta.userAgent,
127
+ after: { realm, issuer, oidcKey }
128
+ }
129
+ });
130
+
131
+ return {
132
+ ...session,
133
+ realm,
134
+ user: {
135
+ id: user.id,
136
+ email: user.email,
137
+ name: user.name,
138
+ roles: assignments.map((item) => item.role.name),
139
+ permissions: assignments.flatMap((item) => item.role.permissions.map((permission) => permission.permission.name))
140
+ }
141
+ };
142
+ }
143
+
60
144
  async issueSession(userId: string, realm: string = DEFAULT_AUTH_REALM) {
61
145
  const refreshToken = randomBytes(48).toString("base64url");
62
146
  await this.prisma.user.update({
@@ -0,0 +1,78 @@
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";
5
+ import { SsoOidcService } from "./sso-oidc.service";
6
+
7
+ @SkipThrottle({ default: true, perUser: true })
8
+ @Controller("auth/sso/oidc")
9
+ 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
+ }
78
+ }
@@ -0,0 +1,84 @@
1
+ import { BadRequestException, UnauthorizedException } from "@nestjs/common";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { SsoOidcService } from "./sso-oidc.service";
4
+
5
+ function configMock(values: Record<string, string | undefined>) {
6
+ return {
7
+ get: vi.fn((key: string) => values[key])
8
+ };
9
+ }
10
+
11
+ describe("SsoOidcService", () => {
12
+ it("isEnabled uses provider preset issuer", () => {
13
+ const cfg = configMock({
14
+ OIDC_PROVIDER: "google",
15
+ OIDC_CLIENT_ID: "cid",
16
+ OIDC_CLIENT_SECRET: "sec",
17
+ OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback"
18
+ });
19
+ const auth = { loginWithOidcProfile: vi.fn() };
20
+ const service = new SsoOidcService(cfg as never, auth as never);
21
+ expect(service.isEnabled()).toBe(true);
22
+ });
23
+
24
+ it("startLogin fails without issuer or known preset", async () => {
25
+ const cfg = configMock({
26
+ OIDC_PROVIDER: "custom",
27
+ OIDC_CLIENT_ID: "cid",
28
+ OIDC_CLIENT_SECRET: "sec",
29
+ OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
30
+ JWT_SECRET: "jwt-secret"
31
+ });
32
+ const auth = { loginWithOidcProfile: vi.fn() };
33
+ const service = new SsoOidcService(cfg as never, auth as never);
34
+ await expect(service.startLogin("admin")).rejects.toBeInstanceOf(BadRequestException);
35
+ });
36
+
37
+ it("handleCallback rejects malformed state", async () => {
38
+ const cfg = configMock({
39
+ OIDC_ISSUER: "https://accounts.google.com",
40
+ OIDC_CLIENT_ID: "cid",
41
+ OIDC_CLIENT_SECRET: "sec",
42
+ OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
43
+ JWT_SECRET: "jwt-secret"
44
+ });
45
+ const auth = { loginWithOidcProfile: vi.fn() };
46
+ const service = new SsoOidcService(cfg as never, auth as never);
47
+ const req = { cookies: { oajs_oidc: "x.y" }, headers: {}, ip: "127.0.0.1", path: "/auth/sso/oidc/callback" };
48
+ await expect(service.handleCallback(req as never, "code", "bad")).rejects.toBeInstanceOf(UnauthorizedException);
49
+ });
50
+
51
+ it("handleCallback rejects callback host mismatch", async () => {
52
+ vi.stubGlobal(
53
+ "fetch",
54
+ vi.fn().mockResolvedValue({
55
+ ok: true,
56
+ json: async () => ({
57
+ authorization_endpoint: "https://accounts.google.com/o/oauth2/v2/auth",
58
+ token_endpoint: "https://oauth2.googleapis.com/token",
59
+ userinfo_endpoint: "https://openidconnect.googleapis.com/v1/userinfo"
60
+ })
61
+ })
62
+ );
63
+ const cfg = configMock({
64
+ OIDC_ISSUER: "https://accounts.google.com",
65
+ OIDC_CLIENT_ID: "cid",
66
+ OIDC_CLIENT_SECRET: "sec",
67
+ OIDC_REDIRECT_URI: "http://localhost:4000/auth/sso/oidc/callback",
68
+ JWT_SECRET: "jwt-secret"
69
+ });
70
+ const auth = { loginWithOidcProfile: vi.fn() };
71
+ const service = new SsoOidcService(cfg as never, auth as never);
72
+ const started = await service.startLogin("admin");
73
+ const state = new URL(started.authorizeUrl).searchParams.get("state") ?? "";
74
+ const req = {
75
+ cookies: { oajs_oidc: started.setCookie.value },
76
+ headers: { host: "evil.example.com" },
77
+ ip: "127.0.0.1",
78
+ path: "/auth/sso/oidc/callback"
79
+ };
80
+ await expect(service.handleCallback(req as never, "code", state)).rejects.toBeInstanceOf(UnauthorizedException);
81
+ vi.unstubAllGlobals();
82
+ });
83
+ });
84
+