@quatronic/sdk 0.7.1-test.9412cbd → 0.7.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/dist/{chunk-NMJOF3ZM.js → chunk-2AYDFLKR.js} +104 -6
- package/dist/chunk-2AYDFLKR.js.map +1 -0
- package/dist/cli/legacy/qdc-sourcemaps.js +6 -16
- package/dist/cli/skills-postinstall.js +3 -4
- package/dist/cli/skills.js +3 -4
- package/dist/cli/sourcemaps.js +6 -16
- package/dist/integrations/index.d.ts +75 -3
- package/dist/integrations/index.js +4 -6
- package/dist/next/auth/index.js +152 -3
- package/dist/next/auth/index.js.map +1 -1
- package/dist/next/db/index.d.ts +1 -18
- package/dist/next/db/index.js +0 -25
- package/dist/next/db/index.js.map +1 -1
- package/dist/next/integrations/index.d.ts +1 -2
- package/dist/next/integrations/index.js +4 -6
- package/dist/next/security/index.d.ts +1 -23
- package/dist/next/security/index.js +56 -39
- package/dist/next/security/index.js.map +1 -1
- package/dist/next/security/testing.js +1 -10
- package/dist/next/security/testing.js.map +1 -1
- package/dist/next/sentry/register.js +13 -5
- package/dist/next/sentry/register.js.map +1 -1
- package/dist/node/integrations/index.d.ts +1 -2
- package/dist/node/integrations/index.js +4 -6
- package/migrations/no-raw-fetch/meta.json +1 -1
- package/package.json +4 -26
- package/skills/catalog.json +0 -1
- package/skills/qore-add-integration/SKILL.next.md +7 -13
- package/skills/qore-add-integration/SKILL.node.md +7 -13
- package/skills/qore-author-skill/SKILL.md +0 -1
- package/dist/chunk-5RAO3LPF.js +0 -116
- package/dist/chunk-5RAO3LPF.js.map +0 -1
- package/dist/chunk-NMJOF3ZM.js.map +0 -1
- package/dist/chunk-P7HNHLW7.js +0 -65
- package/dist/chunk-P7HNHLW7.js.map +0 -1
- package/dist/chunk-QMOZDE3U.js +0 -158
- package/dist/chunk-QMOZDE3U.js.map +0 -1
- package/dist/chunk-WU7N4PET.js +0 -20
- package/dist/chunk-WU7N4PET.js.map +0 -1
- package/dist/mail/index.d.ts +0 -9
- package/dist/mail/index.js +0 -26
- package/dist/mail/index.js.map +0 -1
- package/dist/next/boot/index.d.ts +0 -33
- package/dist/next/boot/index.js +0 -21
- package/dist/next/boot/index.js.map +0 -1
- package/dist/next/global-error/index.d.ts +0 -9
- package/dist/next/global-error/index.js +0 -17
- package/dist/next/global-error/index.js.map +0 -1
- package/dist/next/platform/index.d.ts +0 -19
- package/dist/next/platform/index.js +0 -44
- package/dist/next/platform/index.js.map +0 -1
- package/dist/node/boot/index.d.ts +0 -9
- package/dist/node/boot/index.js +0 -13
- package/dist/node/boot/index.js.map +0 -1
- package/dist/node-HH3ZZD2R.js +0 -46
- package/dist/node-HH3ZZD2R.js.map +0 -1
- package/dist/types-Cl7g4ego.d.ts +0 -80
- package/migrations/bootstrap-qore-env/codemod.mjs +0 -77
- package/migrations/bootstrap-qore-env/instructions.md +0 -28
- package/migrations/bootstrap-qore-env/meta.json +0 -7
- package/migrations/global-error/codemod.mjs +0 -28
- package/migrations/global-error/instructions.md +0 -26
- package/migrations/global-error/meta.json +0 -7
- package/migrations/local-db-port/codemod.mjs +0 -61
- package/migrations/local-db-port/instructions.md +0 -45
- package/migrations/local-db-port/meta.json +0 -7
- package/migrations/mail-reexport/codemod.mjs +0 -64
- package/migrations/mail-reexport/instructions.md +0 -27
- package/migrations/mail-reexport/meta.json +0 -7
- package/migrations/platform-routes/codemod.mjs +0 -45
- package/migrations/platform-routes/instructions.md +0 -30
- package/migrations/platform-routes/meta.json +0 -7
- package/migrations/qore-boot/codemod.mjs +0 -263
- package/migrations/qore-boot/instructions.md +0 -74
- package/migrations/qore-boot/meta.json +0 -7
- package/migrations/qore-proxy/codemod.mjs +0 -88
- package/migrations/qore-proxy/instructions.md +0 -56
- package/migrations/qore-proxy/meta.json +0 -7
- package/migrations/run.mjs +0 -334
- package/migrations/sourcemaps-finalize/codemod.mjs +0 -63
- package/migrations/sourcemaps-finalize/instructions.md +0 -56
- package/migrations/sourcemaps-finalize/meta.json +0 -7
- package/skills/qore-add-env-key/SKILL.md +0 -57
- package/workspace-requirements.json +0 -4
package/dist/next/db/index.d.ts
CHANGED
|
@@ -9,21 +9,4 @@ 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
|
-
|
|
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 };
|
|
12
|
+
export { type MigrationDb, createMigrationDb, grantRuntimeDefaultPrivileges, parseRoleFromUrl };
|
package/dist/next/db/index.js
CHANGED
|
@@ -7,35 +7,10 @@ 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
|
-
}
|
|
34
10
|
export {
|
|
35
11
|
createMigrationDb,
|
|
36
12
|
grantRuntimeDefaultPrivileges,
|
|
37
13
|
isNorthflankManagedPostgres,
|
|
38
|
-
migrateApp,
|
|
39
14
|
parseRoleFromUrl,
|
|
40
15
|
resolvePostgresConfig
|
|
41
16
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export {
|
|
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';
|
|
1
|
+
export { AUTH_ENV_FIELDS, AUTH_SECRET_FIELDS, AuthKind, DEFAULT_INTEGRATION_TIMEOUT_MS, EnvKey, EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, IntegrationAuth, IntegrationClient, IntegrationConfig, IntegrationDefinition, IntegrationError, IntegrationErrorCode, IntegrationHandle, IntegrationMap, IntegrationProblem, IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, ParamValue, Protocol, RESERVED_KEY_PREFIX, allKeys, assertIntegrations, createIntegrationClient, defineIntegrations, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys } from '../../integrations/index.js';
|
|
3
2
|
import '../../env-R-bci5RU.js';
|
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
import {
|
|
2
|
+
AUTH_ENV_FIELDS,
|
|
3
|
+
AUTH_SECRET_FIELDS,
|
|
2
4
|
DEFAULT_INTEGRATION_TIMEOUT_MS,
|
|
3
5
|
INTEGRATION_ALIAS_ATTR,
|
|
4
6
|
INTEGRATION_SPAN_TYPE,
|
|
5
7
|
INTEGRATION_SPAN_TYPE_ATTR,
|
|
6
8
|
IntegrationError,
|
|
7
9
|
OAUTH_REFRESH_SKEW_MS,
|
|
8
|
-
createIntegrationClient
|
|
9
|
-
} from "../../chunk-NMJOF3ZM.js";
|
|
10
|
-
import {
|
|
11
|
-
AUTH_ENV_FIELDS,
|
|
12
|
-
AUTH_SECRET_FIELDS,
|
|
13
10
|
RESERVED_KEY_PREFIX,
|
|
14
11
|
allKeys,
|
|
15
12
|
assertIntegrations,
|
|
13
|
+
createIntegrationClient,
|
|
16
14
|
defineIntegrations,
|
|
17
15
|
loggingEnabled,
|
|
18
16
|
loggingKey,
|
|
19
17
|
readRef,
|
|
20
18
|
requiredKeys
|
|
21
|
-
} from "../../chunk-
|
|
19
|
+
} from "../../chunk-2AYDFLKR.js";
|
|
22
20
|
import {
|
|
23
21
|
PLATFORM_MANAGED_HOSTS,
|
|
24
22
|
isPlatformManagedHost
|
|
@@ -96,8 +96,6 @@ 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";
|
|
101
99
|
/**
|
|
102
100
|
* Build the `POST` handler for `src/app/api/csp-report/route.ts`.
|
|
103
101
|
*
|
|
@@ -107,26 +105,6 @@ declare const QORE_CSP_REPORT_URI = "/api/qore/csp-report";
|
|
|
107
105
|
*/
|
|
108
106
|
declare function createCspReportRoute(options: CspReportRouteOptions): (request: Request) => Promise<Response>;
|
|
109
107
|
|
|
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
|
-
|
|
130
108
|
/**
|
|
131
109
|
* What a Next proxy (formerly "middleware") is allowed to be.
|
|
132
110
|
*
|
|
@@ -173,4 +151,4 @@ declare const NONCE_HEADER = "x-qdc-nonce";
|
|
|
173
151
|
*/
|
|
174
152
|
declare function withSecurityHeaders(handler: ProxyHandlerFn, options?: SecurityHeaderOptions): SecuredProxy;
|
|
175
153
|
|
|
176
|
-
export { type CspReportFields, type CspReportLogger, type CspReportRouteOptions, NONCE_HEADER, type ProxyHandlerFn,
|
|
154
|
+
export { type CspReportFields, type CspReportLogger, type CspReportRouteOptions, NONCE_HEADER, type ProxyHandlerFn, STATIC_SECURITY_HEADERS, type SecuredProxy, type SecurityHeaderOptions, buildCsp, createCspReportRoute, proxyMatcher, readCspReport, withSecurityHeaders };
|
|
@@ -1,18 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseJsonBounded
|
|
3
|
+
} from "../../chunk-FUPTRHT7.js";
|
|
1
4
|
import {
|
|
2
5
|
proxyMatcher
|
|
3
6
|
} from "../../chunk-X6D3TBNS.js";
|
|
4
|
-
import {
|
|
5
|
-
QORE_CSP_REPORT_URI,
|
|
6
|
-
createCspReportRoute,
|
|
7
|
-
readCspReport
|
|
8
|
-
} from "../../chunk-P7HNHLW7.js";
|
|
9
|
-
import "../../chunk-FUPTRHT7.js";
|
|
10
7
|
import {
|
|
11
8
|
STATIC_SECURITY_HEADERS
|
|
12
9
|
} from "../../chunk-2HE2D4SY.js";
|
|
13
10
|
|
|
14
11
|
// src/next/security/index.ts
|
|
15
|
-
import { NextResponse
|
|
12
|
+
import { NextResponse } from "next/server";
|
|
16
13
|
|
|
17
14
|
// src/security-core/csp.ts
|
|
18
15
|
var HTTP_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
@@ -67,36 +64,58 @@ function cspHeaderName(options = {}) {
|
|
|
67
64
|
return options.reportOnly ?? true ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
|
|
68
65
|
}
|
|
69
66
|
|
|
70
|
-
// src/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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);
|
|
67
|
+
// src/security-core/cspReport.ts
|
|
68
|
+
var DEFAULT_MAX_BYTES = 16 * 1024;
|
|
69
|
+
function asRecord(value) {
|
|
70
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
81
71
|
}
|
|
82
|
-
function
|
|
83
|
-
|
|
84
|
-
const url = req.nextUrl.clone();
|
|
85
|
-
url.pathname = "/login";
|
|
86
|
-
return NextResponse.redirect(url);
|
|
72
|
+
function asString(value) {
|
|
73
|
+
return typeof value === "string" && value.length > 0 ? value.slice(0, 500) : void 0;
|
|
87
74
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
75
|
+
function collectReports(payload) {
|
|
76
|
+
const single = asRecord(payload);
|
|
77
|
+
if (single) {
|
|
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 [];
|
|
85
|
+
}
|
|
86
|
+
function readCspReport(report) {
|
|
87
|
+
return {
|
|
88
|
+
documentUri: asString(report["document-uri"] ?? report["documentURL"]),
|
|
89
|
+
blockedUri: asString(report["blocked-uri"] ?? report["blockedURL"]),
|
|
90
|
+
effectiveDirective: asString(report["effective-directive"] ?? report["effectiveDirective"]),
|
|
91
|
+
disposition: asString(report["disposition"])
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createCspReportRoute(options) {
|
|
95
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
96
|
+
const log = options.log;
|
|
97
|
+
return async function POST(request) {
|
|
98
|
+
const noContent = () => new Response(null, { status: 204 });
|
|
99
|
+
let body;
|
|
100
|
+
try {
|
|
101
|
+
body = await request.text();
|
|
102
|
+
} catch {
|
|
103
|
+
return noContent();
|
|
104
|
+
}
|
|
105
|
+
if (body.length === 0 || body.length > maxBytes) {
|
|
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
|
+
};
|
|
100
119
|
}
|
|
101
120
|
|
|
102
121
|
// src/next/security/index.ts
|
|
@@ -139,9 +158,9 @@ function withSecurityHeaders(handler, options = {}) {
|
|
|
139
158
|
const handled = await handler(request, event);
|
|
140
159
|
let response;
|
|
141
160
|
if (!handled) {
|
|
142
|
-
response =
|
|
161
|
+
response = NextResponse.next({ request: { headers: requestHeaders } });
|
|
143
162
|
} else if (isPassThrough(handled)) {
|
|
144
|
-
response =
|
|
163
|
+
response = NextResponse.next({ request: { headers: requestHeaders } });
|
|
145
164
|
carryOver(handled, response);
|
|
146
165
|
} else {
|
|
147
166
|
response = handled;
|
|
@@ -152,12 +171,10 @@ function withSecurityHeaders(handler, options = {}) {
|
|
|
152
171
|
}
|
|
153
172
|
export {
|
|
154
173
|
NONCE_HEADER,
|
|
155
|
-
QORE_CSP_REPORT_URI,
|
|
156
174
|
STATIC_SECURITY_HEADERS,
|
|
157
175
|
buildCsp,
|
|
158
176
|
createCspReportRoute,
|
|
159
177
|
proxyMatcher,
|
|
160
|
-
qoreProxy,
|
|
161
178
|
readCspReport,
|
|
162
179
|
withSecurityHeaders
|
|
163
180
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/next/security/index.ts","../../../src/security-core/csp.ts","../../../src/next/security/qoreProxy.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, 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_CSP_REPORT_URI, ...options.security },\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,gBAAAA,qBAAoB;;;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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AAQ,IAAI,SAAS,GAAG;AACnC;AAsBO,SAAS,oBACd,SACA,UAAiC,CAAC,GACpB;AACd,SAAO,OAAO,SAAsB,UAA6C;AAC/E,UAAM,QAAQ,cAAc;AAC5B,UAAM,MAAM,SAAS,OAAO,EAAE,GAAG,SAAS,WAAW,QAAQ,aAAa,QAAQ,IAAI,WAAW,CAAC;AAClG,UAAM,UAAU,cAAc,OAAO;AAErC,UAAM,iBAAiB,IAAI,QAAQ,QAAQ,OAAO;AAClD,mBAAe,IAAI,cAAc,KAAK;AAGtC,mBAAe,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"]}
|
|
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;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
2
|
ALWAYS_EXCLUDED
|
|
3
3
|
} from "../../chunk-X6D3TBNS.js";
|
|
4
|
-
import {
|
|
5
|
-
QORE_CSP_REPORT_URI
|
|
6
|
-
} from "../../chunk-P7HNHLW7.js";
|
|
7
|
-
import "../../chunk-FUPTRHT7.js";
|
|
8
4
|
|
|
9
5
|
// src/next/security/testing.ts
|
|
10
6
|
var DEFAULT_SESSION_COOKIES = [
|
|
@@ -40,7 +36,6 @@ function expectHeader(response, name, value) {
|
|
|
40
36
|
);
|
|
41
37
|
}
|
|
42
38
|
}
|
|
43
|
-
var REPORT_URIS = ["/api/csp-report", QORE_CSP_REPORT_URI];
|
|
44
39
|
function expectContains(actual, needle, what) {
|
|
45
40
|
if (!actual.includes(needle)) {
|
|
46
41
|
throw new Error(`${what}: expected it to contain ${JSON.stringify(needle)}, got ${JSON.stringify(actual)}`);
|
|
@@ -87,11 +82,7 @@ function securityHeaderChecks(target) {
|
|
|
87
82
|
expectContains(first, "'strict-dynamic'", "content-security-policy");
|
|
88
83
|
expectContains(first, "frame-ancestors 'none'", "content-security-policy");
|
|
89
84
|
expectContains(first, "object-src 'none'", "content-security-policy");
|
|
90
|
-
|
|
91
|
-
throw new Error(
|
|
92
|
-
`content-security-policy: expected a report-uri of ${REPORT_URIS.join(" or ")}, got ${JSON.stringify(first)}`
|
|
93
|
-
);
|
|
94
|
-
}
|
|
85
|
+
expectContains(first, "report-uri /api/csp-report", "content-security-policy");
|
|
95
86
|
const nonce = nonceOf(first);
|
|
96
87
|
if (!nonce) throw new Error(`content-security-policy carries no nonce: ${first}`);
|
|
97
88
|
if (nonce === nonceOf(second)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/next/security/testing.ts"],"sourcesContent":["import { ALWAYS_EXCLUDED } from \"../../security-core/proxy\"\nimport { QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nimport type { SecuredProxy } from \"./index\"\n\n/**\n * The security-header contract, as a list of checks an app runs against its own\n * proxy.\n *\n * These are not tests of `@quatronic/sdk` — this package has its own. They are\n * for the generated app, so that removing `withSecurityHeaders` from\n * `src/proxy.ts`, or matching so few routes that it stops running, fails that\n * app's build rather than being noticed in a penetration test.\n *\n * It returns checks rather than declaring them, so this module needs no test\n * runner of its own and works under whichever one the app uses:\n *\n * import { describe, it } from \"vitest\"\n * import { securityHeaderChecks } from \"@quatronic/sdk/next/security/testing\"\n * import { config, proxy } from \"@/proxy\"\n *\n * describe(\"security headers\", () => {\n * for (const check of securityHeaderChecks({ proxy, config })) it(check.name, check.run)\n * })\n *\n * A failing check throws with the header it wanted and the value it got, which\n * every runner reports as the test failure.\n */\n\nexport interface SecurityContractCookie {\n name: string\n value: string\n}\n\nexport interface SecurityContractTarget {\n /** The app's `proxy` export — the value `withSecurityHeaders` returned. */\n proxy: SecuredProxy\n /** The app's `config` export. Its matcher is checked too. */\n config: { matcher: readonly string[] }\n /**\n * Cookies that make a request look signed-in, so an auth module's proxy\n * passes it through instead of redirecting.\n *\n * Defaults to both QDC session cookies at once, which is what lets one\n * shipped test file cover every recipe: an app generated from `next-auth`\n * reads `qdc_session`, one from `next-betterauth` reads\n * `better-auth.session_token`, and a `next-base` app reads neither.\n */\n sessionCookies?: readonly SecurityContractCookie[]\n /** The URL the stub request carries. Must be a route the matcher covers. */\n url?: string\n}\n\nexport interface SecurityCheck {\n name: string\n run: () => Promise<void>\n}\n\nconst DEFAULT_SESSION_COOKIES: SecurityContractCookie[] = [\n { name: \"qdc_session\", value: \"test\" },\n { name: \"better-auth.session_token\", value: \"test\" },\n]\n\nconst DEFAULT_URL = \"https://app.example.test/dashboard\"\n\nfunction nextUrlStub(href: string): URL {\n return Object.assign(new URL(href), { clone: () => nextUrlStub(href) })\n}\n\n/**\n * Enough of a `NextRequest` for a proxy: the URL it can clone and the cookie\n * jar it reads. Casting through `unknown` keeps the stub honest about being one\n * — a partial `NextRequest` is exactly what this is.\n */\nfunction makeRequest(url: string, cookies: readonly SecurityContractCookie[]): NextRequestStub {\n return Object.assign(new Request(url), {\n nextUrl: nextUrlStub(url),\n cookies: {\n has: (name: string) => cookies.some((cookie) => cookie.name === name),\n get: (name: string) => cookies.find((cookie) => cookie.name === name),\n getAll: () => [...cookies],\n },\n }) as unknown as NextRequestStub\n}\n\ntype NextRequestStub = Parameters<SecuredProxy>[0]\n\n/** No runtime reads the fetch event, and jsdom has no `NextFetchEvent`. */\nconst NO_EVENT = {} as unknown as Parameters<SecuredProxy>[1]\n\nfunction cspOf(response: Response): string {\n return (\n response.headers.get(\"content-security-policy\") ??\n response.headers.get(\"content-security-policy-report-only\") ??\n \"\"\n )\n}\n\nfunction nonceOf(csp: string): string | undefined {\n return /'nonce-([^']+)'/.exec(csp)?.[1]\n}\n\nfunction expectHeader(response: Response, name: string, value: string): void {\n const actual = response.headers.get(name)\n if (actual !== value) {\n throw new Error(\n `${name}: expected ${JSON.stringify(value)}, got ${actual === null ? \"no header\" : JSON.stringify(actual)}`,\n )\n }\n}\n\nconst REPORT_URIS = [\"/api/csp-report\", QORE_CSP_REPORT_URI]\n\nfunction expectContains(actual: string, needle: string, what: string): void {\n if (!actual.includes(needle)) {\n throw new Error(`${what}: expected it to contain ${JSON.stringify(needle)}, got ${JSON.stringify(actual)}`)\n }\n}\n\nexport function securityHeaderChecks(target: SecurityContractTarget): SecurityCheck[] {\n const url = target.url ?? DEFAULT_URL\n const signedIn = target.sessionCookies ?? DEFAULT_SESSION_COOKIES\n const run = (cookies: readonly SecurityContractCookie[]): Promise<Response> =>\n Promise.resolve(target.proxy(makeRequest(url, cookies), NO_EVENT))\n\n return [\n {\n name: \"sends the static headers on a signed-in request\",\n async run() {\n const response = await run(signedIn)\n expectHeader(response, \"x-content-type-options\", \"nosniff\")\n expectHeader(response, \"x-frame-options\", \"DENY\")\n expectHeader(response, \"referrer-policy\", \"strict-origin-when-cross-origin\")\n expectHeader(response, \"cross-origin-resource-policy\", \"same-origin\")\n expectContains(\n response.headers.get(\"strict-transport-security\") ?? \"\",\n \"max-age=\",\n \"strict-transport-security\",\n )\n expectContains(\n response.headers.get(\"permissions-policy\") ?? \"\",\n \"camera=()\",\n \"permissions-policy\",\n )\n },\n },\n {\n name: \"sends them on a request with no session too\",\n async run() {\n // Whatever this app does with an anonymous request — pass it through or\n // redirect it to a login — the response is still one the browser hardens.\n const response = await run([])\n expectHeader(response, \"x-content-type-options\", \"nosniff\")\n expectContains(cspOf(response), \"default-src 'self'\", \"content-security-policy\")\n },\n },\n {\n name: \"builds a CSP with a fresh nonce per response\",\n async run() {\n const first = cspOf(await run(signedIn))\n const second = cspOf(await run(signedIn))\n\n expectContains(first, \"'strict-dynamic'\", \"content-security-policy\")\n expectContains(first, \"frame-ancestors 'none'\", \"content-security-policy\")\n expectContains(first, \"object-src 'none'\", \"content-security-policy\")\n // `withSecurityHeaders` reports to the app's own route, `qoreProxy` to the\n // platform's; either one collects the evidence.\n if (!REPORT_URIS.some((uri) => first.includes(`report-uri ${uri}`))) {\n throw new Error(\n `content-security-policy: expected a report-uri of ${REPORT_URIS.join(\" or \")}, got ${JSON.stringify(first)}`,\n )\n }\n\n const nonce = nonceOf(first)\n if (!nonce) throw new Error(`content-security-policy carries no nonce: ${first}`)\n if (nonce === nonceOf(second)) {\n throw new Error(`two responses shared one nonce (${nonce}); a reused nonce protects nothing`)\n }\n },\n },\n {\n name: \"hands the nonce to the renderer on the forwarded request\",\n async run() {\n // A nonce only protects anything if the page carrying it is the page the\n // nonce was minted for. Next reads it off the request's CSP header.\n const response = await run(signedIn)\n const nonce = nonceOf(cspOf(response))\n if (!nonce) throw new Error(\"content-security-policy carries no nonce\")\n\n expectHeader(response, \"x-middleware-request-x-qdc-nonce\", nonce)\n expectContains(\n response.headers.get(\"x-middleware-request-content-security-policy\") ?? \"\",\n `'nonce-${nonce}'`,\n \"the forwarded request's content-security-policy\",\n )\n },\n },\n {\n name: \"matches every route that serves HTML\",\n run() {\n if (target.config.matcher.length === 0) {\n throw new Error(\"config.matcher is empty, so the proxy never runs\")\n }\n // Next extracts `config` statically, so the app writes this as a\n // literal rather than calling `proxyMatcher`. That makes the literal\n // the thing that can drift, and this the check that catches it: the\n // build output and the image optimizer are the only sanctioned holes,\n // and nonce-ing them would be pointless work on every asset request.\n for (const pattern of target.config.matcher) {\n for (const excluded of ALWAYS_EXCLUDED) {\n expectContains(pattern, excluded, \"config.matcher entry\")\n }\n }\n return Promise.resolve()\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;AAyDA,IAAM,0BAAoD;AAAA,EACxD,EAAE,MAAM,eAAe,OAAO,OAAO;AAAA,EACrC,EAAE,MAAM,6BAA6B,OAAO,OAAO;AACrD;AAEA,IAAM,cAAc;AAEpB,SAAS,YAAY,MAAmB;AACtC,SAAO,OAAO,OAAO,IAAI,IAAI,IAAI,GAAG,EAAE,OAAO,MAAM,YAAY,IAAI,EAAE,CAAC;AACxE;AAOA,SAAS,YAAY,KAAa,SAA6D;AAC7F,SAAO,OAAO,OAAO,IAAI,QAAQ,GAAG,GAAG;AAAA,IACrC,SAAS,YAAY,GAAG;AAAA,IACxB,SAAS;AAAA,MACP,KAAK,CAAC,SAAiB,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,IAAI;AAAA,MACpE,KAAK,CAAC,SAAiB,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,IAAI;AAAA,MACpE,QAAQ,MAAM,CAAC,GAAG,OAAO;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAKA,IAAM,WAAW,CAAC;AAElB,SAAS,MAAM,UAA4B;AACzC,SACE,SAAS,QAAQ,IAAI,yBAAyB,KAC9C,SAAS,QAAQ,IAAI,qCAAqC,KAC1D;AAEJ;AAEA,SAAS,QAAQ,KAAiC;AAChD,SAAO,kBAAkB,KAAK,GAAG,IAAI,CAAC;AACxC;AAEA,SAAS,aAAa,UAAoB,MAAc,OAAqB;AAC3E,QAAM,SAAS,SAAS,QAAQ,IAAI,IAAI;AACxC,MAAI,WAAW,OAAO;AACpB,UAAM,IAAI;AA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;AACA,eAAO,QAAQ,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/next/security/testing.ts"],"sourcesContent":["import { ALWAYS_EXCLUDED } from \"../../security-core/proxy\"\nimport type { SecuredProxy } from \"./index\"\n\n/**\n * The security-header contract, as a list of checks an app runs against its own\n * proxy.\n *\n * These are not tests of `@quatronic/sdk` — this package has its own. They are\n * for the generated app, so that removing `withSecurityHeaders` from\n * `src/proxy.ts`, or matching so few routes that it stops running, fails that\n * app's build rather than being noticed in a penetration test.\n *\n * It returns checks rather than declaring them, so this module needs no test\n * runner of its own and works under whichever one the app uses:\n *\n * import { describe, it } from \"vitest\"\n * import { securityHeaderChecks } from \"@quatronic/sdk/next/security/testing\"\n * import { config, proxy } from \"@/proxy\"\n *\n * describe(\"security headers\", () => {\n * for (const check of securityHeaderChecks({ proxy, config })) it(check.name, check.run)\n * })\n *\n * A failing check throws with the header it wanted and the value it got, which\n * every runner reports as the test failure.\n */\n\nexport interface SecurityContractCookie {\n name: string\n value: string\n}\n\nexport interface SecurityContractTarget {\n /** The app's `proxy` export — the value `withSecurityHeaders` returned. */\n proxy: SecuredProxy\n /** The app's `config` export. Its matcher is checked too. */\n config: { matcher: readonly string[] }\n /**\n * Cookies that make a request look signed-in, so an auth module's proxy\n * passes it through instead of redirecting.\n *\n * Defaults to both QDC session cookies at once, which is what lets one\n * shipped test file cover every recipe: an app generated from `next-auth`\n * reads `qdc_session`, one from `next-betterauth` reads\n * `better-auth.session_token`, and a `next-base` app reads neither.\n */\n sessionCookies?: readonly SecurityContractCookie[]\n /** The URL the stub request carries. Must be a route the matcher covers. */\n url?: string\n}\n\nexport interface SecurityCheck {\n name: string\n run: () => Promise<void>\n}\n\nconst DEFAULT_SESSION_COOKIES: SecurityContractCookie[] = [\n { name: \"qdc_session\", value: \"test\" },\n { name: \"better-auth.session_token\", value: \"test\" },\n]\n\nconst DEFAULT_URL = \"https://app.example.test/dashboard\"\n\nfunction nextUrlStub(href: string): URL {\n return Object.assign(new URL(href), { clone: () => nextUrlStub(href) })\n}\n\n/**\n * Enough of a `NextRequest` for a proxy: the URL it can clone and the cookie\n * jar it reads. Casting through `unknown` keeps the stub honest about being one\n * — a partial `NextRequest` is exactly what this is.\n */\nfunction makeRequest(url: string, cookies: readonly SecurityContractCookie[]): NextRequestStub {\n return Object.assign(new Request(url), {\n nextUrl: nextUrlStub(url),\n cookies: {\n has: (name: string) => cookies.some((cookie) => cookie.name === name),\n get: (name: string) => cookies.find((cookie) => cookie.name === name),\n getAll: () => [...cookies],\n },\n }) as unknown as NextRequestStub\n}\n\ntype NextRequestStub = Parameters<SecuredProxy>[0]\n\n/** No runtime reads the fetch event, and jsdom has no `NextFetchEvent`. */\nconst NO_EVENT = {} as unknown as Parameters<SecuredProxy>[1]\n\nfunction cspOf(response: Response): string {\n return (\n response.headers.get(\"content-security-policy\") ??\n response.headers.get(\"content-security-policy-report-only\") ??\n \"\"\n )\n}\n\nfunction nonceOf(csp: string): string | undefined {\n return /'nonce-([^']+)'/.exec(csp)?.[1]\n}\n\nfunction expectHeader(response: Response, name: string, value: string): void {\n const actual = response.headers.get(name)\n if (actual !== value) {\n throw new Error(\n `${name}: expected ${JSON.stringify(value)}, got ${actual === null ? \"no header\" : JSON.stringify(actual)}`,\n )\n }\n}\n\nfunction expectContains(actual: string, needle: string, what: string): void {\n if (!actual.includes(needle)) {\n throw new Error(`${what}: expected it to contain ${JSON.stringify(needle)}, got ${JSON.stringify(actual)}`)\n }\n}\n\nexport function securityHeaderChecks(target: SecurityContractTarget): SecurityCheck[] {\n const url = target.url ?? DEFAULT_URL\n const signedIn = target.sessionCookies ?? DEFAULT_SESSION_COOKIES\n const run = (cookies: readonly SecurityContractCookie[]): Promise<Response> =>\n Promise.resolve(target.proxy(makeRequest(url, cookies), NO_EVENT))\n\n return [\n {\n name: \"sends the static headers on a signed-in request\",\n async run() {\n const response = await run(signedIn)\n expectHeader(response, \"x-content-type-options\", \"nosniff\")\n expectHeader(response, \"x-frame-options\", \"DENY\")\n expectHeader(response, \"referrer-policy\", \"strict-origin-when-cross-origin\")\n expectHeader(response, \"cross-origin-resource-policy\", \"same-origin\")\n expectContains(\n response.headers.get(\"strict-transport-security\") ?? \"\",\n \"max-age=\",\n \"strict-transport-security\",\n )\n expectContains(\n response.headers.get(\"permissions-policy\") ?? \"\",\n \"camera=()\",\n \"permissions-policy\",\n )\n },\n },\n {\n name: \"sends them on a request with no session too\",\n async run() {\n // Whatever this app does with an anonymous request — pass it through or\n // redirect it to a login — the response is still one the browser hardens.\n const response = await run([])\n expectHeader(response, \"x-content-type-options\", \"nosniff\")\n expectContains(cspOf(response), \"default-src 'self'\", \"content-security-policy\")\n },\n },\n {\n name: \"builds a CSP with a fresh nonce per response\",\n async run() {\n const first = cspOf(await run(signedIn))\n const second = cspOf(await run(signedIn))\n\n expectContains(first, \"'strict-dynamic'\", \"content-security-policy\")\n expectContains(first, \"frame-ancestors 'none'\", \"content-security-policy\")\n expectContains(first, \"object-src 'none'\", \"content-security-policy\")\n expectContains(first, \"report-uri /api/csp-report\", \"content-security-policy\")\n\n const nonce = nonceOf(first)\n if (!nonce) throw new Error(`content-security-policy carries no nonce: ${first}`)\n if (nonce === nonceOf(second)) {\n throw new Error(`two responses shared one nonce (${nonce}); a reused nonce protects nothing`)\n }\n },\n },\n {\n name: \"hands the nonce to the renderer on the forwarded request\",\n async run() {\n // A nonce only protects anything if the page carrying it is the page the\n // nonce was minted for. Next reads it off the request's CSP header.\n const response = await run(signedIn)\n const nonce = nonceOf(cspOf(response))\n if (!nonce) throw new Error(\"content-security-policy carries no nonce\")\n\n expectHeader(response, \"x-middleware-request-x-qdc-nonce\", nonce)\n expectContains(\n response.headers.get(\"x-middleware-request-content-security-policy\") ?? \"\",\n `'nonce-${nonce}'`,\n \"the forwarded request's content-security-policy\",\n )\n },\n },\n {\n name: \"matches every route that serves HTML\",\n run() {\n if (target.config.matcher.length === 0) {\n throw new Error(\"config.matcher is empty, so the proxy never runs\")\n }\n // Next extracts `config` statically, so the app writes this as a\n // literal rather than calling `proxyMatcher`. That makes the literal\n // the thing that can drift, and this the check that catches it: the\n // build output and the image optimizer are the only sanctioned holes,\n // and nonce-ing them would be pointless work on every asset request.\n for (const pattern of target.config.matcher) {\n for (const excluded of ALWAYS_EXCLUDED) {\n expectContains(pattern, excluded, \"config.matcher entry\")\n }\n }\n return Promise.resolve()\n },\n },\n ]\n}\n"],"mappings":";;;;;AAwDA,IAAM,0BAAoD;AAAA,EACxD,EAAE,MAAM,eAAe,OAAO,OAAO;AAAA,EACrC,EAAE,MAAM,6BAA6B,OAAO,OAAO;AACrD;AAEA,IAAM,cAAc;AAEpB,SAAS,YAAY,MAAmB;AACtC,SAAO,OAAO,OAAO,IAAI,IAAI,IAAI,GAAG,EAAE,OAAO,MAAM,YAAY,IAAI,EAAE,CAAC;AACxE;AAOA,SAAS,YAAY,KAAa,SAA6D;AAC7F,SAAO,OAAO,OAAO,IAAI,QAAQ,GAAG,GAAG;AAAA,IACrC,SAAS,YAAY,GAAG;AAAA,IACxB,SAAS;AAAA,MACP,KAAK,CAAC,SAAiB,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,IAAI;AAAA,MACpE,KAAK,CAAC,SAAiB,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,IAAI;AAAA,MACpE,QAAQ,MAAM,CAAC,GAAG,OAAO;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAKA,IAAM,WAAW,CAAC;AAElB,SAAS,MAAM,UAA4B;AACzC,SACE,SAAS,QAAQ,IAAI,yBAAyB,KAC9C,SAAS,QAAQ,IAAI,qCAAqC,KAC1D;AAEJ;AAEA,SAAS,QAAQ,KAAiC;AAChD,SAAO,kBAAkB,KAAK,GAAG,IAAI,CAAC;AACxC;AAEA,SAAS,aAAa,UAAoB,MAAc,OAAqB;AAC3E,QAAM,SAAS,SAAS,QAAQ,IAAI,IAAI;AACxC,MAAI,WAAW,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
|
-
import "../../chunk-G7VPNC6M.js";
|
|
2
|
+
initSentry
|
|
3
|
+
} from "../../chunk-G7VPNC6M.js";
|
|
6
4
|
import "../../chunk-MET4SIMB.js";
|
|
7
|
-
import
|
|
5
|
+
import {
|
|
6
|
+
readSentryConfig
|
|
7
|
+
} from "../../chunk-7ASQHY7O.js";
|
|
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;
|
|
8
16
|
export {
|
|
9
17
|
onRequestError,
|
|
10
18
|
register
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/next/sentry/register.ts"],"sourcesContent":["import * as Sentry from \"@sentry/nextjs\"\nimport { readSentryConfig } from \"../../sentry-core/env\"\nimport { initSentry } from \"../../sentry-core/init\"\n\nexport async function register(): Promise<void> {\n const runtime = process.env.NEXT_RUNTIME === \"edge\" ? \"edge\" : \"node\"\n initSentry(Sentry, runtime, readSentryConfig(process.env, { frontend: true }))\n}\n\nexport const onRequestError = Sentry.captureRequestError\n"],"mappings":";;;;;;;;;AAAA,YAAY,YAAY;AAIxB,eAAsB,WAA0B;AAC9C,QAAM,UAAU,QAAQ,IAAI,iBAAiB,SAAS,SAAS;AAC/D,aAAW,QAAQ,SAAS,iBAAiB,QAAQ,KAAK,EAAE,UAAU,KAAK,CAAC,CAAC;AAC/E;AAEO,IAAM,iBAAwB;","names":[]}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export {
|
|
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';
|
|
1
|
+
export { AUTH_ENV_FIELDS, AUTH_SECRET_FIELDS, AuthKind, DEFAULT_INTEGRATION_TIMEOUT_MS, EnvKey, EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, IntegrationAuth, IntegrationClient, IntegrationConfig, IntegrationDefinition, IntegrationError, IntegrationErrorCode, IntegrationHandle, IntegrationMap, IntegrationProblem, IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, ParamValue, Protocol, RESERVED_KEY_PREFIX, allKeys, assertIntegrations, createIntegrationClient, defineIntegrations, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys } from '../../integrations/index.js';
|
|
3
2
|
import '../../env-R-bci5RU.js';
|
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
import {
|
|
2
|
+
AUTH_ENV_FIELDS,
|
|
3
|
+
AUTH_SECRET_FIELDS,
|
|
2
4
|
DEFAULT_INTEGRATION_TIMEOUT_MS,
|
|
3
5
|
INTEGRATION_ALIAS_ATTR,
|
|
4
6
|
INTEGRATION_SPAN_TYPE,
|
|
5
7
|
INTEGRATION_SPAN_TYPE_ATTR,
|
|
6
8
|
IntegrationError,
|
|
7
9
|
OAUTH_REFRESH_SKEW_MS,
|
|
8
|
-
createIntegrationClient
|
|
9
|
-
} from "../../chunk-NMJOF3ZM.js";
|
|
10
|
-
import {
|
|
11
|
-
AUTH_ENV_FIELDS,
|
|
12
|
-
AUTH_SECRET_FIELDS,
|
|
13
10
|
RESERVED_KEY_PREFIX,
|
|
14
11
|
allKeys,
|
|
15
12
|
assertIntegrations,
|
|
13
|
+
createIntegrationClient,
|
|
16
14
|
defineIntegrations,
|
|
17
15
|
loggingEnabled,
|
|
18
16
|
loggingKey,
|
|
19
17
|
readRef,
|
|
20
18
|
requiredKeys
|
|
21
|
-
} from "../../chunk-
|
|
19
|
+
} from "../../chunk-2AYDFLKR.js";
|
|
22
20
|
import {
|
|
23
21
|
PLATFORM_MANAGED_HOSTS,
|
|
24
22
|
isPlatformManagedHost
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quatronic/sdk",
|
|
3
|
-
"version": "0.7.1
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"private": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -12,8 +12,7 @@
|
|
|
12
12
|
"migrations",
|
|
13
13
|
"semgrep",
|
|
14
14
|
"skills",
|
|
15
|
-
"postinstall.mjs"
|
|
16
|
-
"workspace-requirements.json"
|
|
15
|
+
"postinstall.mjs"
|
|
17
16
|
],
|
|
18
17
|
"bin": {
|
|
19
18
|
"qore-skills": "./dist/cli/skills.js",
|
|
@@ -123,26 +122,6 @@
|
|
|
123
122
|
"./next/db": {
|
|
124
123
|
"types": "./dist/next/db/index.d.ts",
|
|
125
124
|
"import": "./dist/next/db/index.js"
|
|
126
|
-
},
|
|
127
|
-
"./mail": {
|
|
128
|
-
"types": "./dist/mail/index.d.ts",
|
|
129
|
-
"import": "./dist/mail/index.js"
|
|
130
|
-
},
|
|
131
|
-
"./next/boot": {
|
|
132
|
-
"types": "./dist/next/boot/index.d.ts",
|
|
133
|
-
"import": "./dist/next/boot/index.js"
|
|
134
|
-
},
|
|
135
|
-
"./node/boot": {
|
|
136
|
-
"types": "./dist/node/boot/index.d.ts",
|
|
137
|
-
"import": "./dist/node/boot/index.js"
|
|
138
|
-
},
|
|
139
|
-
"./next/global-error": {
|
|
140
|
-
"types": "./dist/next/global-error/index.d.ts",
|
|
141
|
-
"import": "./dist/next/global-error/index.js"
|
|
142
|
-
},
|
|
143
|
-
"./next/platform": {
|
|
144
|
-
"types": "./dist/next/platform/index.d.ts",
|
|
145
|
-
"import": "./dist/next/platform/index.js"
|
|
146
125
|
}
|
|
147
126
|
},
|
|
148
127
|
"scripts": {
|
|
@@ -220,7 +199,7 @@
|
|
|
220
199
|
"@types/pg": "^8.11.10",
|
|
221
200
|
"@types/react": "^18.3.17",
|
|
222
201
|
"@types/react-dom": "^18.3.5",
|
|
223
|
-
"@vitest/coverage-v8": "^
|
|
202
|
+
"@vitest/coverage-v8": "^2.1.9",
|
|
224
203
|
"better-auth": "^1.6.24",
|
|
225
204
|
"drizzle-kit": "^0.30.1",
|
|
226
205
|
"drizzle-orm": "^0.38.2",
|
|
@@ -236,7 +215,6 @@
|
|
|
236
215
|
"tsup": "^8.3.5",
|
|
237
216
|
"typescript": "^5.7.2",
|
|
238
217
|
"typescript-eslint": "^8.61.1",
|
|
239
|
-
"
|
|
240
|
-
"vitest": "^4.1.12"
|
|
218
|
+
"vitest": "^2.1.8"
|
|
241
219
|
}
|
|
242
220
|
}
|
package/skills/catalog.json
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
{"name": "qore-add-api-route", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-add-api-route"]},
|
|
4
4
|
{"name": "qore-add-connection", "kind": "contract", "legacyNames": ["quatronic-add-connection"]},
|
|
5
5
|
{"name": "qore-add-db-table", "kind": "convenience", "requires": ["runtime=next", "db"], "legacyNames": ["quatronic-add-db-table"]},
|
|
6
|
-
{"name": "qore-add-env-key", "kind": "contract"},
|
|
7
6
|
{"name": "qore-add-feature", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-add-feature"]},
|
|
8
7
|
{"name": "qore-add-integration", "kind": "contract", "legacyNames": ["quatronic-add-integration"]},
|
|
9
8
|
{"name": "qore-add-page", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-add-page"]},
|