@quatronic/sdk 0.7.0-rc.8 → 0.7.0-test.1a5da40
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/dist/auth/index.js +1 -1
- package/dist/{chunk-2AYDFLKR.js → chunk-F3NHTHFO.js} +6 -104
- package/dist/chunk-F3NHTHFO.js.map +1 -0
- package/dist/{chunk-5MNPBJYS.js → chunk-G7VPNC6M.js} +5 -11
- package/dist/{chunk-5MNPBJYS.js.map → chunk-G7VPNC6M.js.map} +1 -1
- package/dist/{chunk-ZZTO5Z3N.js → chunk-HQT57ITV.js} +2 -2
- package/dist/{chunk-EK6TGWWT.js → chunk-MET4SIMB.js} +2 -8
- package/dist/chunk-MET4SIMB.js.map +1 -0
- package/dist/chunk-P7HNHLW7.js +65 -0
- package/dist/chunk-P7HNHLW7.js.map +1 -0
- package/dist/chunk-QMOZDE3U.js +158 -0
- package/dist/chunk-QMOZDE3U.js.map +1 -0
- package/dist/{chunk-ROHIN74F.js → chunk-TEBDKNUB.js} +2 -2
- package/dist/chunk-TOBGX4CZ.js +109 -0
- package/dist/chunk-TOBGX4CZ.js.map +1 -0
- package/dist/chunk-WU7N4PET.js +20 -0
- package/dist/chunk-WU7N4PET.js.map +1 -0
- package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
- package/dist/cli/skills-postinstall.js +133 -3
- package/dist/cli/skills.js +133 -3
- package/dist/cli/sourcemaps.js +16 -6
- package/dist/eslint/index.js +2 -22
- package/dist/eslint/index.js.map +1 -1
- package/dist/integrations/index.d.ts +3 -75
- package/dist/integrations/index.js +6 -4
- package/dist/mail/index.d.ts +9 -0
- package/dist/mail/index.js +26 -0
- package/dist/mail/index.js.map +1 -0
- package/dist/next/auth/index.d.ts +12 -0
- package/dist/next/auth/index.js +15 -156
- package/dist/next/auth/index.js.map +1 -1
- package/dist/next/better-auth/index.js +1 -1
- package/dist/next/boot/index.d.ts +33 -0
- package/dist/next/boot/index.js +21 -0
- package/dist/next/boot/index.js.map +1 -0
- package/dist/next/connections/index.js +3 -3
- package/dist/next/db/index.d.ts +18 -1
- package/dist/next/db/index.js +25 -0
- package/dist/next/db/index.js.map +1 -1
- package/dist/next/global-error/index.d.ts +9 -0
- package/dist/next/global-error/index.js +17 -0
- package/dist/next/global-error/index.js.map +1 -0
- package/dist/next/integrations/index.d.ts +2 -1
- package/dist/next/integrations/index.js +6 -4
- package/dist/next/platform/index.d.ts +19 -0
- package/dist/next/platform/index.js +44 -0
- package/dist/next/platform/index.js.map +1 -0
- package/dist/next/security/index.d.ts +23 -1
- package/dist/next/security/index.js +41 -58
- package/dist/next/security/index.js.map +1 -1
- package/dist/next/sentry/client.d.ts +0 -1
- package/dist/next/sentry/client.js +2 -2
- package/dist/next/sentry/register.js +6 -14
- package/dist/next/sentry/register.js.map +1 -1
- package/dist/next/users/index.js +7 -4
- package/dist/next/users/index.js.map +1 -1
- package/dist/node/boot/index.d.ts +9 -0
- package/dist/node/boot/index.js +13 -0
- package/dist/node/boot/index.js.map +1 -0
- package/dist/node/connections/index.js +3 -3
- package/dist/node/identity/index.js +2 -2
- package/dist/node/integrations/index.d.ts +2 -1
- package/dist/node/integrations/index.js +6 -4
- package/dist/node/sentry/register.js +2 -2
- package/dist/node-Z7ERWJDZ.js +46 -0
- package/dist/node-Z7ERWJDZ.js.map +1 -0
- package/dist/types-CAwj03sM.d.ts +75 -0
- package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
- package/migrations/bootstrap-qore-env/instructions.md +28 -0
- package/migrations/bootstrap-qore-env/meta.json +7 -0
- package/migrations/global-error/codemod.mjs +28 -0
- package/migrations/global-error/instructions.md +26 -0
- package/migrations/global-error/meta.json +7 -0
- package/migrations/local-db-port/codemod.mjs +61 -0
- package/migrations/local-db-port/instructions.md +35 -0
- package/migrations/local-db-port/meta.json +7 -0
- package/migrations/mail-reexport/codemod.mjs +64 -0
- package/migrations/mail-reexport/instructions.md +27 -0
- package/migrations/mail-reexport/meta.json +7 -0
- package/migrations/platform-routes/codemod.mjs +45 -0
- package/migrations/platform-routes/instructions.md +30 -0
- package/migrations/platform-routes/meta.json +7 -0
- package/migrations/qore-boot/codemod.mjs +261 -0
- package/migrations/qore-boot/instructions.md +74 -0
- package/migrations/qore-boot/meta.json +7 -0
- package/migrations/qore-proxy/codemod.mjs +88 -0
- package/migrations/qore-proxy/instructions.md +56 -0
- package/migrations/qore-proxy/meta.json +7 -0
- package/migrations/run.mjs +322 -0
- package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
- package/migrations/sourcemaps-finalize/instructions.md +56 -0
- package/migrations/sourcemaps-finalize/meta.json +7 -0
- package/package.json +26 -8
- package/skills/qore-enable-auth-method/SKILL.md +4 -3
- package/skills/qore-use-mail-domain/SKILL.next.md +4 -4
- package/workspace-requirements.json +4 -0
- package/dist/chunk-2AYDFLKR.js.map +0 -1
- package/dist/chunk-EK6TGWWT.js.map +0 -1
- package/dist/observability/index.d.ts +0 -10
- package/dist/observability/index.js +0 -7
- package/dist/observability/index.js.map +0 -1
- package/migrations/report-error/codemod.mjs +0 -94
- package/migrations/report-error/instructions.md +0 -46
- package/migrations/report-error/meta.json +0 -6
- /package/dist/{chunk-ZZTO5Z3N.js.map → chunk-HQT57ITV.js.map} +0 -0
- /package/dist/{chunk-ROHIN74F.js.map → chunk-TEBDKNUB.js.map} +0 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { I as IntegrationMap } from '../../types-CAwj03sM.js';
|
|
2
|
+
export { onRequestError } from '../sentry/register.js';
|
|
3
|
+
import '@sentry/nextjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The app-specific parts of boot. Each is a loader (`() => import(...)`), so
|
|
7
|
+
* nothing is imported until the Node runtime asks for it, in this order:
|
|
8
|
+
* integrations, env, auth migrations, app migrations, seed.
|
|
9
|
+
*/
|
|
10
|
+
interface NodeBoot {
|
|
11
|
+
/** `() => import("@/config/integrations")` */
|
|
12
|
+
integrations?: () => Promise<{
|
|
13
|
+
integrations: IntegrationMap;
|
|
14
|
+
}>;
|
|
15
|
+
/** `() => import("@/config/env")`; validated before anything touches the database. */
|
|
16
|
+
env?: () => Promise<{
|
|
17
|
+
serverEnv: () => unknown;
|
|
18
|
+
}>;
|
|
19
|
+
/** Run the SDK's own auth-schema migrations (Keycloak apps). */
|
|
20
|
+
authMigrations?: boolean;
|
|
21
|
+
/** `() => import("./lib/migrate")` */
|
|
22
|
+
migrations?: () => Promise<{
|
|
23
|
+
runAppMigrations: () => Promise<void>;
|
|
24
|
+
}>;
|
|
25
|
+
/** `() => import("./scripts/seed")`; runs only when `QORE_RUN_SEED=true` (previews). */
|
|
26
|
+
seed?: () => Promise<{
|
|
27
|
+
default: () => Promise<void>;
|
|
28
|
+
}>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
declare function qoreRegister(node?: NodeBoot): Promise<void>;
|
|
32
|
+
|
|
33
|
+
export { type NodeBoot, qoreRegister };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
onRequestError,
|
|
3
|
+
register
|
|
4
|
+
} from "../../chunk-WU7N4PET.js";
|
|
5
|
+
import "../../chunk-G7VPNC6M.js";
|
|
6
|
+
import "../../chunk-MET4SIMB.js";
|
|
7
|
+
import "../../chunk-7ASQHY7O.js";
|
|
8
|
+
|
|
9
|
+
// src/next/boot/index.ts
|
|
10
|
+
async function qoreRegister(node) {
|
|
11
|
+
await register();
|
|
12
|
+
if (process.env.NEXT_RUNTIME === "nodejs" && node) {
|
|
13
|
+
const { bootNode } = await import("../../node-Z7ERWJDZ.js");
|
|
14
|
+
await bootNode(node);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
onRequestError,
|
|
19
|
+
qoreRegister
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/boot/index.ts"],"sourcesContent":["// The body of a Next app's `src/instrumentation.ts`. The app passes what only\n// it can name (its env, migrations, seed); the platform's own boot steps live\n// here, so a new one reaches every app as an SDK release.\n//\n// export async function register() {\n// await qoreRegister(process.env.NEXT_RUNTIME === \"nodejs\" ? { ...loaders } : undefined)\n// // the app's own boot code, after migrations\n// }\n//\n// The ternary in the app file, and the `if` below, are what keep the Node-only\n// loaders out of the edge bundle: Next replaces NEXT_RUNTIME at build time and\n// the bundler drops the dead branch with its imports.\nimport { register as registerSentry } from \"../sentry/register\"\nimport type { NodeBoot } from \"./types\"\n\nexport { onRequestError } from \"../sentry/register\"\nexport type { NodeBoot } from \"./types\"\n\nexport async function qoreRegister(node?: NodeBoot): Promise<void> {\n await registerSentry()\n if (process.env.NEXT_RUNTIME === \"nodejs\" && node) {\n const { bootNode } = await import(\"./node\")\n await bootNode(node)\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,eAAsB,aAAa,MAAgC;AACjE,QAAM,SAAe;AACrB,MAAI,QAAQ,IAAI,iBAAiB,YAAY,MAAM;AACjD,UAAM,EAAE,SAAS,IAAI,MAAM,OAAO,wBAAQ;AAC1C,UAAM,SAAS,IAAI;AAAA,EACrB;AACF;","names":[]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
assertConnections,
|
|
4
4
|
assertInboundConnection,
|
|
5
5
|
connection
|
|
6
|
-
} from "../../chunk-
|
|
6
|
+
} from "../../chunk-HQT57ITV.js";
|
|
7
7
|
import {
|
|
8
8
|
CONNECTION_REJECTED_ATTR,
|
|
9
9
|
CONNECTION_REJECT_REASON_ATTR,
|
|
@@ -11,9 +11,9 @@ import {
|
|
|
11
11
|
ConnectionError,
|
|
12
12
|
DEFAULT_CONNECTION_TIMEOUT_MS,
|
|
13
13
|
requireConnection
|
|
14
|
-
} from "../../chunk-
|
|
14
|
+
} from "../../chunk-TEBDKNUB.js";
|
|
15
15
|
import "../../chunk-5XMTUPIY.js";
|
|
16
|
-
import "../../chunk-
|
|
16
|
+
import "../../chunk-MET4SIMB.js";
|
|
17
17
|
export {
|
|
18
18
|
CONNECTION_REJECTED_ATTR,
|
|
19
19
|
CONNECTION_REJECT_REASON_ATTR,
|
package/dist/next/db/index.d.ts
CHANGED
|
@@ -9,4 +9,21 @@ declare function createMigrationDb(databaseUrl: string): MigrationDb;
|
|
|
9
9
|
declare function parseRoleFromUrl(databaseUrl: string): string;
|
|
10
10
|
declare function grantRuntimeDefaultPrivileges(db: NodePgDatabase, schema: string, runtimeRole: string): Promise<void>;
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
interface MigrateAppOptions {
|
|
13
|
+
/** The Postgres schema the app's tables live in (`appSchema.schemaName`, or `"public"`). */
|
|
14
|
+
schema: string;
|
|
15
|
+
/** Defaults to `<cwd>/src/db/migrations`, where `pnpm db:generate` writes. */
|
|
16
|
+
migrationsFolder?: string;
|
|
17
|
+
/** The runtime role's DSN. Defaults to `DATABASE_URL`. */
|
|
18
|
+
databaseUrl?: string;
|
|
19
|
+
/** The migrator role's DSN. Defaults to `MIGRATION_DATABASE_URL`. */
|
|
20
|
+
migrationDatabaseUrl?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Applies the app's drizzle-kit migrations as the migrator role, then grants
|
|
24
|
+
* the runtime role access to what they created. Safe on every boot: drizzle
|
|
25
|
+
* skips applied migrations and the grant is a no-op when both roles are one.
|
|
26
|
+
*/
|
|
27
|
+
declare function migrateApp(options: MigrateAppOptions): Promise<void>;
|
|
28
|
+
|
|
29
|
+
export { type MigrateAppOptions, type MigrationDb, createMigrationDb, grantRuntimeDefaultPrivileges, migrateApp, parseRoleFromUrl };
|
package/dist/next/db/index.js
CHANGED
|
@@ -7,10 +7,35 @@ import {
|
|
|
7
7
|
isNorthflankManagedPostgres,
|
|
8
8
|
resolvePostgresConfig
|
|
9
9
|
} from "../../chunk-4MBB2UQW.js";
|
|
10
|
+
|
|
11
|
+
// src/db-core/migrate-app.ts
|
|
12
|
+
import { join } from "path";
|
|
13
|
+
import { migrate } from "drizzle-orm/node-postgres/migrator";
|
|
14
|
+
function required(value, key) {
|
|
15
|
+
if (!value) throw new Error(`migrateApp: ${key} is required`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
async function migrateApp(options) {
|
|
19
|
+
const databaseUrl = required(options.databaseUrl ?? process.env.DATABASE_URL, "DATABASE_URL");
|
|
20
|
+
const migrationUrl = required(
|
|
21
|
+
options.migrationDatabaseUrl ?? process.env.MIGRATION_DATABASE_URL,
|
|
22
|
+
"MIGRATION_DATABASE_URL"
|
|
23
|
+
);
|
|
24
|
+
const { db, close } = createMigrationDb(migrationUrl);
|
|
25
|
+
try {
|
|
26
|
+
await migrate(db, {
|
|
27
|
+
migrationsFolder: options.migrationsFolder ?? join(process.cwd(), "src/db/migrations")
|
|
28
|
+
});
|
|
29
|
+
await grantRuntimeDefaultPrivileges(db, options.schema, parseRoleFromUrl(databaseUrl));
|
|
30
|
+
} finally {
|
|
31
|
+
await close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
10
34
|
export {
|
|
11
35
|
createMigrationDb,
|
|
12
36
|
grantRuntimeDefaultPrivileges,
|
|
13
37
|
isNorthflankManagedPostgres,
|
|
38
|
+
migrateApp,
|
|
14
39
|
parseRoleFromUrl,
|
|
15
40
|
resolvePostgresConfig
|
|
16
41
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/db-core/migrate-app.ts"],"sourcesContent":["import { join } from \"node:path\"\nimport { migrate } from \"drizzle-orm/node-postgres/migrator\"\nimport { createMigrationDb, grantRuntimeDefaultPrivileges, parseRoleFromUrl } from \"./migration-db\"\n\nexport interface MigrateAppOptions {\n /** The Postgres schema the app's tables live in (`appSchema.schemaName`, or `\"public\"`). */\n schema: string\n /** Defaults to `<cwd>/src/db/migrations`, where `pnpm db:generate` writes. */\n migrationsFolder?: string\n /** The runtime role's DSN. Defaults to `DATABASE_URL`. */\n databaseUrl?: string\n /** The migrator role's DSN. Defaults to `MIGRATION_DATABASE_URL`. */\n migrationDatabaseUrl?: string\n}\n\nfunction required(value: string | undefined, key: string): string {\n if (!value) throw new Error(`migrateApp: ${key} is required`)\n return value\n}\n\n/**\n * Applies the app's drizzle-kit migrations as the migrator role, then grants\n * the runtime role access to what they created. Safe on every boot: drizzle\n * skips applied migrations and the grant is a no-op when both roles are one.\n */\nexport async function migrateApp(options: MigrateAppOptions): Promise<void> {\n const databaseUrl = required(options.databaseUrl ?? process.env.DATABASE_URL, \"DATABASE_URL\")\n const migrationUrl = required(\n options.migrationDatabaseUrl ?? process.env.MIGRATION_DATABASE_URL,\n \"MIGRATION_DATABASE_URL\",\n )\n const { db, close } = createMigrationDb(migrationUrl)\n try {\n await migrate(db, {\n migrationsFolder: options.migrationsFolder ?? join(process.cwd(), \"src/db/migrations\"),\n })\n await grantRuntimeDefaultPrivileges(db, options.schema, parseRoleFromUrl(databaseUrl))\n } finally {\n await close()\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAe;AAcxB,SAAS,SAAS,OAA2B,KAAqB;AAChE,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,eAAe,GAAG,cAAc;AAC5D,SAAO;AACT;AAOA,eAAsB,WAAW,SAA2C;AAC1E,QAAM,cAAc,SAAS,QAAQ,eAAe,QAAQ,IAAI,cAAc,cAAc;AAC5F,QAAM,eAAe;AAAA,IACnB,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,EAAE,IAAI,MAAM,IAAI,kBAAkB,YAAY;AACpD,MAAI;AACF,UAAM,QAAQ,IAAI;AAAA,MAChB,kBAAkB,QAAQ,oBAAoB,KAAK,QAAQ,IAAI,GAAG,mBAAmB;AAAA,IACvF,CAAC;AACD,UAAM,8BAA8B,IAAI,QAAQ,QAAQ,iBAAiB,WAAW,CAAC;AAAA,EACvF,UAAE;AACA,UAAM,MAAM;AAAA,EACd;AACF;","names":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/next/global-error/index.tsx
|
|
4
|
+
import { useEffect } from "react";
|
|
5
|
+
import NextError from "next/error";
|
|
6
|
+
import * as Sentry from "@sentry/nextjs";
|
|
7
|
+
import { jsx } from "react/jsx-runtime";
|
|
8
|
+
function GlobalError({ error }) {
|
|
9
|
+
useEffect(() => {
|
|
10
|
+
Sentry.captureException(error);
|
|
11
|
+
}, [error]);
|
|
12
|
+
return /* @__PURE__ */ jsx("html", { lang: "en", children: /* @__PURE__ */ jsx("body", { children: /* @__PURE__ */ jsx(NextError, { statusCode: 0 }) }) });
|
|
13
|
+
}
|
|
14
|
+
export {
|
|
15
|
+
GlobalError as default
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/global-error/index.tsx"],"sourcesContent":["\"use client\"\n// The page Next renders when the root layout itself throws. The app's\n// `src/app/global-error.tsx` re-exports this under its own \"use client\"\n// (bundling drops the directive here), so how a crash is reported and shown\n// changes with an SDK release.\nimport { useEffect } from \"react\"\nimport NextError from \"next/error\"\nimport * as Sentry from \"@sentry/nextjs\"\n\nexport default function GlobalError({ error }: { error: Error & { digest?: string } }) {\n useEffect(() => {\n Sentry.captureException(error)\n }, [error])\n\n return (\n <html lang=\"en\">\n <body>\n <NextError statusCode={0} />\n </body>\n </html>\n )\n}\n"],"mappings":";;;AAKA,SAAS,iBAAiB;AAC1B,OAAO,eAAe;AACtB,YAAY,YAAY;AAUhB;AARO,SAAR,YAA6B,EAAE,MAAM,GAA2C;AACrF,YAAU,MAAM;AACd,IAAO,wBAAiB,KAAK;AAAA,EAC/B,GAAG,CAAC,KAAK,CAAC;AAEV,SACE,oBAAC,UAAK,MAAK,MACT,8BAAC,UACC,8BAAC,aAAU,YAAY,GAAG,GAC5B,GACF;AAEJ;","names":[]}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export { AUTH_ENV_FIELDS, AUTH_SECRET_FIELDS, AuthKind,
|
|
1
|
+
export { A as AUTH_ENV_FIELDS, b as AUTH_SECRET_FIELDS, c as AuthKind, d as EnvKey, E as EnvRef, e as IntegrationAuth, a as IntegrationDefinition, I as IntegrationMap, P as Protocol, R as RESERVED_KEY_PREFIX, f as defineIntegrations } from '../../types-CAwj03sM.js';
|
|
2
|
+
export { DEFAULT_INTEGRATION_TIMEOUT_MS, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, IntegrationClient, IntegrationConfig, IntegrationError, IntegrationErrorCode, IntegrationHandle, IntegrationProblem, IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, ParamValue, allKeys, assertIntegrations, createIntegrationClient, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys } from '../../integrations/index.js';
|
|
2
3
|
import '../../env-R-bci5RU.js';
|
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
import {
|
|
2
|
-
AUTH_ENV_FIELDS,
|
|
3
|
-
AUTH_SECRET_FIELDS,
|
|
4
2
|
DEFAULT_INTEGRATION_TIMEOUT_MS,
|
|
5
3
|
INTEGRATION_ALIAS_ATTR,
|
|
6
4
|
INTEGRATION_SPAN_TYPE,
|
|
7
5
|
INTEGRATION_SPAN_TYPE_ATTR,
|
|
8
6
|
IntegrationError,
|
|
9
7
|
OAUTH_REFRESH_SKEW_MS,
|
|
8
|
+
createIntegrationClient
|
|
9
|
+
} from "../../chunk-F3NHTHFO.js";
|
|
10
|
+
import {
|
|
11
|
+
AUTH_ENV_FIELDS,
|
|
12
|
+
AUTH_SECRET_FIELDS,
|
|
10
13
|
RESERVED_KEY_PREFIX,
|
|
11
14
|
allKeys,
|
|
12
15
|
assertIntegrations,
|
|
13
|
-
createIntegrationClient,
|
|
14
16
|
defineIntegrations,
|
|
15
17
|
loggingEnabled,
|
|
16
18
|
loggingKey,
|
|
17
19
|
readRef,
|
|
18
20
|
requiredKeys
|
|
19
|
-
} from "../../chunk-
|
|
21
|
+
} from "../../chunk-TOBGX4CZ.js";
|
|
20
22
|
import {
|
|
21
23
|
PLATFORM_MANAGED_HOSTS,
|
|
22
24
|
isPlatformManagedHost
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Routes the platform serves inside every app, under `/api/qore/*`.
|
|
3
|
+
*
|
|
4
|
+
* The app holds one file, `src/app/api/qore/[...path]/route.ts`:
|
|
5
|
+
*
|
|
6
|
+
* export const runtime = "nodejs"
|
|
7
|
+
* export const dynamic = "force-dynamic"
|
|
8
|
+
* export { GET, POST } from "@quatronic/sdk/next/platform"
|
|
9
|
+
*
|
|
10
|
+
* so a new platform route arrives with an SDK release. `runtime` and `dynamic`
|
|
11
|
+
* stay literals in the app: Next reads them off the route module and does not
|
|
12
|
+
* follow them into a package. `/api/healthz` is not here, because the portal's
|
|
13
|
+
* monitor calls it at that path.
|
|
14
|
+
*/
|
|
15
|
+
type Handler = (request: Request) => Promise<Response>;
|
|
16
|
+
declare const GET: Handler;
|
|
17
|
+
declare const POST: Handler;
|
|
18
|
+
|
|
19
|
+
export { GET, POST };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {
|
|
2
|
+
QORE_CSP_REPORT_URI,
|
|
3
|
+
createCspReportRoute
|
|
4
|
+
} from "../../chunk-P7HNHLW7.js";
|
|
5
|
+
import "../../chunk-FUPTRHT7.js";
|
|
6
|
+
import {
|
|
7
|
+
getLogger
|
|
8
|
+
} from "../../chunk-MET4SIMB.js";
|
|
9
|
+
|
|
10
|
+
// src/next/platform/index.ts
|
|
11
|
+
var PREFIX = "/api/qore/";
|
|
12
|
+
var cspReport = createCspReportRoute({
|
|
13
|
+
log: {
|
|
14
|
+
warn: ({ event, ...fields }) => getLogger().warn(
|
|
15
|
+
{
|
|
16
|
+
"qore.audit.event": String(event),
|
|
17
|
+
...Object.fromEntries(
|
|
18
|
+
Object.entries(fields).filter(([, value]) => value !== void 0).map(([key, value]) => [`qore.csp.${key}`, String(value)])
|
|
19
|
+
)
|
|
20
|
+
},
|
|
21
|
+
String(event)
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
var ROUTES = {
|
|
26
|
+
[QORE_CSP_REPORT_URI.slice(PREFIX.length)]: { POST: cspReport }
|
|
27
|
+
};
|
|
28
|
+
function dispatch(method) {
|
|
29
|
+
return async (request) => {
|
|
30
|
+
const path = new URL(request.url).pathname;
|
|
31
|
+
const route = path.startsWith(PREFIX) ? ROUTES[path.slice(PREFIX.length).replace(/\/$/, "")] : void 0;
|
|
32
|
+
if (!route) return new Response(null, { status: 404 });
|
|
33
|
+
const handler = route[method];
|
|
34
|
+
if (!handler) return new Response(null, { status: 405, headers: { allow: Object.keys(route).join(", ") } });
|
|
35
|
+
return handler(request);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
var GET = dispatch("GET");
|
|
39
|
+
var POST = dispatch("POST");
|
|
40
|
+
export {
|
|
41
|
+
GET,
|
|
42
|
+
POST
|
|
43
|
+
};
|
|
44
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/platform/index.ts"],"sourcesContent":["import { getLogger } from \"../../telemetry-hooks\"\nimport { createCspReportRoute, QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\n\n/**\n * Routes the platform serves inside every app, under `/api/qore/*`.\n *\n * The app holds one file, `src/app/api/qore/[...path]/route.ts`:\n *\n * export const runtime = \"nodejs\"\n * export const dynamic = \"force-dynamic\"\n * export { GET, POST } from \"@quatronic/sdk/next/platform\"\n *\n * so a new platform route arrives with an SDK release. `runtime` and `dynamic`\n * stay literals in the app: Next reads them off the route module and does not\n * follow them into a package. `/api/healthz` is not here, because the portal's\n * monitor calls it at that path.\n */\n\ntype Handler = (request: Request) => Promise<Response>\n\nconst PREFIX = \"/api/qore/\"\n\nconst cspReport = createCspReportRoute({\n log: {\n warn: ({ event, ...fields }) =>\n getLogger().warn(\n {\n \"qore.audit.event\": String(event),\n ...Object.fromEntries(\n Object.entries(fields)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [`qore.csp.${key}`, String(value)]),\n ),\n },\n String(event),\n ),\n },\n})\n\nconst ROUTES: Record<string, Partial<Record<\"GET\" | \"POST\", Handler>>> = {\n [QORE_CSP_REPORT_URI.slice(PREFIX.length)]: { POST: cspReport },\n}\n\nfunction dispatch(method: \"GET\" | \"POST\"): Handler {\n return async (request) => {\n const path = new URL(request.url).pathname\n const route = path.startsWith(PREFIX) ? ROUTES[path.slice(PREFIX.length).replace(/\\/$/, \"\")] : undefined\n if (!route) return new Response(null, { status: 404 })\n const handler = route[method]\n if (!handler) return new Response(null, { status: 405, headers: { allow: Object.keys(route).join(\", \") } })\n return handler(request)\n }\n}\n\nexport const GET = dispatch(\"GET\")\nexport const POST = dispatch(\"POST\")\n"],"mappings":";;;;;;;;;;AAoBA,IAAM,SAAS;AAEf,IAAM,YAAY,qBAAqB;AAAA,EACrC,KAAK;AAAA,IACH,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,MACxB,UAAU,EAAE;AAAA,MACV;AAAA,QACE,oBAAoB,OAAO,KAAK;AAAA,QAChC,GAAG,OAAO;AAAA,UACR,OAAO,QAAQ,MAAM,EAClB,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,UAAU,MAAS,EACzC,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,YAAY,GAAG,IAAI,OAAO,KAAK,CAAC,CAAC;AAAA,QAC7D;AAAA,MACF;AAAA,MACA,OAAO,KAAK;AAAA,IACd;AAAA,EACJ;AACF,CAAC;AAED,IAAM,SAAmE;AAAA,EACvE,CAAC,oBAAoB,MAAM,OAAO,MAAM,CAAC,GAAG,EAAE,MAAM,UAAU;AAChE;AAEA,SAAS,SAAS,QAAiC;AACjD,SAAO,OAAO,YAAY;AACxB,UAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAClC,UAAM,QAAQ,KAAK,WAAW,MAAM,IAAI,OAAO,KAAK,MAAM,OAAO,MAAM,EAAE,QAAQ,OAAO,EAAE,CAAC,IAAI;AAC/F,QAAI,CAAC,MAAO,QAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AACrD,UAAM,UAAU,MAAM,MAAM;AAC5B,QAAI,CAAC,QAAS,QAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,SAAS,EAAE,OAAO,OAAO,KAAK,KAAK,EAAE,KAAK,IAAI,EAAE,EAAE,CAAC;AAC1G,WAAO,QAAQ,OAAO;AAAA,EACxB;AACF;AAEO,IAAM,MAAM,SAAS,KAAK;AAC1B,IAAM,OAAO,SAAS,MAAM;","names":[]}
|
|
@@ -96,6 +96,8 @@ interface CspReportRouteOptions {
|
|
|
96
96
|
}
|
|
97
97
|
/** The two field namings, hyphenated (`report-uri`) and camel (`report-to`). */
|
|
98
98
|
declare function readCspReport(report: Record<string, unknown>): CspReportFields;
|
|
99
|
+
/** Where the platform's catch-all route (`@quatronic/sdk/next/platform`) receives CSP reports. */
|
|
100
|
+
declare const QORE_CSP_REPORT_URI = "/api/qore/csp-report";
|
|
99
101
|
/**
|
|
100
102
|
* Build the `POST` handler for `src/app/api/csp-report/route.ts`.
|
|
101
103
|
*
|
|
@@ -105,6 +107,26 @@ declare function readCspReport(report: Record<string, unknown>): CspReportFields
|
|
|
105
107
|
*/
|
|
106
108
|
declare function createCspReportRoute(options: CspReportRouteOptions): (request: Request) => Promise<Response>;
|
|
107
109
|
|
|
110
|
+
type QoreProxyAuth = "keycloak" | "betterauth" | "none";
|
|
111
|
+
interface QoreProxyOptions {
|
|
112
|
+
/** Which session the proxy pre-checks. Real validation stays server-side. */
|
|
113
|
+
auth?: QoreProxyAuth;
|
|
114
|
+
/** Overrides for the security headers and the CSP. */
|
|
115
|
+
security?: SecurityHeaderOptions;
|
|
116
|
+
/**
|
|
117
|
+
* The app's own proxy logic. Runs after the session pre-check passes;
|
|
118
|
+
* return nothing to pass through, or a Response to answer early.
|
|
119
|
+
*/
|
|
120
|
+
handler?: ProxyHandlerFn;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The body of a Next app's `src/proxy.ts`: security headers and a CSP nonce on
|
|
124
|
+
* every response, a cheap session-cookie pre-check that redirects to login,
|
|
125
|
+
* then the app's own handler. Which paths it covers stays the app's `config`
|
|
126
|
+
* literal, since Next reads that statically.
|
|
127
|
+
*/
|
|
128
|
+
declare function qoreProxy(options?: QoreProxyOptions): SecuredProxy;
|
|
129
|
+
|
|
108
130
|
/**
|
|
109
131
|
* What a Next proxy (formerly "middleware") is allowed to be.
|
|
110
132
|
*
|
|
@@ -151,4 +173,4 @@ declare const NONCE_HEADER = "x-qdc-nonce";
|
|
|
151
173
|
*/
|
|
152
174
|
declare function withSecurityHeaders(handler: ProxyHandlerFn, options?: SecurityHeaderOptions): SecuredProxy;
|
|
153
175
|
|
|
154
|
-
export { type CspReportFields, type CspReportLogger, type CspReportRouteOptions, NONCE_HEADER, type ProxyHandlerFn, STATIC_SECURITY_HEADERS, type SecuredProxy, type SecurityHeaderOptions, buildCsp, createCspReportRoute, proxyMatcher, readCspReport, withSecurityHeaders };
|
|
176
|
+
export { type CspReportFields, type CspReportLogger, type CspReportRouteOptions, NONCE_HEADER, type ProxyHandlerFn, QORE_CSP_REPORT_URI, type QoreProxyAuth, type QoreProxyOptions, STATIC_SECURITY_HEADERS, type SecuredProxy, type SecurityHeaderOptions, buildCsp, createCspReportRoute, proxyMatcher, qoreProxy, readCspReport, withSecurityHeaders };
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
QORE_CSP_REPORT_URI,
|
|
3
|
+
createCspReportRoute,
|
|
4
|
+
readCspReport
|
|
5
|
+
} from "../../chunk-P7HNHLW7.js";
|
|
6
|
+
import "../../chunk-FUPTRHT7.js";
|
|
7
7
|
import {
|
|
8
8
|
proxyMatcher
|
|
9
9
|
} from "../../chunk-X6D3TBNS.js";
|
|
10
|
+
import {
|
|
11
|
+
STATIC_SECURITY_HEADERS
|
|
12
|
+
} from "../../chunk-2HE2D4SY.js";
|
|
10
13
|
|
|
11
14
|
// src/next/security/index.ts
|
|
12
|
-
import { NextResponse } from "next/server";
|
|
15
|
+
import { NextResponse as NextResponse2 } from "next/server";
|
|
13
16
|
|
|
14
17
|
// src/security-core/csp.ts
|
|
15
18
|
var HTTP_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
@@ -64,58 +67,36 @@ function cspHeaderName(options = {}) {
|
|
|
64
67
|
return options.reportOnly ?? true ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
|
|
65
68
|
}
|
|
66
69
|
|
|
67
|
-
// src/security
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const nested = asRecord(single["csp-report"]);
|
|
79
|
-
return nested ? [nested] : [single];
|
|
80
|
-
}
|
|
81
|
-
if (Array.isArray(payload)) {
|
|
82
|
-
return payload.map((entry) => asRecord(asRecord(entry)?.["body"])).filter((report) => report !== void 0);
|
|
83
|
-
}
|
|
84
|
-
return [];
|
|
70
|
+
// src/next/security/qoreProxy.ts
|
|
71
|
+
import { NextResponse } from "next/server";
|
|
72
|
+
var KEYCLOAK_SESSION_COOKIE = "qdc_session";
|
|
73
|
+
var BETTERAUTH_SESSION_SUFFIX = "better-auth.session_token";
|
|
74
|
+
function keycloakGate(req) {
|
|
75
|
+
if (req.cookies.has(KEYCLOAK_SESSION_COOKIE)) return void 0;
|
|
76
|
+
const url = req.nextUrl.clone();
|
|
77
|
+
url.pathname = "/api/auth/login";
|
|
78
|
+
url.search = "";
|
|
79
|
+
url.searchParams.set("redirect", req.nextUrl.pathname + req.nextUrl.search);
|
|
80
|
+
return NextResponse.redirect(url);
|
|
85
81
|
}
|
|
86
|
-
function
|
|
87
|
-
return
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
disposition: asString(report["disposition"])
|
|
92
|
-
};
|
|
82
|
+
function betterAuthGate(req) {
|
|
83
|
+
if (req.cookies.getAll().some((c) => c.name.endsWith(BETTERAUTH_SESSION_SUFFIX))) return void 0;
|
|
84
|
+
const url = req.nextUrl.clone();
|
|
85
|
+
url.pathname = "/login";
|
|
86
|
+
return NextResponse.redirect(url);
|
|
93
87
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return noContent();
|
|
107
|
-
}
|
|
108
|
-
let payload;
|
|
109
|
-
try {
|
|
110
|
-
payload = parseJsonBounded(body, { maxBytes, maxDepth: 8 });
|
|
111
|
-
} catch {
|
|
112
|
-
return noContent();
|
|
113
|
-
}
|
|
114
|
-
for (const report of collectReports(payload)) {
|
|
115
|
-
log.warn({ event: "csp.violation", ...readCspReport(report) });
|
|
116
|
-
}
|
|
117
|
-
return noContent();
|
|
118
|
-
};
|
|
88
|
+
var GATES = {
|
|
89
|
+
keycloak: keycloakGate,
|
|
90
|
+
betterauth: betterAuthGate,
|
|
91
|
+
none: null
|
|
92
|
+
};
|
|
93
|
+
function qoreProxy(options = {}) {
|
|
94
|
+
const gate = GATES[options.auth ?? "none"];
|
|
95
|
+
const handler = options.handler;
|
|
96
|
+
return withSecurityHeaders(
|
|
97
|
+
async (req, event) => gate?.(req) ?? (handler ? handler(req, event) : void 0),
|
|
98
|
+
{ reportUri: QORE_CSP_REPORT_URI, ...options.security }
|
|
99
|
+
);
|
|
119
100
|
}
|
|
120
101
|
|
|
121
102
|
// src/next/security/index.ts
|
|
@@ -158,9 +139,9 @@ function withSecurityHeaders(handler, options = {}) {
|
|
|
158
139
|
const handled = await handler(request, event);
|
|
159
140
|
let response;
|
|
160
141
|
if (!handled) {
|
|
161
|
-
response =
|
|
142
|
+
response = NextResponse2.next({ request: { headers: requestHeaders } });
|
|
162
143
|
} else if (isPassThrough(handled)) {
|
|
163
|
-
response =
|
|
144
|
+
response = NextResponse2.next({ request: { headers: requestHeaders } });
|
|
164
145
|
carryOver(handled, response);
|
|
165
146
|
} else {
|
|
166
147
|
response = handled;
|
|
@@ -171,10 +152,12 @@ function withSecurityHeaders(handler, options = {}) {
|
|
|
171
152
|
}
|
|
172
153
|
export {
|
|
173
154
|
NONCE_HEADER,
|
|
155
|
+
QORE_CSP_REPORT_URI,
|
|
174
156
|
STATIC_SECURITY_HEADERS,
|
|
175
157
|
buildCsp,
|
|
176
158
|
createCspReportRoute,
|
|
177
159
|
proxyMatcher,
|
|
160
|
+
qoreProxy,
|
|
178
161
|
readCspReport,
|
|
179
162
|
withSecurityHeaders
|
|
180
163
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/next/security/index.ts","../../../src/security-core/csp.ts","../../../src/security-core/cspReport.ts"],"sourcesContent":["import { NextResponse } from \"next/server\"\nimport type { NextFetchEvent, NextRequest } from \"next/server\"\n\nimport { buildCsp, cspHeaderName, type SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\n\nexport { buildCsp } from \"../../security-core/csp\"\nexport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nexport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\nexport { proxyMatcher } from \"../../security-core/proxy\"\nexport { createCspReportRoute, readCspReport } from \"../../security-core/cspReport\"\nexport type {\n CspReportFields,\n CspReportLogger,\n CspReportRouteOptions,\n} from \"../../security-core/cspReport\"\n\n/**\n * What a Next proxy (formerly \"middleware\") is allowed to be.\n *\n * Named `ProxyHandlerFn` rather than `ProxyHandler` because `ProxyHandler<T>`\n * is a TypeScript lib global — exporting that name would shadow it in every\n * file that imports from this entry point.\n *\n * Returning nothing means \"pass through\", and that is the shape to prefer: it\n * lets `withSecurityHeaders` build the pass-through response itself, which is\n * the only way the nonce reaches the renderer (see below).\n */\nexport type ProxyHandlerFn = (\n request: NextRequest,\n event: NextFetchEvent,\n) => Response | undefined | null | Promise<Response | undefined | null>\n\n/**\n * What `withSecurityHeaders` returns: the full Next proxy signature, rather\n * than the handler's own. The wrapper genuinely accepts both arguments and\n * genuinely always resolves to a `Response` — a handler that returns nothing\n * still comes back as a pass-through. Next accepts this shape as a `proxy`\n * export unchanged.\n *\n * Named because `@quatronic/sdk/next/security/testing` takes one.\n */\nexport type SecuredProxy = (request: NextRequest, event: NextFetchEvent) => Promise<Response>\n\n/** 128 bits, the CSP spec's floor. */\nconst NONCE_BYTES = 16\n\n/** The header app code reads to nonce its own inline script or style. */\nexport const NONCE_HEADER = \"x-qdc-nonce\"\n\nfunction generateNonce(): string {\n // `crypto.getRandomValues`, not `randomUUID()`: a UUID is 122 bits of\n // randomness wearing a fixed-format costume, and `randomUUID` is absent from\n // some edge runtimes. Web Crypto is present in both edge and node.\n const bytes = new Uint8Array(NONCE_BYTES)\n crypto.getRandomValues(bytes)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nfunction isPassThrough(response: Response): boolean {\n // How `NextResponse.next()` marks itself. Reading it is a dependency on a\n // Next internal, so it is the *fallback* path only — a handler that returns\n // nothing never reaches here. If Next ever renames the marker the cost is a\n // response that carries the headers but not the request-side nonce, which is\n // exactly what we would have had without this branch.\n return response.headers.get(\"x-middleware-next\") === \"1\"\n}\n\nfunction carryOver(from: Response, to: Response): void {\n from.headers.forEach((value, key) => {\n // `x-middleware-*` is Next's own pass-through plumbing, including the\n // encoding of the forwarded request headers. The fresh response regenerates\n // all of it; copying the stale copy over would undo the nonce we just set.\n if (key.toLowerCase().startsWith(\"x-middleware-\")) return\n if (key.toLowerCase() === \"set-cookie\") return\n to.headers.set(key, value)\n })\n // `forEach` folds multiple Set-Cookie headers into one comma-joined string,\n // which no browser parses back into two cookies. `getSetCookie` is the only\n // accessor that keeps them separate.\n for (const cookie of from.headers.getSetCookie?.() ?? []) {\n to.headers.append(\"set-cookie\", cookie)\n }\n}\n\nfunction applySecurityHeaders(response: Response, cspName: string, csp: string): void {\n for (const [name, value] of STATIC_SECURITY_HEADERS) {\n response.headers.set(name, value)\n }\n response.headers.set(cspName, csp)\n}\n\n/**\n * Wrap a Next proxy so every response it produces carries the QDC security\n * headers and a per-response CSP nonce.\n *\n * The nonce goes on the **request** headers under two names: `x-qdc-nonce` for\n * app code, and `Content-Security-Policy` because that is where Next itself\n * looks for it. Next parses the request's CSP header, extracts `nonce-…`, and\n * stamps that nonce onto the bootstrap `<script>` tags it emits. Without it,\n * every generated app breaks the moment `script-src` stops allowing\n * `'unsafe-inline'`.\n *\n * A nonce is per response. Any route whose HTML carries one must render\n * dynamically and must not be cached by a CDN, or every visitor shares a single\n * nonce and the nonce protects nothing.\n *\n * The return type is the full proxy signature rather than the handler's own,\n * because the wrapper genuinely does accept both arguments and genuinely always\n * resolves to a `Response` — a handler that returns nothing still comes back as\n * a pass-through. Next accepts this shape as a `proxy` export unchanged.\n */\nexport function withSecurityHeaders(\n handler: ProxyHandlerFn,\n options: SecurityHeaderOptions = {},\n): SecuredProxy {\n return async (request: NextRequest, event: NextFetchEvent): Promise<Response> => {\n const nonce = generateNonce()\n const csp = buildCsp(nonce, { ...options, sentryDsn: options.sentryDsn ?? process.env.SENTRY_DSN })\n const cspName = cspHeaderName(options)\n\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(NONCE_HEADER, nonce)\n // Always the enforcing name on the request, even in report-only mode: this\n // copy is how Next finds the nonce, not a policy the browser ever sees.\n requestHeaders.set(\"content-security-policy\", csp)\n\n const handled = await handler(request, event)\n\n let response: Response\n if (!handled) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n } else if (isPassThrough(handled)) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n carryOver(handled, response)\n } else {\n // A redirect or an early 401. It never reaches a Next route, so the\n // build-time `headers()` set in `withQdcConfig` would miss it — which is\n // precisely why the headers are applied here too.\n response = handled\n }\n\n applySecurityHeaders(response, cspName, csp)\n return response\n }\n}\n","// Content-Security-Policy assembly. Pure string work, no `next` and no Node\n// built-ins, so the edge proxy can call it.\n\n/** Options for the security headers a QDC app sends on every response. */\nexport interface SecurityHeaderOptions {\n /**\n * Who may frame this app. Defaults to `[\"'none'\"]` — nobody. Values are\n * CSP source expressions, so quoted keywords keep their quotes.\n */\n frameAncestors?: string[]\n /**\n * What this app may frame, on top of `'self'`. Defaults to `[\"'self'\"]`.\n *\n * Without an explicit `frame-src` the directive falls through to\n * `default-src 'self'`, so an app could embed nothing at all — no payment\n * iframe, no map, no video. That was a gap rather than a decision, so the\n * directive is written out and an app widens it here.\n *\n * This is the opposite direction from `frameAncestors`: that one says who may\n * embed us, this one says what we may embed.\n */\n frameSrc?: string[]\n /**\n * Extra origins the browser may open connections to, on top of `'self'`.\n * In a generated app these are the origins behind its `CONN_*` secrets.\n */\n connectSrc?: string[]\n /** Where the browser posts violation reports. Defaults to `/api/csp-report`. */\n reportUri?: string\n /**\n * Send `Content-Security-Policy-Report-Only` instead of the enforcing\n * header. **Defaults to `true`.**\n *\n * `'strict-dynamic'` makes the browser ignore `'self'` and every host\n * allow-list for scripts, so a policy that is slightly wrong is a blank page\n * in production rather than a degraded one. Enforcing before the reports have\n * been read gets the whole policy reverted instead of tightened, so Stage 1\n * collects evidence at `/api/csp-report` first. Pass `false` once those\n * reports are clean for your app.\n */\n reportOnly?: boolean\n /** DSN whose ingest origin the browser may post to. */\n sentryDsn?: string\n}\n\n// Only http(s) has a meaningful `origin` — a DSN with some other scheme (or\n// no scheme at all) gives `URL.origin === \"null\"`, which would otherwise\n// become a literal \"null\" token in connect-src.\nconst HTTP_PROTOCOLS = new Set([\"http:\", \"https:\"])\n\n/** The origin a browser-side Sentry SDK for this DSN posts events to, or `undefined` for an absent/malformed DSN. */\nexport function sentryIngestOrigin(dsn: string | undefined): string | undefined {\n if (!dsn) return undefined\n try {\n const url = new URL(dsn)\n return HTTP_PROTOCOLS.has(url.protocol) ? url.origin : undefined\n } catch {\n return undefined\n }\n}\n\n// A source expression containing \";\" or a newline would end the directive and\n// start a new one — i.e. let caller-supplied config rewrite the whole policy.\n// Reject rather than strip: a silently mangled origin is a connect-src that\n// quietly fails at runtime.\nconst UNSAFE_IN_DIRECTIVE = /[;\\r\\n]/\n\nfunction assertSafe(kind: string, values: readonly string[]): void {\n for (const value of values) {\n if (UNSAFE_IN_DIRECTIVE.test(value)) {\n throw new Error(`Invalid ${kind} for CSP: ${JSON.stringify(value)} contains \";\" or a newline`)\n }\n }\n}\n\n/**\n * Build the Stage-1 QDC policy for one response.\n *\n * `script-src` carries the per-response nonce plus `'strict-dynamic'`, so a\n * script the app itself marked may load further scripts and nothing else runs.\n * `style-src` deliberately keeps `'unsafe-inline'`: HeroUI and Tailwind emit\n * inline styles, and removing it in the same change that introduces the policy\n * would break every generated app — Stage 2 replaces it with the nonce after\n * its own styling audit.\n */\nexport function buildCsp(nonce: string, options: SecurityHeaderOptions = {}): string {\n const frameAncestors = options.frameAncestors ?? [\"'none'\"]\n const frameSrc = options.frameSrc ?? [\"'self'\"]\n const connectSrc = options.connectSrc ?? []\n const reportUri = options.reportUri ?? \"/api/csp-report\"\n const sentryOrigin = sentryIngestOrigin(options.sentryDsn)\n\n assertSafe(\"nonce\", [nonce])\n assertSafe(\"frameAncestors entry\", frameAncestors)\n assertSafe(\"frameSrc entry\", frameSrc)\n assertSafe(\"connectSrc entry\", connectSrc)\n assertSafe(\"reportUri\", [reportUri])\n if (sentryOrigin) assertSafe(\"sentryDsn origin\", [sentryOrigin])\n\n const directives = [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob: https:\",\n \"font-src 'self' data:\",\n \"worker-src 'self' blob:\",\n [\"connect-src\", \"'self'\", ...connectSrc, ...(sentryOrigin ? [sentryOrigin] : [])].join(\" \"),\n ...(frameSrc.length > 0 ? [[\"frame-src\", ...frameSrc].join(\" \")] : [\"frame-src 'none'\"]),\n ...(frameAncestors.length > 0 ? [[\"frame-ancestors\", ...frameAncestors].join(\" \")] : []),\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n \"upgrade-insecure-requests\",\n ...(reportUri ? [`report-uri ${reportUri}`] : []),\n ]\n\n return directives.join(\"; \") + \";\"\n}\n\n/** The header name matching `options.reportOnly`. */\nexport function cspHeaderName(options: SecurityHeaderOptions = {}): string {\n return (options.reportOnly ?? true)\n ? \"Content-Security-Policy-Report-Only\"\n : \"Content-Security-Policy\"\n}\n","import { parseJsonBounded } from \"./parse\"\n\n/**\n * The `report-uri` endpoint for the QDC Content-Security-Policy.\n *\n * The policy ships report-only for its first release, so this endpoint is the\n * evidence: it records what the policy *would* have blocked, so the policy can\n * be corrected before it enforces. It collects and nothing else — one log line\n * per report, forwarded nowhere.\n *\n * It is unauthenticated by necessity: a browser posts a report with no session\n * and no CSRF token. So it reads a small bounded body and logs a fixed set of\n * fields rather than whatever the report happens to contain, and it answers 204\n * whatever happens — an error status only teaches a caller that the endpoint is\n * worth probing.\n */\n\n/** A report is a few hundred bytes. Anything near this is not a browser. */\nconst DEFAULT_MAX_BYTES = 16 * 1024\n\n/** Just enough of a logger. `@/lib/log` in a generated app satisfies it. */\nexport interface CspReportLogger {\n warn(fields: Record<string, unknown>): void\n}\n\n/** The fields read off a violation report, whichever wire format it arrived in. */\nexport interface CspReportFields {\n documentUri?: string\n blockedUri?: string\n effectiveDirective?: string\n disposition?: string\n}\n\nexport interface CspReportRouteOptions {\n /** Where the violations go. One `warn` per report, `event: \"csp.violation\"`. */\n log: CspReportLogger\n /** Request bodies above this are dropped unread. Default: 16 KiB. */\n maxBytes?: number\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value.slice(0, 500) : undefined\n}\n\n/** Both wire formats: `report-uri`'s `{\"csp-report\": {…}}` and `report-to`'s array. */\nfunction collectReports(payload: unknown): Record<string, unknown>[] {\n const single = asRecord(payload)\n if (single) {\n const nested = asRecord(single[\"csp-report\"])\n return nested ? [nested] : [single]\n }\n if (Array.isArray(payload)) {\n return payload\n .map((entry) => asRecord(asRecord(entry)?.[\"body\"]))\n .filter((report): report is Record<string, unknown> => report !== undefined)\n }\n return []\n}\n\n/** The two field namings, hyphenated (`report-uri`) and camel (`report-to`). */\nexport function readCspReport(report: Record<string, unknown>): CspReportFields {\n return {\n documentUri: asString(report[\"document-uri\"] ?? report[\"documentURL\"]),\n blockedUri: asString(report[\"blocked-uri\"] ?? report[\"blockedURL\"]),\n effectiveDirective: asString(report[\"effective-directive\"] ?? report[\"effectiveDirective\"]),\n disposition: asString(report[\"disposition\"]),\n }\n}\n\n/**\n * Build the `POST` handler for `src/app/api/csp-report/route.ts`.\n *\n * The route file still declares `runtime` and `dynamic` itself: Next reads\n * those two exports statically, off the route module, and does not follow them\n * through a package boundary.\n */\nexport function createCspReportRoute(\n options: CspReportRouteOptions,\n): (request: Request) => Promise<Response> {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES\n const log = options.log\n\n return async function POST(request: Request): Promise<Response> {\n const noContent = () => new Response(null, { status: 204 })\n\n let body: string\n try {\n body = await request.text()\n } catch {\n return noContent()\n }\n if (body.length === 0 || body.length > maxBytes) {\n return noContent()\n }\n\n let payload: unknown\n try {\n payload = parseJsonBounded(body, { maxBytes, maxDepth: 8 })\n } catch {\n return noContent()\n }\n\n for (const report of collectReports(payload)) {\n log.warn({ event: \"csp.violation\", ...readCspReport(report) })\n }\n return noContent()\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,oBAAoB;;;ACgD7B,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AAG3C,SAAS,mBAAmB,KAA6C;AAC9E,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,GAAG;AACvB,WAAO,eAAe,IAAI,IAAI,QAAQ,IAAI,IAAI,SAAS;AAAA,EACzD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM,sBAAsB;AAE5B,SAAS,WAAW,MAAc,QAAiC;AACjE,aAAW,SAAS,QAAQ;AAC1B,QAAI,oBAAoB,KAAK,KAAK,GAAG;AACnC,YAAM,IAAI,MAAM,WAAW,IAAI,aAAa,KAAK,UAAU,KAAK,CAAC,4BAA4B;AAAA,IAC/F;AAAA,EACF;AACF;AAYO,SAAS,SAAS,OAAe,UAAiC,CAAC,GAAW;AACnF,QAAM,iBAAiB,QAAQ,kBAAkB,CAAC,QAAQ;AAC1D,QAAM,WAAW,QAAQ,YAAY,CAAC,QAAQ;AAC9C,QAAM,aAAa,QAAQ,cAAc,CAAC;AAC1C,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,eAAe,mBAAmB,QAAQ,SAAS;AAEzD,aAAW,SAAS,CAAC,KAAK,CAAC;AAC3B,aAAW,wBAAwB,cAAc;AACjD,aAAW,kBAAkB,QAAQ;AACrC,aAAW,oBAAoB,UAAU;AACzC,aAAW,aAAa,CAAC,SAAS,CAAC;AACnC,MAAI,aAAc,YAAW,oBAAoB,CAAC,YAAY,CAAC;AAE/D,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,4BAA4B,KAAK;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,CAAC,eAAe,UAAU,GAAG,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],"sourcesContent":["import { NextResponse } from \"next/server\"\nimport type { NextFetchEvent, NextRequest } from \"next/server\"\n\nimport { buildCsp, cspHeaderName, type SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\n\nexport { buildCsp } from \"../../security-core/csp\"\nexport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nexport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\nexport { proxyMatcher } from \"../../security-core/proxy\"\nexport { createCspReportRoute, readCspReport, QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nexport { qoreProxy } from \"./qoreProxy\"\nexport type { QoreProxyAuth, QoreProxyOptions } from \"./qoreProxy\"\nexport type {\n CspReportFields,\n CspReportLogger,\n CspReportRouteOptions,\n} from \"../../security-core/cspReport\"\n\n/**\n * What a Next proxy (formerly \"middleware\") is allowed to be.\n *\n * Named `ProxyHandlerFn` rather than `ProxyHandler` because `ProxyHandler<T>`\n * is a TypeScript lib global — exporting that name would shadow it in every\n * file that imports from this entry point.\n *\n * Returning nothing means \"pass through\", and that is the shape to prefer: it\n * lets `withSecurityHeaders` build the pass-through response itself, which is\n * the only way the nonce reaches the renderer (see below).\n */\nexport type ProxyHandlerFn = (\n request: NextRequest,\n event: NextFetchEvent,\n) => Response | undefined | null | Promise<Response | undefined | null>\n\n/**\n * What `withSecurityHeaders` returns: the full Next proxy signature, rather\n * than the handler's own. The wrapper genuinely accepts both arguments and\n * genuinely always resolves to a `Response` — a handler that returns nothing\n * still comes back as a pass-through. Next accepts this shape as a `proxy`\n * export unchanged.\n *\n * Named because `@quatronic/sdk/next/security/testing` takes one.\n */\nexport type SecuredProxy = (request: NextRequest, event: NextFetchEvent) => Promise<Response>\n\n/** 128 bits, the CSP spec's floor. */\nconst NONCE_BYTES = 16\n\n/** The header app code reads to nonce its own inline script or style. */\nexport const NONCE_HEADER = \"x-qdc-nonce\"\n\nfunction generateNonce(): string {\n // `crypto.getRandomValues`, not `randomUUID()`: a UUID is 122 bits of\n // randomness wearing a fixed-format costume, and `randomUUID` is absent from\n // some edge runtimes. Web Crypto is present in both edge and node.\n const bytes = new Uint8Array(NONCE_BYTES)\n crypto.getRandomValues(bytes)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nfunction isPassThrough(response: Response): boolean {\n // How `NextResponse.next()` marks itself. Reading it is a dependency on a\n // Next internal, so it is the *fallback* path only — a handler that returns\n // nothing never reaches here. If Next ever renames the marker the cost is a\n // response that carries the headers but not the request-side nonce, which is\n // exactly what we would have had without this branch.\n return response.headers.get(\"x-middleware-next\") === \"1\"\n}\n\nfunction carryOver(from: Response, to: Response): void {\n from.headers.forEach((value, key) => {\n // `x-middleware-*` is Next's own pass-through plumbing, including the\n // encoding of the forwarded request headers. The fresh response regenerates\n // all of it; copying the stale copy over would undo the nonce we just set.\n if (key.toLowerCase().startsWith(\"x-middleware-\")) return\n if (key.toLowerCase() === \"set-cookie\") return\n to.headers.set(key, value)\n })\n // `forEach` folds multiple Set-Cookie headers into one comma-joined string,\n // which no browser parses back into two cookies. `getSetCookie` is the only\n // accessor that keeps them separate.\n for (const cookie of from.headers.getSetCookie?.() ?? []) {\n to.headers.append(\"set-cookie\", cookie)\n }\n}\n\nfunction applySecurityHeaders(response: Response, cspName: string, csp: string): void {\n for (const [name, value] of STATIC_SECURITY_HEADERS) {\n response.headers.set(name, value)\n }\n response.headers.set(cspName, csp)\n}\n\n/**\n * Wrap a Next proxy so every response it produces carries the QDC security\n * headers and a per-response CSP nonce.\n *\n * The nonce goes on the **request** headers under two names: `x-qdc-nonce` for\n * app code, and `Content-Security-Policy` because that is where Next itself\n * looks for it. Next parses the request's CSP header, extracts `nonce-…`, and\n * stamps that nonce onto the bootstrap `<script>` tags it emits. Without it,\n * every generated app breaks the moment `script-src` stops allowing\n * `'unsafe-inline'`.\n *\n * A nonce is per response. Any route whose HTML carries one must render\n * dynamically and must not be cached by a CDN, or every visitor shares a single\n * nonce and the nonce protects nothing.\n *\n * The return type is the full proxy signature rather than the handler's own,\n * because the wrapper genuinely does accept both arguments and genuinely always\n * resolves to a `Response` — a handler that returns nothing still comes back as\n * a pass-through. Next accepts this shape as a `proxy` export unchanged.\n */\nexport function withSecurityHeaders(\n handler: ProxyHandlerFn,\n options: SecurityHeaderOptions = {},\n): SecuredProxy {\n return async (request: NextRequest, event: NextFetchEvent): Promise<Response> => {\n const nonce = generateNonce()\n const csp = buildCsp(nonce, { ...options, sentryDsn: options.sentryDsn ?? process.env.SENTRY_DSN })\n const cspName = cspHeaderName(options)\n\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(NONCE_HEADER, nonce)\n // Always the enforcing name on the request, even in report-only mode: this\n // copy is how Next finds the nonce, not a policy the browser ever sees.\n requestHeaders.set(\"content-security-policy\", csp)\n\n const handled = await handler(request, event)\n\n let response: Response\n if (!handled) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n } else if (isPassThrough(handled)) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n carryOver(handled, response)\n } else {\n // A redirect or an early 401. It never reaches a Next route, so the\n // build-time `headers()` set in `withQdcConfig` would miss it — which is\n // precisely why the headers are applied here too.\n response = handled\n }\n\n applySecurityHeaders(response, cspName, csp)\n return response\n }\n}\n","// Content-Security-Policy assembly. Pure string work, no `next` and no Node\n// built-ins, so the edge proxy can call it.\n\n/** Options for the security headers a QDC app sends on every response. */\nexport interface SecurityHeaderOptions {\n /**\n * Who may frame this app. Defaults to `[\"'none'\"]` — nobody. Values are\n * CSP source expressions, so quoted keywords keep their quotes.\n */\n frameAncestors?: string[]\n /**\n * What this app may frame, on top of `'self'`. Defaults to `[\"'self'\"]`.\n *\n * Without an explicit `frame-src` the directive falls through to\n * `default-src 'self'`, so an app could embed nothing at all — no payment\n * iframe, no map, no video. That was a gap rather than a decision, so the\n * directive is written out and an app widens it here.\n *\n * This is the opposite direction from `frameAncestors`: that one says who may\n * embed us, this one says what we may embed.\n */\n frameSrc?: string[]\n /**\n * Extra origins the browser may open connections to, on top of `'self'`.\n * In a generated app these are the origins behind its `CONN_*` secrets.\n */\n connectSrc?: string[]\n /** Where the browser posts violation reports. Defaults to `/api/csp-report`. */\n reportUri?: string\n /**\n * Send `Content-Security-Policy-Report-Only` instead of the enforcing\n * header. **Defaults to `true`.**\n *\n * `'strict-dynamic'` makes the browser ignore `'self'` and every host\n * allow-list for scripts, so a policy that is slightly wrong is a blank page\n * in production rather than a degraded one. Enforcing before the reports have\n * been read gets the whole policy reverted instead of tightened, so Stage 1\n * collects evidence at `/api/csp-report` first. Pass `false` once those\n * reports are clean for your app.\n */\n reportOnly?: boolean\n /** DSN whose ingest origin the browser may post to. */\n sentryDsn?: string\n}\n\n// Only http(s) has a meaningful `origin` — a DSN with some other scheme (or\n// no scheme at all) gives `URL.origin === \"null\"`, which would otherwise\n// become a literal \"null\" token in connect-src.\nconst HTTP_PROTOCOLS = new Set([\"http:\", \"https:\"])\n\n/** The origin a browser-side Sentry SDK for this DSN posts events to, or `undefined` for an absent/malformed DSN. */\nexport function sentryIngestOrigin(dsn: string | undefined): string | undefined {\n if (!dsn) return undefined\n try {\n const url = new URL(dsn)\n return HTTP_PROTOCOLS.has(url.protocol) ? url.origin : undefined\n } catch {\n return undefined\n }\n}\n\n// A source expression containing \";\" or a newline would end the directive and\n// start a new one — i.e. let caller-supplied config rewrite the whole policy.\n// Reject rather than strip: a silently mangled origin is a connect-src that\n// quietly fails at runtime.\nconst UNSAFE_IN_DIRECTIVE = /[;\\r\\n]/\n\nfunction assertSafe(kind: string, values: readonly string[]): void {\n for (const value of values) {\n if (UNSAFE_IN_DIRECTIVE.test(value)) {\n throw new Error(`Invalid ${kind} for CSP: ${JSON.stringify(value)} contains \";\" or a newline`)\n }\n }\n}\n\n/**\n * Build the Stage-1 QDC policy for one response.\n *\n * `script-src` carries the per-response nonce plus `'strict-dynamic'`, so a\n * script the app itself marked may load further scripts and nothing else runs.\n * `style-src` deliberately keeps `'unsafe-inline'`: HeroUI and Tailwind emit\n * inline styles, and removing it in the same change that introduces the policy\n * would break every generated app — Stage 2 replaces it with the nonce after\n * its own styling audit.\n */\nexport function buildCsp(nonce: string, options: SecurityHeaderOptions = {}): string {\n const frameAncestors = options.frameAncestors ?? [\"'none'\"]\n const frameSrc = options.frameSrc ?? [\"'self'\"]\n const connectSrc = options.connectSrc ?? []\n const reportUri = options.reportUri ?? \"/api/csp-report\"\n const sentryOrigin = sentryIngestOrigin(options.sentryDsn)\n\n assertSafe(\"nonce\", [nonce])\n assertSafe(\"frameAncestors entry\", frameAncestors)\n assertSafe(\"frameSrc entry\", frameSrc)\n assertSafe(\"connectSrc entry\", connectSrc)\n assertSafe(\"reportUri\", [reportUri])\n if (sentryOrigin) assertSafe(\"sentryDsn origin\", [sentryOrigin])\n\n const directives = [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob: https:\",\n \"font-src 'self' data:\",\n \"worker-src 'self' blob:\",\n [\"connect-src\", \"'self'\", ...connectSrc, ...(sentryOrigin ? [sentryOrigin] : [])].join(\" \"),\n ...(frameSrc.length > 0 ? [[\"frame-src\", ...frameSrc].join(\" \")] : [\"frame-src 'none'\"]),\n ...(frameAncestors.length > 0 ? [[\"frame-ancestors\", ...frameAncestors].join(\" \")] : []),\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n \"upgrade-insecure-requests\",\n ...(reportUri ? [`report-uri ${reportUri}`] : []),\n ]\n\n return directives.join(\"; \") + \";\"\n}\n\n/** The header name matching `options.reportOnly`. */\nexport function cspHeaderName(options: SecurityHeaderOptions = {}): string {\n return (options.reportOnly ?? true)\n ? \"Content-Security-Policy-Report-Only\"\n : \"Content-Security-Policy\"\n}\n","import { NextResponse } from \"next/server\"\nimport type { NextRequest } from \"next/server\"\n\nimport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nimport { withSecurityHeaders, type ProxyHandlerFn, type SecuredProxy } from \"./index\"\n\nexport type QoreProxyAuth = \"keycloak\" | \"betterauth\" | \"none\"\n\nexport interface QoreProxyOptions {\n /** Which session the proxy pre-checks. Real validation stays server-side. */\n auth?: QoreProxyAuth\n /** Overrides for the security headers and the CSP. */\n security?: SecurityHeaderOptions\n /**\n * The app's own proxy logic. Runs after the session pre-check passes;\n * return nothing to pass through, or a Response to answer early.\n */\n handler?: ProxyHandlerFn\n}\n\n\n// Kept equal to auth-core's COOKIE_NAME by a test; imported from there it would\n// pull the session module into every proxy bundle.\nconst KEYCLOAK_SESSION_COOKIE = \"qdc_session\"\nconst BETTERAUTH_SESSION_SUFFIX = \"better-auth.session_token\"\n\nfunction keycloakGate(req: NextRequest): Response | undefined {\n if (req.cookies.has(KEYCLOAK_SESSION_COOKIE)) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/api/auth/login\"\n url.search = \"\"\n url.searchParams.set(\"redirect\", req.nextUrl.pathname + req.nextUrl.search)\n return NextResponse.redirect(url)\n}\n\nfunction betterAuthGate(req: NextRequest): Response | undefined {\n if (req.cookies.getAll().some((c) => c.name.endsWith(BETTERAUTH_SESSION_SUFFIX))) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/login\"\n return NextResponse.redirect(url)\n}\n\nconst GATES: Record<QoreProxyAuth, ((req: NextRequest) => Response | undefined) | null> = {\n keycloak: keycloakGate,\n betterauth: betterAuthGate,\n none: null,\n}\n\n/**\n * The body of a Next app's `src/proxy.ts`: security headers and a CSP nonce on\n * every response, a cheap session-cookie pre-check that redirects to login,\n * then the app's own handler. Which paths it covers stays the app's `config`\n * literal, since Next reads that statically.\n */\nexport function qoreProxy(options: QoreProxyOptions = {}): SecuredProxy {\n const gate = GATES[options.auth ?? \"none\"]\n const handler = options.handler\n return withSecurityHeaders(\n async (req, event) => gate?.(req) ?? (handler ? handler(req, event) : undefined),\n { reportUri: QORE_C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BAAe,IAAI,2BAA2B,GAAG;AAEjD,UAAM,UAAU,MAAM,QAAQ,SAAS,KAAK;AAE5C,QAAI;AACJ,QAAI,CAAC,SAAS;AACZ,iBAAWC,cAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAAA,IACvE,WAAW,cAAc,OAAO,GAAG;AACjC,iBAAWA,cAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AACrE,gBAAU,SAAS,QAAQ;AAAA,IAC7B,OAAO;AAIL,iBAAW;AAAA,IACb;AAEA,yBAAqB,UAAU,SAAS,GAAG;AAC3C,WAAO;AAAA,EACT;AACF;","names":["NextResponse","NextResponse"]}
|
|
@@ -3,9 +3,9 @@ import {
|
|
|
3
3
|
} from "../../chunk-DYOSRJH3.js";
|
|
4
4
|
import {
|
|
5
5
|
initSentry
|
|
6
|
-
} from "../../chunk-
|
|
6
|
+
} from "../../chunk-G7VPNC6M.js";
|
|
7
|
+
import "../../chunk-MET4SIMB.js";
|
|
7
8
|
import "../../chunk-7ASQHY7O.js";
|
|
8
|
-
import "../../chunk-EK6TGWWT.js";
|
|
9
9
|
|
|
10
10
|
// src/next/sentry/client.ts
|
|
11
11
|
import * as Sentry from "@sentry/nextjs";
|
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import "../../chunk-
|
|
8
|
-
|
|
9
|
-
// src/next/sentry/register.ts
|
|
10
|
-
import * as Sentry from "@sentry/nextjs";
|
|
11
|
-
async function register() {
|
|
12
|
-
const runtime = process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
13
|
-
initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }));
|
|
14
|
-
}
|
|
15
|
-
var onRequestError = Sentry.captureRequestError;
|
|
2
|
+
onRequestError,
|
|
3
|
+
register
|
|
4
|
+
} from "../../chunk-WU7N4PET.js";
|
|
5
|
+
import "../../chunk-G7VPNC6M.js";
|
|
6
|
+
import "../../chunk-MET4SIMB.js";
|
|
7
|
+
import "../../chunk-7ASQHY7O.js";
|
|
16
8
|
export {
|
|
17
9
|
onRequestError,
|
|
18
10
|
register
|