openadminjs 0.1.24 → 0.3.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -81
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +118 -0
- package/dist/create-project.d.ts +77 -2
- package/dist/create-project.js +685 -224
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +26 -0
- package/dist/doctor.js +232 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +476 -166
- package/dist/render-schema.d.ts +3 -0
- package/dist/render-schema.js +33 -0
- 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/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/package.json +39 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +23 -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 +13 -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 +138 -0
- package/template/apps/api/src/common/prisma.service.ts +12 -7
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +14 -1
- 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 +8 -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/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -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/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -99
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -7
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- 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/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-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
|
@@ -1,281 +1,64 @@
|
|
|
1
1
|
import { BadRequestException, Inject, Injectable, UnauthorizedException } from "@nestjs/common";
|
|
2
2
|
import { ConfigService } from "@nestjs/config";
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
|
|
3
|
+
import { createHmac,timingSafeEqual } from "node:crypto";
|
|
4
|
+
import * as oidc from "openid-client";
|
|
6
5
|
import { AuthService } from "./auth.service";
|
|
7
6
|
|
|
8
|
-
|
|
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
|
-
|
|
7
|
+
type Transaction={verifier:string;state:string;nonce:string;expiresAt:number};
|
|
8
|
+
const fail=()=>new UnauthorizedException({message:"OIDC authentication failed",code:"OIDC_INVALID"});
|
|
60
9
|
@Injectable()
|
|
61
10
|
export class SsoOidcService {
|
|
62
|
-
constructor(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const issuer = this.
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
return
|
|
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;
|
|
11
|
+
constructor(@Inject(ConfigService) private readonly config:ConfigService,@Inject(AuthService) private readonly auth:AuthService){}
|
|
12
|
+
private env(name:string){return this.config.get<string>(name)?.trim()||"";}
|
|
13
|
+
private issuer(){return this.env("OIDC_ISSUER")||(this.env("OIDC_PROVIDER")==="google"?"https://accounts.google.com":"");}
|
|
14
|
+
isEnabled(){return this.env("OPENADMIN_OIDC_ENABLED")==="1"&&Boolean(this.issuer()&&this.env("OIDC_CLIENT_ID")&&this.env("OIDC_CLIENT_SECRET")&&this.env("OIDC_REDIRECT_URI")&&this.env("JWT_SECRET"));}
|
|
15
|
+
private settings(){
|
|
16
|
+
if(!this.isEnabled())throw new BadRequestException({message:"OIDC is disabled",code:"OIDC_DISABLED"});
|
|
17
|
+
const issuer=new URL(this.issuer()),redirect=new URL(this.env("OIDC_REDIRECT_URI"));
|
|
18
|
+
if(issuer.protocol!=="https:"||issuer.username||issuer.password||issuer.hash||issuer.search||redirect.pathname!=="/api/auth/oidc/callback"||redirect.hash||redirect.search||redirect.username||redirect.password||!(redirect.protocol==="https:"||(process.env.NODE_ENV!=="production"&&redirect.protocol==="http:"&&["localhost","127.0.0.1"].includes(redirect.hostname))))throw new BadRequestException("Invalid OIDC configuration");
|
|
19
|
+
const allowed=this.env("ADMIN_ORIGIN").split(",").map(x=>x.trim()).filter(Boolean);
|
|
20
|
+
if(allowed.length&&!allowed.includes(redirect.origin))throw new BadRequestException("OIDC redirect origin not allowed");
|
|
21
|
+
return {issuer,redirect};
|
|
91
22
|
}
|
|
92
|
-
|
|
93
|
-
|
|
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;
|
|
23
|
+
private async discovery(issuer:URL){
|
|
24
|
+
return oidc.discovery(issuer,this.env("OIDC_CLIENT_ID"),this.env("OIDC_CLIENT_SECRET"),oidc.ClientSecretPost(this.env("OIDC_CLIENT_SECRET")),{timeout:10,execute:[oidc.enableNonRepudiationChecks]});
|
|
103
25
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (explicit) return explicit;
|
|
108
|
-
const preset = this.resolvePreset();
|
|
109
|
-
if (preset?.issuer) return preset.issuer;
|
|
110
|
-
return undefined;
|
|
26
|
+
private seal(value:Transaction){
|
|
27
|
+
const body=Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
28
|
+
return body+"."+createHmac("sha256",this.env("JWT_SECRET")).update("oidc-v2:"+body).digest("base64url");
|
|
111
29
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
};
|
|
30
|
+
private unseal(raw:string,state:string):Transaction{
|
|
31
|
+
try{
|
|
32
|
+
if(raw.length>4096||state.length>256)throw fail();
|
|
33
|
+
const [body,sig,extra]=raw.split(".");
|
|
34
|
+
if(!body||!sig||extra!==undefined)throw fail();
|
|
35
|
+
const expected=createHmac("sha256",this.env("JWT_SECRET")).update("oidc-v2:"+body).digest();
|
|
36
|
+
const actual=Buffer.from(sig,"base64url");
|
|
37
|
+
if(actual.length!==expected.length||!timingSafeEqual(actual,expected))throw fail();
|
|
38
|
+
const t=JSON.parse(Buffer.from(body,"base64url").toString()) as Transaction;
|
|
39
|
+
if(t.state!==state||!t.verifier||!t.nonce||!Number.isFinite(t.expiresAt)||t.expiresAt<=Date.now())throw fail();
|
|
40
|
+
return t;
|
|
41
|
+
}catch{throw fail();}
|
|
148
42
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
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;
|
|
43
|
+
async startLogin(){
|
|
44
|
+
const {issuer,redirect}=this.settings();
|
|
45
|
+
const config=await this.discovery(issuer);
|
|
46
|
+
const transaction={verifier:oidc.randomPKCECodeVerifier(),state:oidc.randomState(),nonce:oidc.randomNonce(),expiresAt:Date.now()+600000};
|
|
47
|
+
const url=oidc.buildAuthorizationUrl(config,{redirect_uri:redirect.href,scope:"openid email profile",state:transaction.state,nonce:transaction.nonce,code_challenge:await oidc.calculatePKCECodeChallenge(transaction.verifier),code_challenge_method:"S256"});
|
|
48
|
+
return {authorizeUrl:url.href,transaction:this.seal(transaction)};
|
|
256
49
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
try
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
:
|
|
269
|
-
|
|
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
|
-
}
|
|
50
|
+
async handleCallback(code:string,state:string,transaction:string,iss?:string){
|
|
51
|
+
const {issuer,redirect}=this.settings();
|
|
52
|
+
const t=this.unseal(transaction,state);
|
|
53
|
+
try{
|
|
54
|
+
const config=await this.discovery(issuer);
|
|
55
|
+
const callback=new URL(redirect.href);
|
|
56
|
+
callback.searchParams.set("code",code);callback.searchParams.set("state",state);
|
|
57
|
+
if(iss)callback.searchParams.set("iss",iss);
|
|
58
|
+
const result=await oidc.authorizationCodeGrant(config,callback,{expectedState:t.state,expectedNonce:t.nonce,pkceCodeVerifier:t.verifier,idTokenExpected:true});
|
|
59
|
+
const claims=result.claims();
|
|
60
|
+
if(!claims||!claims.sub||!claims.iss||typeof claims.email!=="string"||claims.email_verified!==true)throw fail();
|
|
61
|
+
return await this.auth.loginWithOidcProfile({sub:claims.sub,issuer:claims.iss,email:claims.email,name:typeof claims.name==="string"?claims.name:null},{}, "admin");
|
|
62
|
+
}catch{throw fail();}
|
|
280
63
|
}
|
|
281
64
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ApiExceptionFilter } from "@openadminjs/nest";
|
|
@@ -10,12 +10,14 @@ import { ConfigService } from "@nestjs/config";
|
|
|
10
10
|
import { Reflector } from "@nestjs/core";
|
|
11
11
|
import { GqlExecutionContext } from "@nestjs/graphql";
|
|
12
12
|
import { JwtService } from "@nestjs/jwt";
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
13
14
|
import { DEFAULT_AUTH_REALM } from "@openadminjs/permissions";
|
|
14
15
|
import { PrismaService } from "./prisma.service";
|
|
15
16
|
import { AUTH_REALM_KEY } from "./auth-realm.decorator";
|
|
16
17
|
|
|
17
18
|
export type RequestUser = {
|
|
18
19
|
id: string;
|
|
20
|
+
sessionId: string;
|
|
19
21
|
email?: string;
|
|
20
22
|
name?: string | null;
|
|
21
23
|
realm: string;
|
|
@@ -37,51 +39,76 @@ export class AuthGuard implements CanActivate {
|
|
|
37
39
|
const header = request.headers.authorization;
|
|
38
40
|
const token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
|
|
39
41
|
if (!token) throw new UnauthorizedException({ message: "Missing access token", code: "AUTH_REQUIRED" });
|
|
42
|
+
if (token.startsWith("oajs_")) return this.authenticateApiToken(context,request,token);
|
|
43
|
+
const jwtSecret = this.config.get<string>("JWT_SECRET")?.trim() ?? process.env.JWT_SECRET?.trim();
|
|
44
|
+
let payload: { sub: string; realm?: string; sid?: string };
|
|
40
45
|
try {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
message: "Token was issued for a different application area",
|
|
52
|
-
code: "AUTH_REALM_MISMATCH",
|
|
53
|
-
details: { expected: requiredRealm, tokenRealm: realm }
|
|
54
|
-
});
|
|
55
|
-
}
|
|
46
|
+
payload = await this.jwt.verifyAsync<{ sub: string; realm?: string; sid?: string }>(token, { secret: jwtSecret });
|
|
47
|
+
} catch {
|
|
48
|
+
throw new UnauthorizedException({ message: "Invalid access token", code: "AUTH_INVALID" });
|
|
49
|
+
}
|
|
50
|
+
if (!payload || typeof payload.sub !== "string" || !payload.sub || typeof payload.sid !== "string" || !payload.sid || (payload.realm !== undefined && typeof payload.realm !== "string")) {
|
|
51
|
+
throw new UnauthorizedException({ message: "Invalid access token claims", code: "AUTH_INVALID" });
|
|
52
|
+
}
|
|
53
|
+
// Database/transport failures must propagate as server failures, not invalid credentials.
|
|
54
|
+
// Otherwise the BFF could revoke a valid browser session during a DB outage.
|
|
55
|
+
const realm = payload.realm ?? DEFAULT_AUTH_REALM;
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
57
|
+
const requiredRealm = this.reflector.getAllAndOverride<string | undefined>(AUTH_REALM_KEY, [
|
|
58
|
+
context.getHandler(),
|
|
59
|
+
context.getClass()
|
|
60
|
+
]);
|
|
61
|
+
if (requiredRealm !== undefined && requiredRealm !== realm) {
|
|
62
|
+
throw new ForbiddenException({
|
|
63
|
+
message: "Token was issued for a different application area",
|
|
64
|
+
code: "AUTH_REALM_MISMATCH",
|
|
65
|
+
details: { expected: requiredRealm, tokenRealm: realm }
|
|
60
66
|
});
|
|
61
|
-
|
|
67
|
+
}
|
|
62
68
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
details: { realm }
|
|
69
|
-
});
|
|
70
|
-
}
|
|
69
|
+
const user = await this.prisma.user.findUnique({
|
|
70
|
+
where: { id: payload.sub },
|
|
71
|
+
include: { roles: { include: { role: { include: { permissions: { include: { permission: true } } } } } } }
|
|
72
|
+
});
|
|
73
|
+
if (!user || user.status !== "active") throw new UnauthorizedException({ message: "Invalid session", code: "AUTH_INVALID" });
|
|
71
74
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (e instanceof ForbiddenException) throw e;
|
|
83
|
-
throw new UnauthorizedException({ message: "Invalid access token", code: "AUTH_INVALID" });
|
|
75
|
+
const session = await this.prisma.session.findFirst({ where: { id: payload.sid, userId: user.id, realm, revokedAt: null, expiresAt: { gt: new Date() } } });
|
|
76
|
+
if (!session) throw new UnauthorizedException("Session revoked or expired");
|
|
77
|
+
|
|
78
|
+
const assignments = user.roles.filter((ur) => ur.role.realm === realm);
|
|
79
|
+
if (assignments.length === 0) {
|
|
80
|
+
throw new ForbiddenException({
|
|
81
|
+
message: "No roles for this application area",
|
|
82
|
+
code: "AUTH_REALM_EMPTY",
|
|
83
|
+
details: { realm }
|
|
84
|
+
});
|
|
84
85
|
}
|
|
86
|
+
|
|
87
|
+
request.user = {
|
|
88
|
+
id: user.id,
|
|
89
|
+
sessionId: session.id,
|
|
90
|
+
email: user.email,
|
|
91
|
+
name: user.name,
|
|
92
|
+
realm,
|
|
93
|
+
roles: assignments.map((item) => item.role.name),
|
|
94
|
+
permissions: assignments.flatMap((item) => item.role.permissions.map((p) => p.permission.name))
|
|
95
|
+
} satisfies RequestUser;
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private async authenticateApiToken(context: ExecutionContext, request: {user?:RequestUser}, token:string) {
|
|
100
|
+
const denied = () => new UnauthorizedException("Invalid API token");
|
|
101
|
+
if (!/^oajs_[A-Za-z0-9_-]{43}$/.test(token) || context.getType() !== "http") throw denied();
|
|
102
|
+
const req = context.switchToHttp().getRequest<{method:string;path:string}>();
|
|
103
|
+
// Personal keys are intentionally read-only and cannot access auth, settings, jobs, AI or plugin APIs.
|
|
104
|
+
if (req.method !== "GET" || !/^\/admin\/resources(?:\/|$)/.test(req.path) || req.path === "/admin/resources/overview") throw new ForbiddenException("API token route not allowed");
|
|
105
|
+
const entry = await this.prisma.apiToken.findUnique({where:{tokenHash:createHash("sha256").update(token).digest("hex")},include:{user:{include:{roles:{include:{role:{include:{permissions:{include:{permission:true}}}}}}}}}});
|
|
106
|
+
if (!entry || entry.revokedAt || entry.user.status !== "active" || !Array.isArray(entry.scopes)) throw denied();
|
|
107
|
+
const live = entry.user.roles.filter(x=>x.role.realm==="admin").flatMap(x=>x.role.permissions.map(p=>p.permission.name));
|
|
108
|
+
const permissions = entry.scopes.filter((x):x is string=>typeof x==="string" && x.endsWith(".read") && !["api-tokens.read","settings.read","audit-logs.read","users.read","jobs.read","webhook-logs.read"].includes(x) && (live.includes("*")||live.includes(x)));
|
|
109
|
+
if (!permissions.length) throw denied();
|
|
110
|
+
request.user={id:entry.userId,sessionId:entry.id,realm:"admin",email:entry.user.email,roles:[],permissions};
|
|
111
|
+
return true;
|
|
85
112
|
}
|
|
86
113
|
|
|
87
114
|
private getRequest(context: ExecutionContext): {
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Legacy SQLite schemas used text for JSON columns. Older CLI versions rewrote Json / scalar-list columns to
|
|
3
|
+
* String when scaffolding for SQLite. This module JSON-encodes those columns on
|
|
4
|
+
* write and JSON-decodes them on read so the rest of the API keeps working with
|
|
5
|
+
* objects/arrays as on PostgreSQL/MySQL.
|
|
6
|
+
*
|
|
7
|
+
* On PostgreSQL and MySQL this module is a no-op (isSqliteDatabaseUrl is false).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Prisma Client delegate name (camelCase) → fields stored as JSON text on SQLite. */
|
|
11
|
+
export const SQLITE_JSON_FIELDS: Readonly<Record<string, readonly string[]>> = {
|
|
12
|
+
auditLog: ["before", "after"],
|
|
13
|
+
setting: ["value"],
|
|
14
|
+
apiToken: ["scopes"],
|
|
15
|
+
jobLog: ["payload"],
|
|
16
|
+
product: ["metadata"],
|
|
17
|
+
order: ["metadata"],
|
|
18
|
+
transaction: ["metadata"],
|
|
19
|
+
webhookLog: ["payload"],
|
|
20
|
+
aiMessage: ["meta"],
|
|
21
|
+
aiArtifact: ["meta"]
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export function isSqliteDatabaseUrl(url: string | undefined): boolean {
|
|
25
|
+
return (url ?? "").trim().toLowerCase().startsWith("file:");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function jsonFieldsForModel(model: string): readonly string[] {
|
|
29
|
+
return SQLITE_JSON_FIELDS[model] ?? [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function encodeValue(value: unknown): unknown {
|
|
33
|
+
if (value === null || value === undefined) return value;
|
|
34
|
+
return JSON.stringify(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function decodeValue(value: unknown): unknown {
|
|
38
|
+
if (value === null || value === undefined) return value;
|
|
39
|
+
if (typeof value !== "string") return value;
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse(value) as unknown;
|
|
42
|
+
} catch {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function encodeData(model: string, data: unknown): unknown {
|
|
48
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return data;
|
|
49
|
+
const fields = jsonFieldsForModel(model);
|
|
50
|
+
if (!fields.length) return data;
|
|
51
|
+
const copy = { ...(data as Record<string, unknown>) };
|
|
52
|
+
for (const field of fields) {
|
|
53
|
+
if (field in copy) copy[field] = encodeValue(copy[field]);
|
|
54
|
+
}
|
|
55
|
+
return copy;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function decodeRecord(model: string, record: unknown): unknown {
|
|
59
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) return record;
|
|
60
|
+
const fields = jsonFieldsForModel(model);
|
|
61
|
+
if (!fields.length) return record;
|
|
62
|
+
const copy = { ...(record as Record<string, unknown>) };
|
|
63
|
+
for (const field of fields) {
|
|
64
|
+
if (field in copy) copy[field] = decodeValue(copy[field]);
|
|
65
|
+
}
|
|
66
|
+
return copy;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function decodeMany(model: string, records: unknown): unknown {
|
|
70
|
+
if (!Array.isArray(records)) return records;
|
|
71
|
+
return records.map((r) => decodeRecord(model, r));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type QueryArgs = { data?: unknown; create?: unknown; update?: unknown };
|
|
75
|
+
|
|
76
|
+
/** Encodes JSON fields inside Prisma write args (`data`, `create`, `update`). */
|
|
77
|
+
export function encodeWriteArgs(model: string, args: QueryArgs): QueryArgs {
|
|
78
|
+
const next = { ...args };
|
|
79
|
+
if (next.data !== undefined) next.data = encodeData(model, next.data);
|
|
80
|
+
if (next.create !== undefined) next.create = encodeData(model, next.create);
|
|
81
|
+
if (next.update !== undefined) next.update = encodeData(model, next.update);
|
|
82
|
+
return next;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function decodeReadResult(model: string, result: unknown): unknown {
|
|
86
|
+
if (Array.isArray(result)) return decodeMany(model, result);
|
|
87
|
+
return decodeRecord(model, result);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type PrismaQueryHook = {
|
|
91
|
+
args: QueryArgs;
|
|
92
|
+
query: (args: QueryArgs) => Promise<unknown>;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** Prisma Client extension — only applied when DATABASE_URL is a SQLite file URL. */
|
|
96
|
+
export function sqliteJsonCodecExtension() {
|
|
97
|
+
const queryConfig: Record<string, Record<string, (ctx: PrismaQueryHook) => Promise<unknown>>> = {};
|
|
98
|
+
|
|
99
|
+
for (const model of Object.keys(SQLITE_JSON_FIELDS)) {
|
|
100
|
+
queryConfig[model] = {
|
|
101
|
+
async create({ args, query }) {
|
|
102
|
+
const result = await query(encodeWriteArgs(model, args));
|
|
103
|
+
return decodeRecord(model, result);
|
|
104
|
+
},
|
|
105
|
+
async createMany({ args, query }) {
|
|
106
|
+
if (args.data && Array.isArray(args.data)) {
|
|
107
|
+
return query({ ...args, data: args.data.map((row) => encodeData(model, row)) });
|
|
108
|
+
}
|
|
109
|
+
return query(args);
|
|
110
|
+
},
|
|
111
|
+
async update({ args, query }) {
|
|
112
|
+
const result = await query(encodeWriteArgs(model, args));
|
|
113
|
+
return decodeRecord(model, result);
|
|
114
|
+
},
|
|
115
|
+
async updateMany({ args, query }) {
|
|
116
|
+
return query(encodeWriteArgs(model, args));
|
|
117
|
+
},
|
|
118
|
+
async upsert({ args, query }) {
|
|
119
|
+
const result = await query(encodeWriteArgs(model, args));
|
|
120
|
+
return decodeRecord(model, result);
|
|
121
|
+
},
|
|
122
|
+
async findUnique({ args, query }) {
|
|
123
|
+
const result = await query(args);
|
|
124
|
+
return decodeRecord(model, result);
|
|
125
|
+
},
|
|
126
|
+
async findFirst({ args, query }) {
|
|
127
|
+
const result = await query(args);
|
|
128
|
+
return decodeRecord(model, result);
|
|
129
|
+
},
|
|
130
|
+
async findMany({ args, query }) {
|
|
131
|
+
const result = await query(args);
|
|
132
|
+
return decodeMany(model, result);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return { name: "sqliteJsonCodec", query: queryConfig };
|
|
138
|
+
}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
|
|
2
|
-
import { PrismaClient } from "@prisma/client";
|
|
2
|
+
import { Prisma, PrismaClient } from "@prisma/client";
|
|
3
|
+
import { isSqliteDatabaseUrl, sqliteJsonCodecExtension } from "./json-field-codec";
|
|
3
4
|
|
|
4
5
|
@Injectable()
|
|
5
6
|
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
constructor() {
|
|
8
|
+
super();
|
|
9
|
+
// Native JSON for new SQLite projects. Retain legacy compatibility only
|
|
10
|
+
// when the generated Prisma schema still uses text for old JSON fields.
|
|
11
|
+
const legacy = Prisma.dmmf.datamodel.models.find(model => model.name === "AuditLog")?.fields.some(field => field.name === "after" && field.type === "String");
|
|
12
|
+
if (isSqliteDatabaseUrl(process.env.DATABASE_URL) && legacy) {
|
|
13
|
+
return this.$extends(sqliteJsonCodecExtension() as Parameters<PrismaClient["$extends"]>[0]) as unknown as PrismaService;
|
|
14
|
+
}
|
|
12
15
|
}
|
|
16
|
+
async onModuleInit() { await this.$connect(); }
|
|
17
|
+
async onModuleDestroy() { await this.$disconnect(); }
|
|
13
18
|
}
|