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
@@ -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"
@@ -8,6 +8,7 @@ import {
8
8
  } from "@nestjs/common";
9
9
  import { ConfigService } from "@nestjs/config";
10
10
  import { Reflector } from "@nestjs/core";
11
+ import { GqlExecutionContext } from "@nestjs/graphql";
11
12
  import { JwtService } from "@nestjs/jwt";
12
13
  import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
13
14
  import { PrismaService } from "./prisma.service";
@@ -32,7 +33,7 @@ export class AuthGuard implements CanActivate {
32
33
  ) {}
33
34
 
34
35
  async canActivate(context: ExecutionContext): Promise<boolean> {
35
- const request = context.switchToHttp().getRequest();
36
+ const request = this.getRequest(context);
36
37
  const header = request.headers.authorization;
37
38
  const token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
38
39
  if (!token) throw new UnauthorizedException({ message: "Missing access token", code: "AUTH_REQUIRED" });
@@ -82,4 +83,17 @@ export class AuthGuard implements CanActivate {
82
83
  throw new UnauthorizedException({ message: "Invalid access token", code: "AUTH_INVALID" });
83
84
  }
84
85
  }
86
+
87
+ private getRequest(context: ExecutionContext): {
88
+ headers: { authorization?: string };
89
+ user?: RequestUser;
90
+ ip?: string;
91
+ } {
92
+ const type = context.getType<string>();
93
+ if (type === "graphql") {
94
+ const gql = GqlExecutionContext.create(context);
95
+ return gql.getContext<{ req: { headers: { authorization?: string }; user?: RequestUser; ip?: string } }>().req;
96
+ }
97
+ return context.switchToHttp().getRequest();
98
+ }
85
99
  }
@@ -1,6 +1,10 @@
1
1
  import { createParamDecorator, ExecutionContext } from "@nestjs/common";
2
+ import { GqlExecutionContext } from "@nestjs/graphql";
2
3
 
3
4
  export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
4
- const request = context.switchToHttp().getRequest();
5
- return request.user;
5
+ const type = context.getType<string>();
6
+ if (type === "graphql") {
7
+ return GqlExecutionContext.create(context).getContext<{ req: { user?: unknown } }>().req.user;
8
+ }
9
+ return context.switchToHttp().getRequest().user;
6
10
  });
