openadminjs 0.1.15 → 0.1.17

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 (92) hide show
  1. package/dist/create-project.js +4 -1
  2. package/dist/index.js +127 -0
  3. package/package.json +2 -2
  4. package/template/apps/admin/.storybook/main.ts +12 -0
  5. package/template/apps/admin/.storybook/preview.ts +10 -0
  6. package/template/apps/admin/app/dashboard/page.tsx +357 -277
  7. package/template/apps/admin/app/layout.tsx +5 -1
  8. package/template/apps/admin/app/login/page.tsx +38 -0
  9. package/template/apps/admin/app/resources/[resource]/page.tsx +15 -1
  10. package/template/apps/admin/app/settings/page.tsx +40 -2
  11. package/template/apps/admin/app/system-logs/page.tsx +212 -0
  12. package/template/apps/admin/components/api-error-banner.tsx +26 -0
  13. package/template/apps/admin/components/app-shell.tsx +92 -18
  14. package/template/apps/admin/components/logo.stories.tsx +24 -0
  15. package/template/apps/admin/components/resource-form.tsx +47 -0
  16. package/template/apps/admin/components/resource-table.tsx +417 -44
  17. package/template/apps/admin/lib/api.ts +44 -1
  18. package/template/apps/admin/lib/resource-table-prefs.ts +57 -0
  19. package/template/apps/admin/package.json +6 -0
  20. package/template/apps/admin/storybook-static/370.e922f076.iframe.bundle.js +9 -0
  21. package/template/apps/admin/storybook-static/389.c0dd6bde.iframe.bundle.js +818 -0
  22. package/template/apps/admin/storybook-static/990.36428b6c.iframe.bundle.js +25 -0
  23. package/template/apps/admin/storybook-static/favicon-wrapper.svg +46 -0
  24. package/template/apps/admin/storybook-static/favicon.svg +1 -0
  25. package/template/apps/admin/storybook-static/iframe.html +560 -0
  26. package/template/apps/admin/storybook-static/index.html +139 -0
  27. package/template/apps/admin/storybook-static/index.json +1 -0
  28. package/template/apps/admin/storybook-static/logo-stories.c470fc8c.iframe.bundle.js +1 -0
  29. package/template/apps/admin/storybook-static/main.743ea6f2.iframe.bundle.js +2550 -0
  30. package/template/apps/admin/storybook-static/mocker-runtime-injected.js +2 -0
  31. package/template/apps/admin/storybook-static/nunito-sans-bold-italic.woff2 +0 -0
  32. package/template/apps/admin/storybook-static/nunito-sans-bold.woff2 +0 -0
  33. package/template/apps/admin/storybook-static/nunito-sans-italic.woff2 +0 -0
  34. package/template/apps/admin/storybook-static/nunito-sans-regular.woff2 +0 -0
  35. package/template/apps/admin/storybook-static/project.json +1 -0
  36. package/template/apps/admin/storybook-static/runtime~main.6f822e3b.iframe.bundle.js +2 -0
  37. package/template/apps/admin/storybook-static/sb-addons/onboarding-1/manager-bundle.js +97 -0
  38. package/template/apps/admin/storybook-static/sb-addons/storybook-core-server-presets-0/common-manager-bundle.js +630 -0
  39. package/template/apps/admin/storybook-static/sb-common-assets/favicon-wrapper.svg +46 -0
  40. package/template/apps/admin/storybook-static/sb-common-assets/favicon.svg +1 -0
  41. package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold-italic.woff2 +0 -0
  42. package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-bold.woff2 +0 -0
  43. package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-italic.woff2 +0 -0
  44. package/template/apps/admin/storybook-static/sb-common-assets/nunito-sans-regular.woff2 +0 -0
  45. package/template/apps/admin/storybook-static/sb-manager/globals-runtime.js +76309 -0
  46. package/template/apps/admin/storybook-static/sb-manager/globals.js +24 -0
  47. package/template/apps/admin/storybook-static/sb-manager/manager-stores.js +23 -0
  48. package/template/apps/admin/storybook-static/sb-manager/runtime.js +26078 -0
  49. package/template/apps/admin/storybook-static/sb-preview/globals.js +20 -0
  50. package/template/apps/admin/storybook-static/sb-preview/runtime.js +35472 -0
  51. package/template/apps/api/package.json +13 -2
  52. package/template/apps/api/plugins.manifest.example.json +12 -0
  53. package/template/apps/api/src/admin/admin-logs.controller.ts +31 -0
  54. package/template/apps/api/src/admin/admin-plugins.controller.ts +5 -0
  55. package/template/apps/api/src/admin/admin-plugins.service.ts +11 -0
  56. package/template/apps/api/src/admin/admin-resource.service.ts +235 -1
  57. package/template/apps/api/src/admin/admin.controller.ts +35 -0
  58. package/template/apps/api/src/admin/admin.module.ts +6 -3
  59. package/template/apps/api/src/admin/dto/resource-bulk.dto.ts +17 -0
  60. package/template/apps/api/src/admin/dto/resource-reorder.dto.ts +17 -0
  61. package/template/apps/api/src/admin/dto/resource-upload.dto.ts +20 -0
  62. package/template/apps/api/src/app.module.ts +45 -5
  63. package/template/apps/api/src/auth/auth.module.ts +5 -3
  64. package/template/apps/api/src/auth/auth.service.test.ts +6 -3
  65. package/template/apps/api/src/auth/auth.service.ts +84 -0
  66. package/template/apps/api/src/auth/sso-oidc.controller.ts +78 -0
  67. package/template/apps/api/src/auth/sso-oidc.service.test.ts +84 -0
  68. package/template/apps/api/src/auth/sso-oidc.service.ts +281 -0
  69. package/template/apps/api/src/common/app-logger.service.ts +138 -0
  70. package/template/apps/api/src/common/auth.guard.test.ts +1 -0
  71. package/template/apps/api/src/common/auth.guard.ts +15 -1
  72. package/template/apps/api/src/common/current-user.decorator.ts +6 -2
  73. package/template/apps/api/src/common/logging.module.ts +10 -0
  74. package/template/apps/api/src/common/request-logging.interceptor.ts +70 -0
  75. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +44 -0
  76. package/template/apps/api/src/graphql/admin-resources.resolver.ts +65 -0
  77. package/template/apps/api/src/graphql/graphql.module.ts +26 -0
  78. package/template/apps/api/src/main.ts +2 -0
  79. package/template/apps/api/src/plugins/bundled/registry.ts +3 -1
  80. package/template/apps/api/src/plugins/bundled/webhook.plugin.ts +64 -0
  81. package/template/apps/api/src/resources/categories.resource.ts +1 -0
  82. package/template/apps/api/src/resources/system.resource.ts +1 -0
  83. package/template/packages/core/src/index.ts +5 -0
  84. package/template/packages/core/vitest.config.ts +9 -0
  85. package/template/packages/resource/package.json +11 -0
  86. package/template/packages/resource/src/index.test.ts +45 -0
  87. package/template/packages/resource/src/index.ts +63 -0
  88. package/template/prisma/schema.prisma +5 -0
  89. package/template/packages/core/src/index.js +0 -1
  90. package/template/packages/permissions/src/blueprints.js +0 -57
  91. package/template/packages/permissions/src/index.js +0 -11
  92. package/template/packages/resource/src/index.js +0 -177
