@quatronic/sdk 0.7.0-test.3603305 → 0.7.1-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-F3NHTHFO.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/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 +55 -38
- package/dist/next/security/index.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/package.json +4 -26
- package/dist/chunk-F3NHTHFO.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-TOBGX4CZ.js +0 -109
- package/dist/chunk-TOBGX4CZ.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-Z7ERWJDZ.js +0 -46
- package/dist/node-Z7ERWJDZ.js.map +0 -1
- package/dist/types-CAwj03sM.d.ts +0 -75
- 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 -35
- 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 -261
- 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 -322
- 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/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-F3NHTHFO.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,9 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
readCspReport
|
|
5
|
-
} from "../../chunk-P7HNHLW7.js";
|
|
6
|
-
import "../../chunk-FUPTRHT7.js";
|
|
2
|
+
parseJsonBounded
|
|
3
|
+
} from "../../chunk-FUPTRHT7.js";
|
|
7
4
|
import {
|
|
8
5
|
proxyMatcher
|
|
9
6
|
} from "../../chunk-X6D3TBNS.js";
|
|
@@ -12,7 +9,7 @@ import {
|
|
|
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_RE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,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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,KAAK,yBAAyB;AACnD,aAAS,QAAQ,IAAI,MAAM,KAAK;AAAA,EAClC;AACA,WAAS,QAAQ,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,iBAAW,aAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAAA,IACvE,WAAW,cAAc,OAAO,GAAG;AACjC,iBAAW,aAAa,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":[]}
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "../../chunk-WU7N4PET.js";
|
|
5
|
-
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-F3NHTHFO.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.
|
|
3
|
+
"version": "0.7.1-rc.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
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/integrations-core/constants.ts","../src/integrations-core/errors.ts","../src/integrations-core/client.ts","../src/integrations-core/base64.ts","../src/integrations-core/oauth2.ts"],"sourcesContent":["/** Default request timeout for integration(alias).request, overridable per call. */\nexport const DEFAULT_INTEGRATION_TIMEOUT_MS = 10_000\n\n/** `qore.span.type` value on an integration call's span. */\nexport const INTEGRATION_SPAN_TYPE = \"integration_call\"\n\n/** OTel span attribute carrying the declared alias, which the portal maps to the integration. */\nexport const INTEGRATION_ALIAS_ATTR = \"qore.integration.alias\"\n\n/** OTel span attribute naming the span's kind, shared with connections (`outbound_call`). */\nexport const INTEGRATION_SPAN_TYPE_ATTR = \"qore.span.type\"\n\n/** A cached OAuth2 token is refreshed this long before it expires. */\nexport const OAUTH_REFRESH_SKEW_MS = 30_000\n","/** Why an integration call refused. */\nexport type IntegrationErrorCode =\n | \"not_declared\" // alias is not a key of the declared map\n | \"missing_env\" // a required env key for the alias is unset or empty\n | \"reserved_key\" // unused since assertIntegrations reports instead of throwing; kept so the type does not narrow\n | \"absolute_url\" // request() was given a full URL, which would bypass the declared base\n | \"missing_param\" // a `{name}` in the path template has no value in `params`\n | \"token_failed\" // the OAuth2 token endpoint refused, or answered without an access_token\n\n/**\n * Single error shape for the integrations subpath, mirroring ConnectionError.\n * Every code here is a configuration or programming error on the app's side,\n * so `status` defaults to 500.\n */\nexport class IntegrationError extends Error {\n readonly code: IntegrationErrorCode\n readonly status: number\n\n constructor(code: IntegrationErrorCode, opts?: { message?: string; status?: number }) {\n super(opts?.message ?? code)\n this.name = \"IntegrationError\"\n this.code = code\n this.status = opts?.status ?? 500\n }\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport { defaultEnv, type Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n} from \"./constants\"\nimport { loggingEnabled, readRef } from \"./env\"\nimport { IntegrationError } from \"./errors\"\nimport { getClientCredentialsToken } from \"./oauth2\"\nimport type { EnvRef, IntegrationDefinition, IntegrationMap } from \"./types\"\n\nexport type ParamValue = string | number | boolean\n\nexport interface IntegrationRequest {\n /** Values for the `{name}` placeholders in the path template; each is URI-encoded. */\n params?: Record<string, ParamValue>\n /** Query string, appended with URLSearchParams; `undefined` entries are skipped. */\n query?: Record<string, ParamValue | undefined>\n /**\n * Request body. A string, FormData, Blob, ArrayBuffer, typed array or\n * URLSearchParams is sent as is; anything else is JSON-encoded with\n * `content-type: application/json` unless the caller set one.\n */\n body?: unknown\n headers?: HeadersInit\n timeoutMs?: number\n signal?: AbortSignal\n}\n\n/** The resolved values of a definition's `config` refs, by their logical name. */\nexport type IntegrationConfig<D extends IntegrationDefinition> = D extends {\n config: infer C extends Record<string, EnvRef>\n}\n ? { [K in keyof C]: string | number | boolean | undefined }\n : Record<string, never>\n\nexport interface IntegrationHandle<D extends IntegrationDefinition = IntegrationDefinition> {\n readonly alias: string\n readonly definition: D\n /** The `config` refs read from env, defaults applied. */\n config(): IntegrationConfig<D>\n /**\n * One call against the declared base URL. `pathTemplate` is relative and\n * may hold `{name}` placeholders filled from `params`; an absolute URL is\n * refused so the integration cannot be pointed somewhere else per call.\n */\n request(method: string, pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n get(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n post(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n put(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n patch(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n delete(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n}\n\n/**\n * `integration(alias)`, typed against the declared map so an alias that is\n * not a key fails to compile.\n */\nexport type IntegrationClient<M extends IntegrationMap> = <K extends keyof M & string>(\n alias: K,\n) => IntegrationHandle<M[K]>\n\nconst PLACEHOLDER_RE = /\\{([^{}]+)\\}/g\n\nfunction isRawBody(body: unknown): body is BodyInit {\n if (typeof body === \"string\") return true\n if (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) return true\n if (typeof FormData !== \"undefined\" && body instanceof FormData) return true\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return true\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true\n return false\n}\n\n/**\n * Bind a declared map to an env. The app calls this once in\n * `src/config/integrations.ts` and exports the result as `integration`:\n *\n * export const integrations = defineIntegrations({ sap: { ... } })\n * export const integration = createIntegrationClient(integrations)\n *\n * const res = await integration(\"sap\").get(\"/A_SalesOrder('{id}')\", { params: { id } })\n *\n * There is no global registry on purpose: a handle only exists for an alias\n * the map declares, which is what lets the portal trust the declaration.\n */\nexport function createIntegrationClient<M extends IntegrationMap>(\n map: M,\n opts: { env?: Env } = {},\n): IntegrationClient<M> {\n const envOf = (): Env => opts.env ?? defaultEnv()\n\n return <K extends keyof M & string>(alias: K): IntegrationHandle<M[K]> => {\n const definition = map[alias]\n if (!definition) {\n throw new IntegrationError(\"not_declared\", {\n message: `Integration \"${alias}\" is not declared; declared: ${Object.keys(map).join(\", \") || \"(none)\"}`,\n })\n }\n return createHandle(alias, definition, envOf)\n }\n}\n\nfunction createHandle<D extends IntegrationDefinition>(\n alias: string,\n definition: D,\n envOf: () => Env,\n): IntegrationHandle<D> {\n function required(env: Env, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n }\n\n async function authHeaders(env: Env, headers: Headers, timeoutMs: number): Promise<void> {\n const auth = definition.auth\n switch (auth.kind) {\n case \"none\":\n return\n case \"api_key_header\":\n headers.set(auth.header, required(env, auth.apiKey))\n return\n case \"bearer_static\":\n headers.set(\"authorization\", `Bearer ${required(env, auth.token)}`)\n return\n case \"basic\":\n headers.set(\n \"authorization\",\n `Basic ${toBase64(`${required(env, auth.username)}:${required(env, auth.password)}`)}`,\n )\n return\n case \"oauth2_client_credentials\": {\n const token = await getClientCredentialsToken(alias, auth, env, timeoutMs)\n headers.set(\"authorization\", `Bearer ${token}`)\n return\n }\n }\n }\n\n async function request(\n method: string,\n pathTemplate: string,\n req: IntegrationRequest = {},\n ): Promise<Response> {\n const env = envOf()\n const METHOD = method.toUpperCase()\n const base = required(env, definition.baseUrl)\n\n // The declaration is the one place that says where this integration\n // lives. A full URL per call would make the handle an arbitrary-request\n // primitive that carries the integration's credentials to whatever host\n // it names, so unlike connection().fetch this refuses from day one.\n if (/^https?:\\/\\//i.test(pathTemplate)) {\n throw new IntegrationError(\"absolute_url\", {\n message: `Integration \"${alias}\" was given an absolute URL; pass a path relative to ${definition.baseUrl}`,\n })\n }\n\n const path = pathTemplate.replace(PLACEHOLDER_RE, (_match, name: string) => {\n const value = req.params?.[name]\n if (value === undefined) {\n throw new IntegrationError(\"missing_param\", {\n message: `Integration \"${alias}\": path \"${pathTemplate}\" needs params.${name}`,\n })\n }\n return encodeURIComponent(String(value))\n })\n\n let url = base.replace(/\\/+$/, \"\") + \"/\" + path.replace(/^\\/+/, \"\")\n if (req.query) {\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(req.query)) {\n if (value !== undefined) search.append(key, String(value))\n }\n const qs = search.toString()\n if (qs) url += (url.includes(\"?\") ? \"&\" : \"?\") + qs\n }\n\n const { timeoutMs = DEFAULT_INTEGRATION_TIMEOUT_MS, signal: caller } = req\n const headers = new Headers(req.headers)\n\n let body: BodyInit | undefined\n if (req.body !== undefined) {\n if (isRawBody(req.body)) {\n body = req.body\n } else {\n body = JSON.stringify(req.body)\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n }\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n if (caller) {\n if (caller.aborted) controller.abort()\n else caller.addEventListener(\"abort\", () => controller.abort(), { once: true })\n }\n\n const log = loggingEnabled(env, alias)\n const startedAt = Date.now()\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n // Named after the template, not the expanded path, so the portal can group\n // calls per endpoint; the alias attribute is what it maps to the declaration.\n return tracer.startActiveSpan(\n `→ ${alias} ${METHOD} ${pathTemplate}`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"url.template\": pathTemplate,\n \"http.request.method\": METHOD,\n },\n },\n async (span) => {\n try {\n await authHeaders(env, headers, timeoutMs)\n const res = await fetch(url, { method: METHOD, headers, body, signal: controller.signal })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (res.status >= 500) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n }\n if (log) {\n // Alias, method, template, status, duration. Never the URL (it may\n // carry ids), never headers (credentials), never a body.\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: res.status,\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n return res\n } catch (err) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n if (log) {\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: null,\n error: (err as Error)?.name ?? \"Error\",\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n }\n\n return {\n alias,\n definition,\n config() {\n const env = envOf()\n const out: Record<string, string | number | boolean | undefined> = {}\n for (const [name, ref] of Object.entries(definition.config ?? {})) {\n out[name] = readRef(env, ref)\n }\n return out as IntegrationConfig<D>\n },\n request,\n get: (path, req) => request(\"GET\", path, req),\n post: (path, req) => request(\"POST\", path, req),\n put: (path, req) => request(\"PUT\", path, req),\n patch: (path, req) => request(\"PATCH\", path, req),\n delete: (path, req) => request(\"DELETE\", path, req),\n }\n}\n","/**\n * Base64 for the `Authorization: Basic` header. `Buffer` on Node, which is\n * where an integration call runs (a route handler, a server action, a backend\n * job); `btoa` as the edge fallback, which is Latin-1 only — a credential with\n * characters outside that range needs the node runtime.\n */\nexport function toBase64(text: string): string {\n if (typeof Buffer !== \"undefined\") return Buffer.from(text, \"utf8\").toString(\"base64\")\n return btoa(text)\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport type { Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n OAUTH_REFRESH_SKEW_MS,\n} from \"./constants\"\nimport { IntegrationError } from \"./errors\"\nimport type { IntegrationAuth } from \"./types\"\n\nexport type OAuth2ClientCredentials = Extract<IntegrationAuth, { kind: \"oauth2_client_credentials\" }>\n\ninterface CacheEntry {\n accessToken?: string\n expiresAt: number\n inFlight?: Promise<string>\n}\n\n/** When `expires_in` is absent, assume a short-lived token rather than a permanent one. */\nconst DEFAULT_EXPIRES_IN_S = 300\n\n/**\n * One cache per process, keyed on what makes a token distinct. Two aliases\n * pointing at the same token endpoint with the same client share one token,\n * which is what the issuer would hand out anyway.\n */\nconst cache = new Map<string, CacheEntry>()\n\n/** Test-only: forget every cached token. Not exported from the public barrels. */\nexport function __resetIntegrationTokenCache(): void {\n cache.clear()\n}\n\nfunction required(env: Env, alias: string, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n}\n\nfunction optional(env: Env, key: string | undefined): string | undefined {\n if (!key) return undefined\n const value = env[key]\n return value === \"\" ? undefined : value\n}\n\n/**\n * A bearer token for an OAuth2 client-credentials integration: cached until\n * shortly before it expires, fetched once when several calls race for it.\n * The token request gets its own span (`→ <alias> token`) so a slow or\n * refusing issuer shows up as itself, not as a slow API call.\n */\nexport async function getClientCredentialsToken(\n alias: string,\n auth: OAuth2ClientCredentials,\n env: Env,\n timeoutMs: number,\n): Promise<string> {\n const tokenUrl = required(env, alias, auth.tokenUrl)\n const clientId = required(env, alias, auth.clientId)\n const clientSecret = required(env, alias, auth.clientSecret)\n const scope = optional(env, auth.scope)\n const audience = optional(env, auth.audience)\n\n const key = `${tokenUrl}|${clientId}|${scope ?? \"\"}|${audience ?? \"\"}`\n const entry = cache.get(key)\n if (entry?.accessToken && entry.expiresAt - OAUTH_REFRESH_SKEW_MS > Date.now()) {\n return entry.accessToken\n }\n if (entry?.inFlight) return entry.inFlight\n\n const inFlight = fetchToken(alias, {\n tokenUrl,\n clientId,\n clientSecret,\n scope,\n audience,\n credentialsIn: auth.credentialsIn ?? \"header\",\n timeoutMs,\n })\n .then((token) => {\n cache.set(key, { accessToken: token.accessToken, expiresAt: token.expiresAt })\n return token.accessToken\n })\n .catch((err: unknown) => {\n // Keep whatever was cached (possibly still usable within the skew), drop the in-flight marker.\n const current = cache.get(key)\n if (current?.inFlight === inFlight) {\n if (current.accessToken) cache.set(key, { accessToken: current.accessToken, expiresAt: current.expiresAt })\n else cache.delete(key)\n }\n throw err\n })\n cache.set(key, { ...(entry ?? { expiresAt: 0 }), inFlight })\n return inFlight\n}\n\ninterface TokenRequest {\n tokenUrl: string\n clientId: string\n clientSecret: string\n scope?: string\n audience?: string\n credentialsIn: \"header\" | \"body\"\n timeoutMs: number\n}\n\nasync function fetchToken(\n alias: string,\n req: TokenRequest,\n): Promise<{ accessToken: string; expiresAt: number }> {\n const form = new URLSearchParams({ grant_type: \"client_credentials\" })\n if (req.scope) form.set(\"scope\", req.scope)\n if (req.audience) form.set(\"audience\", req.audience)\n const headers = new Headers({\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n })\n if (req.credentialsIn === \"body\") {\n form.set(\"client_id\", req.clientId)\n form.set(\"client_secret\", req.clientSecret)\n } else {\n headers.set(\"authorization\", `Basic ${toBase64(`${req.clientId}:${req.clientSecret}`)}`)\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), req.timeoutMs)\n\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n return tracer.startActiveSpan(\n `→ ${alias} token`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"http.request.method\": \"POST\",\n },\n },\n async (span) => {\n try {\n const res = await fetch(req.tokenUrl, {\n method: \"POST\",\n headers,\n body: form.toString(),\n signal: controller.signal,\n })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (!res.ok) {\n // Status only. The issuer's body can echo the request, credentials included.\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token request for \"${alias}\" failed with HTTP ${res.status}`,\n })\n }\n let payload: unknown\n try {\n payload = await res.json()\n } catch {\n payload = undefined\n }\n const body = (payload ?? {}) as { access_token?: unknown; expires_in?: unknown }\n if (typeof body.access_token !== \"string\" || body.access_token === \"\") {\n span.setStatus({ code: SpanStatusCode.ERROR, message: \"no access_token\" })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token response for \"${alias}\" carried no access_token`,\n })\n }\n const expiresIn = Number(body.expires_in)\n const seconds = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEFAULT_EXPIRES_IN_S\n return { accessToken: body.access_token, expiresAt: Date.now() + seconds * 1000 }\n } catch (err) {\n if (!(err instanceof IntegrationError)) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;AACO,IAAM,iCAAiC;AAGvC,IAAM,wBAAwB;AAG9B,IAAM,yBAAyB;AAG/B,IAAM,6BAA6B;AAGnC,IAAM,wBAAwB;;;ACC9B,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACA;AAAA,EAET,YAAY,MAA4B,MAA8C;AACpF,UAAM,MAAM,WAAW,IAAI;AAC3B,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS,MAAM,UAAU;AAAA,EAChC;AACF;;;ACxBA,SAAS,kBAAAA,iBAAgB,SAAAC,cAAa;;;ACM/B,SAAS,SAAS,MAAsB;AAC7C,MAAI,OAAO,WAAW,YAAa,QAAO,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,QAAQ;AACrF,SAAO,KAAK,IAAI;AAClB;;;ACTA,SAAS,gBAAgB,aAAa;AAqBtC,IAAM,uBAAuB;AAO7B,IAAM,QAAQ,oBAAI,IAAwB;AAO1C,SAAS,SAAS,KAAU,OAAe,KAAqB;AAC9D,QAAM,QAAQ,IAAI,GAAG;AACrB,MAAI,UAAU,UAAa,UAAU,IAAI;AACvC,UAAM,IAAI,iBAAiB,eAAe;AAAA,MACxC,SAAS,gBAAgB,KAAK,gBAAgB,GAAG;AAAA,IACnD,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,SAAS,SAAS,KAAU,KAA6C;AACvE,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,QAAQ,IAAI,GAAG;AACrB,SAAO,UAAU,KA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