@@ -0,0 +1,10 @@
1
+ import { Global, Module } from "@nestjs/common";
2
+ import { AppLoggerService } from "./app-logger.service";
3
+
4
+ @Global()
5
+ @Module({
6
+ providers: [AppLoggerService],
7
+ exports: [AppLoggerService]
8
+ })
9
+ export class LoggingModule {}
10
+
@@ -0,0 +1,70 @@
1
+ import {
2
+ CallHandler,
3
+ ExecutionContext,
4
+ Injectable,
5
+ NestInterceptor
6
+ } from "@nestjs/common";
7
+ import { Observable, catchError, tap, throwError } from "rxjs";
8
+ import { AppLoggerService } from "./app-logger.service";
9
+
10
+ @Injectable()
11
+ export class RequestLoggingInterceptor implements NestInterceptor {
12
+ constructor(private readonly logger: AppLoggerService) {}
13
+
14
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
15
+ if (context.getType() !== "http") return next.handle();
16
+ const req = context.switchToHttp().getRequest<{
17
+ method?: string;
18
+ url?: string;
19
+ ip?: string;
20
+ user?: { id?: string };
21
+ }>();
22
+ const res = context.switchToHttp().getResponse<{ statusCode?: number }>();
23
+ const started = Date.now();
24
+ const method = req.method ?? "UNKNOWN";
25
+ const path = req.url ?? "/";
26
+ const ip = req.ip ?? "";
27
+ const userId = req.user?.id;
28
+
29
+ return next.handle().pipe(
30
+ tap(() => {
31
+ const durationMs = Date.now() - started;
32
+ this.logger.info("request.completed", {
33
+ context: "http",
34
+ method,
35
+ path,
36
+ statusCode: res.statusCode ?? 200,
37
+ durationMs,
38
+ ip,
39
+ userId
40
+ });
41
+ }),
42
+ catchError((err: unknown) => {
43
+ const durationMs = Date.now() - started;
44
+ const statusCode =
45
+ typeof err === "object" && err !== null && "status" in err && typeof (err as { status?: number }).status === "number"
46
+ ? (err as { status: number }).status
47
+ : 500;
48
+ const message =
49
+ err instanceof Error
50
+ ? err.message
51
+ : typeof err === "object" && err !== null && "message" in err
52
+ ? String((err as { message?: unknown }).message ?? "unknown error")
53
+ : "unknown error";
54
+
55
+ this.logger.error("request.failed", {
56
+ context: "http",
57
+ method,
58
+ path,
59
+ statusCode,
60
+ durationMs,
61
+ ip,
62
+ userId,
63
+ errorMessage: message
64
+ });
65
+ return throwError(() => err);
66
+ })
67
+ );
68
+ }
69
+ }
70
+
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { AdminResourcesResolver } from "./admin-resources.resolver";
3
+
4
+ describe("AdminResourcesResolver", () => {
5
+ it("maps GraphQL filter input to REST-style filter query keys", async () => {
6
+ const adminResources = {
7
+ list: vi.fn().mockResolvedValue({ data: [], meta: { page: 1, limit: 20, total: 0, pages: 1 } })
8
+ };
9
+ const resolver = new AdminResourcesResolver(adminResources as never);
10
+ const user = { id: "u1", permissions: ["*"] };
11
+
12
+ await resolver.adminResourceList(
13
+ "posts",
14
+ user as never,
15
+ 2,
16
+ 15,
17
+ "hello",
18
+ "createdAt:desc",
19
+ "en",
20
+ {
21
+ status: { eq: "published" },
22
+ views: { gte: 10, lte: 100 },
23
+ authorId: "u1"
24
+ }
25
+ );
26
+
27
+ expect(adminResources.list).toHaveBeenCalledWith(
28
+ "posts",
29
+ {
30
+ page: 2,
31
+ limit: 15,
32
+ search: "hello",
33
+ sort: "createdAt:desc",
34
+ locale: "en",
35
+ "filter[status][eq]": "published",
36
+ "filter[views][gte]": 10,
37
+ "filter[views][lte]": 100,
38
+ "filter[authorId]": "u1"
39
+ },
40
+ user
41
+ );
42
+ });
43
+ });
44
+
@@ -0,0 +1,65 @@
1
+ import { UseGuards } from "@nestjs/common";
2
+ import { Args, Int, Query, Resolver } from "@nestjs/graphql";
3
+ import { GraphQLJSON } from "graphql-scalars";
4
+ import { AdminResourceService } from "../admin/admin-resource.service";
5
+ import { AuthGuard } from "../common/auth.guard";
6
+ import type { RequestUser } from "../common/auth.guard";
7
+ import { RequireAuthRealm } from "../common/auth-realm.decorator";
8
+ import { CurrentUser } from "../common/current-user.decorator";
9
+ import { resources } from "../resources/registry";
10
+
11
+ @Resolver()
12
+ @UseGuards(AuthGuard)
13
+ @RequireAuthRealm("admin")
14
+ export class AdminResourcesResolver {
15
+ constructor(private readonly adminResources: AdminResourceService) {}
16
+
17
+ private flattenFilters(input: unknown): Record<string, unknown> {
18
+ if (!input || typeof input !== "object" || Array.isArray(input)) return {};
19
+ const out: Record<string, unknown> = {};
20
+ for (const [field, raw] of Object.entries(input as Record<string, unknown>)) {
21
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
22
+ out[`filter[${field}]`] = raw;
23
+ continue;
24
+ }
25
+ for (const [op, val] of Object.entries(raw as Record<string, unknown>)) {
26
+ out[`filter[${field}][${op}]`] = val;
27
+ }
28
+ }
29
+ return out;
30
+ }
31
+
32
+ @Query(() => [String], { name: "adminRegisteredResourceNames" })
33
+ adminRegisteredResourceNames(@CurrentUser() user: RequestUser): string[] {
34
+ return resources
35
+ .filter(
36
+ (r) =>
37
+ Boolean(r.permissions.read) &&
38
+ (user.permissions.includes("*") || user.permissions.includes(r.permissions.read!))
39
+ )
40
+ .map((r) => r.name);
41
+ }
42
+
43
+ @Query(() => GraphQLJSON, { name: "adminResourceList", description: "Paginated list (same rules as REST /admin/resources/:name)" })
44
+ adminResourceList(
45
+ @Args("name") name: string,
46
+ @CurrentUser() user: RequestUser,
47
+ @Args("page", { type: () => Int, nullable: true, defaultValue: 1 }) page: number,
48
+ @Args("limit", { type: () => Int, nullable: true, defaultValue: 20 }) limit: number,
49
+ @Args("search", { nullable: true }) search?: string,
50
+ @Args("sort", { nullable: true }) sort?: string,
51
+ @Args("locale", { nullable: true }) locale?: string,
52
+ @Args("filter", { type: () => GraphQLJSON, nullable: true }) filter?: Record<string, unknown>
53
+ ) {
54
+ const query: Record<string, unknown> = { page, limit, ...this.flattenFilters(filter) };
55
+ if (search) query.search = search;
56
+ if (sort) query.sort = sort;
57
+ if (locale) query.locale = locale;
58
+ return this.adminResources.list(name, query, user);
59
+ }
60
+
61
+ @Query(() => GraphQLJSON, { name: "adminResourceRecord" })
62
+ adminResourceRecord(@Args("name") name: string, @Args("id") id: string, @CurrentUser() user: RequestUser) {
63
+ return this.adminResources.get(name, id, user);
64
+ }
65
+ }