@@ -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
+
@@ -0,0 +1,281 @@
1
+ import { BadRequestException, Inject, Injectable, UnauthorizedException } from "@nestjs/common";
2
+ import { ConfigService } from "@nestjs/config";
3
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import type { Request } from "express";
5
+ import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
6
+ import { AuthService } from "./auth.service";
7
+
8
+ const COOKIE = "oajs_oidc";
9
+
10
+ type OidcDiscovery = {
11
+ issuer?: string;
12
+ authorization_endpoint: string;
13
+ token_endpoint: string;
14
+ userinfo_endpoint?: string;
15
+ };
16
+
17
+ type Sealed = { v: string; s: string; r: string; exp: number };
18
+ type OidcPreset = { issuer: string; scopes: string };
19
+
20
+ function base64url(buf: Buffer): string {
21
+ return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
22
+ }
23
+
24
+ function sealCookie(payload: object, secret: string): string {
25
+ const body = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
26
+ const sig = createHmac("sha256", secret).update(body).digest("base64url");
27
+ return `${body}.${sig}`;
28
+ }
29
+
30
+ function unsealCookie<T>(raw: string, secret: string): T | null {
31
+ const i = raw.lastIndexOf(".");
32
+ if (i <= 0) return null;
33
+ const body = raw.slice(0, i);
34
+ const sig = raw.slice(i + 1);
35
+ const expected = createHmac("sha256", secret).update(body).digest("base64url");
36
+ try {
37
+ if (sig.length !== expected.length || !timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) return null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ try {
42
+ return JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as T;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ function decodeJwtPayload(jwt: string): Record<string, unknown> | null {
49
+ const parts = jwt.split(".");
50
+ if (parts.length !== 3 || !parts[1]) return null;
51
+ try {
52
+ const pad = parts[1].length % 4 === 0 ? "" : "=".repeat(4 - (parts[1].length % 4));
53
+ const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/") + pad;
54
+ return JSON.parse(Buffer.from(b64, "base64").toString("utf8")) as Record<string, unknown>;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ @Injectable()
61
+ export class SsoOidcService {
62
+ constructor(
63
+ @Inject(ConfigService) private readonly config: ConfigService,
64
+ @Inject(AuthService) private readonly auth: AuthService
65
+ ) {}
66
+
67
+ isEnabled(): boolean {
68
+ const issuer = this.resolveIssuer();
69
+ const id = this.config.get<string>("OIDC_CLIENT_ID")?.trim();
70
+ const secret = this.config.get<string>("OIDC_CLIENT_SECRET")?.trim();
71
+ const redirect = this.config.get<string>("OIDC_REDIRECT_URI")?.trim();
72
+ return Boolean(issuer && id && secret && redirect);
73
+ }
74
+
75
+ private cookieSecret(): string {
76
+ const s = this.config.get<string>("JWT_SECRET")?.trim() ?? process.env.JWT_SECRET?.trim();
77
+ if (!s) throw new BadRequestException({ message: "JWT_SECRET required for OIDC state cookie", code: "OIDC_CONFIG" });
78
+ return s;
79
+ }
80
+
81
+ private async discover(issuerRaw: string): Promise<OidcDiscovery> {
82
+ const issuer = issuerRaw.replace(/\/$/, "");
83
+ if (process.env.NODE_ENV === "production" && !issuer.startsWith("https://")) {
84
+ throw new BadRequestException({ message: "OIDC_ISSUER must use https in production", code: "OIDC_CONFIG" });
85
+ }
86
+ const r = await fetch(`${issuer}/.well-known/openid-configuration`);
87
+ if (!r.ok) {
88
+ throw new BadRequestException({ message: "OpenID Connect discovery failed", code: "OIDC_DISCOVERY" });
89
+ }
90
+ return (await r.json()) as OidcDiscovery;
91
+ }
92
+
93
+ private resolvePreset(): OidcPreset | null {
94
+ const provider = this.config.get<string>("OIDC_PROVIDER")?.trim().toLowerCase();
95
+ if (!provider) return null;
96
+ const presets: Record<string, OidcPreset> = {
97
+ google: { issuer: "https://accounts.google.com", scopes: "openid email profile" },
98
+ microsoft: { issuer: "https://login.microsoftonline.com/common/v2.0", scopes: "openid email profile" },
99
+ auth0: { issuer: "", scopes: "openid email profile" },
100
+ okta: { issuer: "", scopes: "openid email profile" }
101
+ };
102
+ return presets[provider] ?? null;
103
+ }
104
+
105
+ private resolveIssuer(): string | undefined {
106
+ const explicit = this.config.get<string>("OIDC_ISSUER")?.trim();
107
+ if (explicit) return explicit;
108
+ const preset = this.resolvePreset();
109
+ if (preset?.issuer) return preset.issuer;
110
+ return undefined;
111
+ }
112
+
113
+ async startLogin(realm: string): Promise<{ authorizeUrl: string; setCookie: { name: string; value: string; maxAge: number } }> {
114
+ if (!this.isEnabled()) {
115
+ throw new BadRequestException({ message: "OIDC is not configured (set OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_REDIRECT_URI)", code: "OIDC_DISABLED" });
116
+ }
117
+ const issuer = this.resolveIssuer();
118
+ const clientId = this.config.get<string>("OIDC_CLIENT_ID")!.trim();
119
+ const redirectUri = this.config.get<string>("OIDC_REDIRECT_URI")!.trim();
120
+ if (!issuer) {
121
+ throw new BadRequestException({ message: "OIDC_ISSUER is required (or use OIDC_PROVIDER preset)", code: "OIDC_CONFIG" });
122
+ }
123
+ const scopes =
124
+ this.config.get<string>("OIDC_SCOPES")?.trim() ??
125
+ this.resolvePreset()?.scopes ??
126
+ "openid email profile";
127
+
128
+ const d = await this.discover(issuer);
129
+ const codeVerifier = base64url(randomBytes(32));
130
+ const codeChallenge = base64url(createHash("sha256").update(codeVerifier).digest());
131
+ const state = base64url(randomBytes(24));
132
+ const sealed: Sealed = { v: codeVerifier, s: state, r: realm || DEFAULT_AUTH_REALM, exp: Date.now() + 600_000 };
133
+ const cookie = sealCookie(sealed, this.cookieSecret());
134
+
135
+ const url = new URL(d.authorization_endpoint);
136
+ url.searchParams.set("response_type", "code");
137
+ url.searchParams.set("client_id", clientId);
138
+ url.searchParams.set("redirect_uri", redirectUri);
139
+ url.searchParams.set("scope", scopes);
140
+ url.searchParams.set("state", state);
141
+ url.searchParams.set("code_challenge", codeChallenge);
142
+ url.searchParams.set("code_challenge_method", "S256");
143
+
144
+ return {
145
+ authorizeUrl: url.toString(),
146
+ setCookie: { name: COOKIE, value: cookie, maxAge: 600 }
147
+ };
148
+ }
149
+
150
+ async handleCallback(req: Request, code: string | undefined, state: string | undefined) {
151
+ if (!this.isEnabled()) {
152
+ throw new BadRequestException({ message: "OIDC is not configured", code: "OIDC_DISABLED" });
153
+ }
154
+ if (!code || !state) {
155
+ throw new BadRequestException({ message: "Missing code or state", code: "OIDC_CALLBACK" });
156
+ }
157
+ if (!/^[A-Za-z0-9_-]{16,}$/.test(state)) {
158
+ throw new UnauthorizedException({ message: "Malformed OIDC state", code: "OIDC_STATE" });
159
+ }
160
+ const rawCookie = req.cookies?.[COOKIE] as string | undefined;
161
+ if (!rawCookie) {
162
+ throw new UnauthorizedException({ message: "Missing OIDC session cookie", code: "OIDC_COOKIE" });
163
+ }
164
+ const data = unsealCookie<Sealed>(rawCookie, this.cookieSecret());
165
+ if (!data || data.s !== state || data.exp < Date.now()) {
166
+ throw new UnauthorizedException({ message: "Invalid or expired OIDC state", code: "OIDC_STATE" });
167
+ }
168
+
169
+ const issuerRaw = this.resolveIssuer();
170
+ if (!issuerRaw) {
171
+ throw new BadRequestException({ message: "OIDC_ISSUER is required (or use OIDC_PROVIDER preset)", code: "OIDC_CONFIG" });
172
+ }
173
+ const issuer = issuerRaw.trim().replace(/\/$/, "");
174
+ const clientId = this.config.get<string>("OIDC_CLIENT_ID")!.trim();
175
+ const clientSecret = this.config.get<string>("OIDC_CLIENT_SECRET")!.trim();
176
+ const redirectUri = this.config.get<string>("OIDC_REDIRECT_URI")!.trim();
177
+
178
+ const d = await this.discover(issuer);
179
+ const body = new URLSearchParams({
180
+ grant_type: "authorization_code",
181
+ code,
182
+ redirect_uri: redirectUri,
183
+ client_id: clientId,
184
+ client_secret: clientSecret,
185
+ code_verifier: data.v
186
+ });
187
+
188
+ this.assertCallbackMatchesConfig(req, redirectUri);
189
+
190
+ const tr = await fetch(d.token_endpoint, {
191
+ method: "POST",
192
+ headers: { "content-type": "application/x-www-form-urlencoded" },
193
+ body
194
+ });
195
+ const tok = (await tr.json()) as {
196
+ access_token?: string;
197
+ id_token?: string;
198
+ token_type?: string;
199
+ error?: string;
200
+ error_description?: string;
201
+ };
202
+ if (!tr.ok) {
203
+ throw new UnauthorizedException({
204
+ message: tok.error_description ?? tok.error ?? "Token exchange failed",
205
+ code: "OIDC_TOKEN"
206
+ });
207
+ }
208
+ if (tok.token_type && tok.token_type.toLowerCase() !== "bearer") {
209
+ throw new UnauthorizedException({ message: "Unsupported token_type returned by provider", code: "OIDC_TOKEN" });
210
+ }
211
+
212
+ let sub = "";
213
+ let email = "";
214
+ let name: string | null = null;
215
+ let picture: string | null = null;
216
+
217
+ if (tok.id_token) {
218
+ const claims = decodeJwtPayload(tok.id_token);
219
+ if (claims) {
220
+ sub = String(claims.sub ?? "");
221
+ email = String(claims.email ?? "");
222
+ name = claims.name != null ? String(claims.name) : null;
223
+ picture = claims.picture != null ? String(claims.picture) : null;
224
+ }
225
+ }
226
+
227
+ if ((!email || !sub) && tok.access_token && d.userinfo_endpoint) {
228
+ const ui = await fetch(d.userinfo_endpoint, {
229
+ headers: { authorization: `Bearer ${tok.access_token}` }
230
+ });
231
+ if (ui.ok) {
232
+ const profile = (await ui.json()) as Record<string, unknown>;
233
+ sub = sub || String(profile.sub ?? "");
234
+ email = email || String(profile.email ?? "");
235
+ name = name ?? (profile.name != null ? String(profile.name) : null);
236
+ picture = picture ?? (profile.picture != null ? String(profile.picture) : null);
237
+ }
238
+ }
239
+
240
+ if (!sub || !email) {
241
+ throw new UnauthorizedException({
242
+ message: "IdP did not return sub and email (check scopes and claims)",
243
+ code: "OIDC_CLAIMS"
244
+ });
245
+ }
246
+
247
+ return this.auth.loginWithOidcProfile(
248
+ { sub, issuer, email, name, picture },
249
+ { ipAddress: req.ip, userAgent: req.headers["user-agent"] },
250
+ data.r || DEFAULT_AUTH_REALM
251
+ );
252
+ }
253
+
254
+ clearCookieName(): string {
255
+ return COOKIE;
256
+ }
257
+
258
+ private assertCallbackMatchesConfig(req: Request, redirectUri: string): void {
259
+ let expected: URL;
260
+ try {
261
+ expected = new URL(redirectUri);
262
+ } catch {
263
+ throw new BadRequestException({ message: "OIDC_REDIRECT_URI must be an absolute URL", code: "OIDC_CONFIG" });
264
+ }
265
+ const forwardedHost = req.headers["x-forwarded-host"];
266
+ const hostHeader = Array.isArray(forwardedHost)
267
+ ? forwardedHost[0]
268
+ : typeof forwardedHost === "string"
269
+ ? forwardedHost
270
+ : req.headers.host;
271
+ const host = hostHeader?.split(",")[0]?.trim();
272
+ const path = req.path;
273
+ if (!host || !path) return;
274
+ if (expected.host !== host || expected.pathname !== path) {
275
+ throw new UnauthorizedException({
276
+ message: "Callback request does not match configured OIDC_REDIRECT_URI",
277
+ code: "OIDC_CALLBACK_MISMATCH"
278
+ });
279
+ }
280
+ }
281
+ }
@@ -0,0 +1,138 @@
1
+ import { Injectable } from "@nestjs/common";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { createLogger, format, transports, type Logger } from "winston";
6
+ import DailyRotateFile from "winston-daily-rotate-file";
7
+
8
+ type LogLevel = "info" | "error";
9
+
10
+ type QueryLogsInput = {
11
+ level?: LogLevel;
12
+ search?: string;
13
+ from?: string;
14
+ to?: string;
15
+ page?: number;
16
+ limit?: number;
17
+ };
18
+
19
+ type ParsedLog = {
20
+ timestamp: string;
21
+ level: string;
22
+ message: string;
23
+ context?: string;
24
+ path?: string;
25
+ method?: string;
26
+ statusCode?: number;
27
+ durationMs?: number;
28
+ userId?: string;
29
+ ip?: string;
30
+ };
31
+
32
+ @Injectable()
33
+ export class AppLoggerService {
34
+ private readonly dir = join(process.cwd(), "logs");
35
+ private readonly logger: Logger;
36
+
37
+ constructor() {
38
+ this.ensureDir();
39
+ this.logger = createLogger({
40
+ level: "info",
41
+ format: format.combine(format.timestamp(), format.json()),
42
+ transports: [
43
+ new DailyRotateFile({
44
+ dirname: this.dir,
45
+ filename: "info-%DATE%.log",
46
+ datePattern: "YYYY-MM-DD",
47
+ level: "info",
48
+ maxFiles: "7d",
49
+ zippedArchive: false
50
+ }),
51
+ new DailyRotateFile({
52
+ dirname: this.dir,
53
+ filename: "error-%DATE%.log",
54
+ datePattern: "YYYY-MM-DD",
55
+ level: "error",
56
+ maxFiles: "30d",
57
+ zippedArchive: false
58
+ }),
59
+ ...(process.env.NODE_ENV !== "production"
60
+ ? [new transports.Console({ format: format.combine(format.colorize(), format.simple()) })]
61
+ : [])
62
+ ]
63
+ });
64
+ }
65
+
66
+ info(message: string, meta?: Record<string, unknown>) {
67
+ this.logger.info(message, meta);
68
+ }
69
+
70
+ error(message: string, meta?: Record<string, unknown>) {
71
+ this.logger.error(message, meta);
72
+ }
73
+
74
+ async query(input: QueryLogsInput) {
75
+ const level = input.level === "error" ? "error" : "info";
76
+ const page = Math.max(1, Number(input.page ?? 1));
77
+ const limit = Math.min(200, Math.max(1, Number(input.limit ?? 50)));
78
+ const search = input.search?.trim().toLowerCase() ?? "";
79
+ const fromMs = input.from ? Date.parse(input.from) : NaN;
80
+ const toMs = input.to ? Date.parse(input.to) : NaN;
81
+
82
+ const files = await this.pickFiles(level);
83
+ const all: ParsedLog[] = [];
84
+ for (const file of files) {
85
+ const full = join(this.dir, file);
86
+ const content = await readFile(full, "utf8").catch(() => "");
87
+ if (!content) continue;
88
+ const lines = content.split("\n");
89
+ for (const line of lines) {
90
+ if (!line.trim()) continue;
91
+ try {
92
+ const parsed = JSON.parse(line) as ParsedLog;
93
+ const ts = Date.parse(String(parsed.timestamp ?? ""));
94
+ if (!Number.isNaN(fromMs) && (Number.isNaN(ts) || ts < fromMs)) continue;
95
+ if (!Number.isNaN(toMs) && (Number.isNaN(ts) || ts > toMs + 86_400_000)) continue;
96
+ if (search) {
97
+ const blob = JSON.stringify(parsed).toLowerCase();
98
+ if (!blob.includes(search)) continue;
99
+ }
100
+ all.push(parsed);
101
+ } catch {
102
+ // skip malformed line
103
+ }
104
+ }
105
+ }
106
+
107
+ all.sort((a, b) => Date.parse(String(b.timestamp ?? 0)) - Date.parse(String(a.timestamp ?? 0)));
108
+ const total = all.length;
109
+ const start = (page - 1) * limit;
110
+ const data = all.slice(start, start + limit);
111
+ return {
112
+ data,
113
+ meta: {
114
+ page,
115
+ limit,
116
+ total,
117
+ pages: Math.max(1, Math.ceil(total / limit))
118
+ }
119
+ };
120
+ }
121
+
122
+ private async pickFiles(level: LogLevel): Promise<string[]> {
123
+ await this.ensureDir();
124
+ const entries = await readdir(this.dir).catch(() => []);
125
+ return entries
126
+ .filter((name) => name.startsWith(`${level}-`) && name.endsWith(".log"))
127
+ .sort()
128
+ .reverse()
129
+ .slice(0, level === "error" ? 31 : 8);
130
+ }
131
+
132
+ private async ensureDir() {
133
+ if (!existsSync(this.dir)) {
134
+ await mkdir(this.dir, { recursive: true });
135
+ }
136
+ }
137
+ }
138
+
@@ -8,6 +8,7 @@ function createContext(authHeader?: string, requiredRealm?: string) {
8
8
  return {
9
9
  request,
10
10
  ctx: {
11
+ getType: () => "http",
11
12
  switchToHttp: () => ({ getRequest: () => request }),
12
13
  getHandler: () => "handler",
13
14
  getClass: () => "class"