@steadphast/connector-nextjs 0.5.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -7
- package/dist/config.d.ts +16 -0
- package/dist/index.js +444 -127
- package/dist/server.d.ts +14 -0
- package/dist/server.js +293 -0
- package/package.json +20 -9
package/README.md
CHANGED
|
@@ -31,10 +31,9 @@ authoritative terms.
|
|
|
31
31
|
|
|
32
32
|
## Requirements
|
|
33
33
|
|
|
34
|
-
- Next.js 15
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
work. Next.js 14 and earlier are not supported.
|
|
34
|
+
- Next.js 15 or 16 (`^15.0.0 || ^16.0.0`) and React 19 (`^19.0.0`) are peer dependencies.
|
|
35
|
+
Tested with Next.js 15.5.23 (`middleware.ts`) and 16.3.2 (`proxy.ts`); other releases on
|
|
36
|
+
those two Next.js lines are expected to work. Next.js 14 and earlier are not supported.
|
|
38
37
|
- A Steadphast API key, created in the dashboard under **Settings → API keys** with **Used with**
|
|
39
38
|
set to the mode you deploy: **Next.js on Vercel** or **Next.js self-hosted**. A key is issued for
|
|
40
39
|
one deployment mode and is rejected by the other.
|
|
@@ -423,7 +422,11 @@ and redirects are rejected, so your API key is never sent over plaintext or to a
|
|
|
423
422
|
## What is captured
|
|
424
423
|
|
|
425
424
|
Each captured request produces one strict JSON record containing the deployment mode, capture
|
|
426
|
-
timestamp, your `recordIdPrefix`, request metadata
|
|
425
|
+
timestamp, your `recordIdPrefix`, request metadata and platform metadata. With `collector: true`,
|
|
426
|
+
an eligible forwarded document navigation appends `collector_served: true` and `served_at`
|
|
427
|
+
(Unix milliseconds). These fields report the connector's serving intent, not proof that the
|
|
428
|
+
component rendered or the script executed. Every other envelope, including collector-off
|
|
429
|
+
installations, ends at `platform` as in 0.5.x.
|
|
427
430
|
|
|
428
431
|
- **Request:** method, URL, and headers. The connector reads nothing else. It never reads, clones,
|
|
429
432
|
buffers, or transmits the request body, so every downstream body consumer in your application
|
|
@@ -459,14 +462,26 @@ The built-in filter is a **limited, fixed set**, not a general secret detector.
|
|
|
459
462
|
case-insensitively with separators removed (`x-api-key`, `X_Api_Key`, and `xapikey` are the same
|
|
460
463
|
name). The exact set is:
|
|
461
464
|
|
|
462
|
-
- `authorization`, `x-authorization`, and `
|
|
465
|
+
- `authorization`, `x-authorization`, `proxy-authorization`, and `payment-authorization` (but not
|
|
466
|
+
`x-proxy-authorization`);
|
|
463
467
|
- `api-key`, `api-token`, `auth-key`, `access-key`, `secret-key`, `auth-token`, `access-token`,
|
|
464
468
|
`bearer-token`, `refresh-token`, `id-token`, `session-token`, and `csrf-token`, each with or
|
|
465
469
|
without an `x-` prefix;
|
|
466
470
|
- the bare names `token` and `key` (but not `x-token` or `x-key`);
|
|
467
471
|
- any name ending in `apikey`, `authtoken`, or `accesstoken`, and any name containing `cryptogram`
|
|
468
472
|
or `networktoken`;
|
|
469
|
-
- `agentic-payment-container` and Vercel's `x-vercel-protection-bypass
|
|
473
|
+
- `agentic-payment-container` and Vercel's `x-vercel-protection-bypass`, `x-vercel-oidc-token`, and
|
|
474
|
+
`x-vercel-proxy-signature`;
|
|
475
|
+
|
|
476
|
+
A `Payment-Authorization` header is the payment credential of the Machine Payments Protocol (MPP).
|
|
477
|
+
Its value is never sent. In its place the captured map carries
|
|
478
|
+
`x-steadphast-payment-credential: payment-authorization`, which records only that a credential was
|
|
479
|
+
presented. It is not evidence that a payment succeeded or that a person authorized one. The
|
|
480
|
+
connector removes any `x-steadphast-payment-credential` header the visitor sends, so only the
|
|
481
|
+
connector sets it. List it in `excludedHeaders` to suppress the marker.
|
|
482
|
+
|
|
483
|
+
Vercel's visitor location headers (`x-vercel-ip-country`, `-country-region`, `-city`, `-latitude`,
|
|
484
|
+
`-longitude`, `-postal-code`) are captured; add them to `excludedHeaders` to keep them out.
|
|
470
485
|
|
|
471
486
|
Every other header is captured, including custom credential headers such as `x-token`,
|
|
472
487
|
`x-github-token`, `x-openai-key`, `x-internal-secret`, or `x-<vendor>-signature`. Audit the
|
|
@@ -497,6 +512,116 @@ Delivery does not block the visitor response: the connector serializes the recor
|
|
|
497
512
|
changes the response status, headers, or body, and never propagates an error into your composed
|
|
498
513
|
handler.
|
|
499
514
|
|
|
515
|
+
## Optional: the T0 client collector
|
|
516
|
+
|
|
517
|
+
Unreleased version 0.6.0 adds the **T0 client collector**: a small clean-room script, inlined into
|
|
518
|
+
document HTML, that observes browser realms and posts one beacon to `POST /v1/client/t0`.
|
|
519
|
+
The server joins the beacon to its event by the envelope's `record_id_prefix:request_id` identity
|
|
520
|
+
and records `client_environment`; the six client-side flags are derived from that evidence.
|
|
521
|
+
|
|
522
|
+
It is **off by default**, including when the server component is mounted without configuration.
|
|
523
|
+
Every request has inbound `x-steadphast-collector-*` headers removed, even while collection is off.
|
|
524
|
+
Before enabling any tenant, ship the privacy statement line and customer install/notice guidance,
|
|
525
|
+
resolve applicable consent requirements with counsel, and obtain that tenant's explicit opt-in.
|
|
526
|
+
Merging or installing the package does not enable collection.
|
|
527
|
+
|
|
528
|
+
Keep one server-only configuration and pass it to both entry points:
|
|
529
|
+
|
|
530
|
+
```ts
|
|
531
|
+
// discover-config.ts: never import this module into a Client Component.
|
|
532
|
+
import type { DiscoverNextConfig } from "@steadphast/connector-nextjs";
|
|
533
|
+
|
|
534
|
+
export const discoverConfig = {
|
|
535
|
+
kind: "vercel",
|
|
536
|
+
apiUrl: "https://api.steadphast.ai/v1/connectors/nextjs/events",
|
|
537
|
+
excludedHeaders: ["cookie"],
|
|
538
|
+
recordIdPrefix: "vercel-production",
|
|
539
|
+
collector: false, // Set true only after the tenant's activation prerequisites are complete.
|
|
540
|
+
} satisfies DiscoverNextConfig;
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
```ts
|
|
544
|
+
// middleware.ts (15.5) or proxy.ts (16.3)
|
|
545
|
+
import { withDiscover } from "@steadphast/connector-nextjs";
|
|
546
|
+
import { discoverConfig } from "./discover-config";
|
|
547
|
+
|
|
548
|
+
export default withDiscover(discoverConfig);
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
```tsx
|
|
552
|
+
// app/layout.tsx
|
|
553
|
+
import { DiscoverCollector } from "@steadphast/connector-nextjs/server";
|
|
554
|
+
import { discoverConfig } from "../discover-config";
|
|
555
|
+
|
|
556
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
557
|
+
return (
|
|
558
|
+
<html lang="en">
|
|
559
|
+
<body>
|
|
560
|
+
{children}
|
|
561
|
+
<DiscoverCollector config={discoverConfig} />
|
|
562
|
+
</body>
|
|
563
|
+
</html>
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
What the wrapper does with `collector: true`, on a **document navigation** only (a `GET` whose
|
|
569
|
+
`Sec-Fetch-Dest` is `document`, or, when that header is absent, whose `Accept` names `text/html`):
|
|
570
|
+
|
|
571
|
+
- authenticates a render context bound to `record_id_prefix:request_id` and the current
|
|
572
|
+
millisecond with the server's connector API key;
|
|
573
|
+
- forwards only `x-steadphast-collector-context`, after stripping every inbound header in that
|
|
574
|
+
namespace; this domain-separated context is not a browser beacon nonce;
|
|
575
|
+
- appends `collector_served: true` and `served_at` to the envelope. The server holds later
|
|
576
|
+
requests only after a valid beacon has confirmed installation; a late first beacon can confirm it.
|
|
577
|
+
|
|
578
|
+
The wrapper does not read or rewrite the response body. It forwards the authenticated context with
|
|
579
|
+
`NextResponse.next({ request: { headers } })`, including composed next/rewrite responses.
|
|
580
|
+
`DiscoverCollector` separately requires `config.collector === true`, resolves the endpoint only
|
|
581
|
+
from that server configuration, validates the context and mints the browser nonce through the
|
|
582
|
+
server-side HMAC path. Missing configuration, missing context and forged context render nothing.
|
|
583
|
+
Visitor endpoint, nonce and enablement headers are never trusted. The component needs the App
|
|
584
|
+
Router (`next/headers`); the Pages Router is not supported. `react` ^19 is a peer for `./server`.
|
|
585
|
+
|
|
586
|
+
The collector observes the main window, a Blob worker, and a sandboxed `srcdoc` iframe, and reports
|
|
587
|
+
realm cross-checks (a spoofed `navigator` that disagrees across realms), native-function integrity,
|
|
588
|
+
headless and automation markers, a coarse screen/WebGL/feature profile, and interaction *counts*
|
|
589
|
+
(untrusted clicks, whether any trusted input happened). It registers no listener that reads what
|
|
590
|
+
was typed, and it never touches form contents, pointer coordinates, the clipboard, storage,
|
|
591
|
+
cookies, extension URLs, WebRTC, or any persistent identifier. Its one keepalive `text/plain`
|
|
592
|
+
POST explicitly uses `credentials: "omit"`, with a UTF-8 body capped at 2000 bytes. It sends at
|
|
593
|
+
`DOMContentLoaded` plus a short realm grace, on early exit/backgrounding, or at the 1500 ms cap,
|
|
594
|
+
then removes its listeners, worker, Blob URL and iframe. The bundle is gated below 8 KB gzipped.
|
|
595
|
+
|
|
596
|
+
Availability is factual: `available`, `unsupported-api`, `script-failure`, `background-tab`,
|
|
597
|
+
`early-exit` or `insufficient-observation`. Missing realms are not disagreements; discarded fields
|
|
598
|
+
cannot leave stale cross-realm findings. Availability alone changes no classification verdict.
|
|
599
|
+
|
|
600
|
+
**Content-Security-Policy.** Supply an independently server-generated application CSP nonce as
|
|
601
|
+
`<DiscoverCollector config={discoverConfig} nonce={cspNonce} />`; never read it from an unsanitized
|
|
602
|
+
visitor header. The browser beacon still receives its separate HMAC nonce. The iframe uses that
|
|
603
|
+
script nonce under its own restrictive policy and observes whether a nonce-less probe executes
|
|
604
|
+
there, not whether the customer's page happens to permit inline scripts. Under a strict parent
|
|
605
|
+
policy, allow the intended Blob worker and frame or expect incomplete availability. No policy is
|
|
606
|
+
weakened automatically; unsupported or failed observation is not automation evidence.
|
|
607
|
+
|
|
608
|
+
## Repository verification
|
|
609
|
+
|
|
610
|
+
From a repository checkout:
|
|
611
|
+
|
|
612
|
+
```sh
|
|
613
|
+
nix develop -c pnpm -C ts --filter @steadphast/connector-nextjs test
|
|
614
|
+
nix develop -c pnpm -C ts --filter @steadphast/connector-nextjs build
|
|
615
|
+
nix develop -c pnpm -C ts deadcode
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
The build has two public entries and two repository-only loopback fixture entries. Knip tracks
|
|
619
|
+
the build entrypoints explicitly because the Next.js fixtures import their compiled paths;
|
|
620
|
+
the private entries remain excluded from package exports and published files. The hosted
|
|
621
|
+
`nextjs-connector-checks` gate exercises both supported runtimes through nginx and the live API.
|
|
622
|
+
The durable replay test waits for the first committed value and then for every replay job to
|
|
623
|
+
settle; asynchronous acceptance does not promise FIFO completion.
|
|
624
|
+
|
|
500
625
|
## Troubleshooting
|
|
501
626
|
|
|
502
627
|
- **No events appear:** switch the Explore traffic filter to all traffic first, because the default
|
|
@@ -528,6 +653,10 @@ handler.
|
|
|
528
653
|
|
|
529
654
|
## Upgrading
|
|
530
655
|
|
|
656
|
+
- **0.6.0** (unreleased) adds the opt-in T0 client collector. It also stops sending the
|
|
657
|
+
`Payment-Authorization` credential and sends the `x-steadphast-payment-credential` presence
|
|
658
|
+
marker in its place. Upgrade the connector and the Steadphast API together: the API rejects an
|
|
659
|
+
older envelope that still carries `Payment-Authorization`.
|
|
531
660
|
- **0.5.4** Documentation only: this README now carries the reference nginx configuration and the
|
|
532
661
|
coding-agent setup prompts; no runtime change.
|
|
533
662
|
- **0.5.3** Documentation and metadata only; no runtime change.
|
package/dist/config.d.ts
CHANGED
|
@@ -21,6 +21,14 @@ export interface DiscoverNextCommonConfig {
|
|
|
21
21
|
excludedHeaders?: ReadonlyArray<string>;
|
|
22
22
|
recordIdPrefix?: string;
|
|
23
23
|
timeoutMs?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Serve the T0 client collector (ADR 0037). Off by default. Both middleware and the server
|
|
26
|
+
* component must receive this server-owned configuration with collector explicitly enabled.
|
|
27
|
+
* The middleware authenticates a render context for captured document navigations; the server
|
|
28
|
+
* component verifies it and mints the beacon nonce. Neither nonce nor destination is accepted
|
|
29
|
+
* from visitor headers. Disabled requests have no collector output or envelope keys.
|
|
30
|
+
*/
|
|
31
|
+
collector?: boolean;
|
|
24
32
|
}
|
|
25
33
|
/** The connector configuration: the explicit deployment mode plus the common transport settings. */
|
|
26
34
|
export type DiscoverNextConfig = DiscoverDeploymentMode & DiscoverNextCommonConfig;
|
|
@@ -37,6 +45,12 @@ export declare const SELF_HOSTED_CONNECTOR_ASSERTION: DiscoverConnectorAssertion
|
|
|
37
45
|
* `CanonicalEvent`, and it must never be admitted as one.
|
|
38
46
|
*/
|
|
39
47
|
export declare const ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
|
|
48
|
+
/** The unauthenticated, CORS-simple T0 beacon route the collector posts to (ADR 0037 decision 5). */
|
|
49
|
+
export declare const BEACON_PATHNAME = "/v1/client/t0";
|
|
50
|
+
/** Reserved namespace: every inbound member is stripped before capture or delegation. */
|
|
51
|
+
export declare const COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
|
|
52
|
+
/** Authenticated middleware-to-render context, domain-separated from browser beacon nonces. */
|
|
53
|
+
export declare const COLLECTOR_CONTEXT_HEADER = "x-steadphast-collector-context";
|
|
40
54
|
export declare class DiscoverConfigError extends TypeError {
|
|
41
55
|
readonly name = "DiscoverConfigError";
|
|
42
56
|
}
|
|
@@ -63,3 +77,5 @@ export declare function parseStrictUrl(value: string, setting: string): URL;
|
|
|
63
77
|
export declare function connectorAssertionFor(mode: DiscoverDeploymentMode): DiscoverConnectorAssertion;
|
|
64
78
|
/** Validates the discriminated mode and returns the resolved `publicOrigin` for self-hosted. */
|
|
65
79
|
export declare function resolveDeploymentMode(mode: DiscoverDeploymentMode): DiscoverDeploymentMode;
|
|
80
|
+
/** Resolves only server-owned environment settings, never request metadata. */
|
|
81
|
+
export declare function resolveApiKey(customEnvVar: string | undefined): string | undefined;
|
package/dist/index.js
CHANGED
|
@@ -1,114 +1,3 @@
|
|
|
1
|
-
// src/config.ts
|
|
2
|
-
var SELF_HOSTED_CLIENT_IP_HEADER = "x-steadphast-client-ip";
|
|
3
|
-
var SELF_HOSTED_REQUEST_ID_HEADER = "x-steadphast-request-id";
|
|
4
|
-
var MAX_SELF_HOSTED_CLIENT_IP_LENGTH = 45;
|
|
5
|
-
var VERCEL_CONNECTOR_ASSERTION = "vercel-routing-middleware";
|
|
6
|
-
var SELF_HOSTED_CONNECTOR_ASSERTION = "nextjs-self-hosted";
|
|
7
|
-
var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
|
|
8
|
-
var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
|
|
9
|
-
var DiscoverConfigError = class extends TypeError {
|
|
10
|
-
name = "DiscoverConfigError";
|
|
11
|
-
};
|
|
12
|
-
function validateApiKeyEnvVar(apiKeyEnvVar) {
|
|
13
|
-
if (apiKeyEnvVar?.startsWith("NEXT_PUBLIC_")) {
|
|
14
|
-
throw new DiscoverConfigError(
|
|
15
|
-
"Steadphast connector apiKeyEnvVar must reference a server-only environment variable."
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function resolveProductionIngestUrl(apiUrl) {
|
|
20
|
-
const url = parseStrictUrl(apiUrl, "apiUrl");
|
|
21
|
-
if (url.protocol !== "https:") {
|
|
22
|
-
throw new DiscoverConfigError(
|
|
23
|
-
"Steadphast connector apiUrl must use the https scheme."
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
if (url.pathname === LEGACY_CANONICAL_INGEST_PATHNAME) {
|
|
27
|
-
throw new DiscoverConfigError(
|
|
28
|
-
`Steadphast connector apiUrl must not target the canonical-event ingest route; use the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
29
|
-
);
|
|
30
|
-
}
|
|
31
|
-
if (url.pathname !== "/" && url.pathname !== ENVELOPE_INGEST_PATHNAME) {
|
|
32
|
-
throw new DiscoverConfigError(
|
|
33
|
-
`Steadphast connector apiUrl must be the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
return `${url.origin}${ENVELOPE_INGEST_PATHNAME}`;
|
|
37
|
-
}
|
|
38
|
-
function resolvePublicOrigin(publicOrigin) {
|
|
39
|
-
const url = parseStrictUrl(publicOrigin, "publicOrigin");
|
|
40
|
-
if (url.protocol !== "https:") {
|
|
41
|
-
throw new DiscoverConfigError(
|
|
42
|
-
"Steadphast connector publicOrigin must use the https scheme."
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
if (url.pathname !== "/") {
|
|
46
|
-
throw new DiscoverConfigError(
|
|
47
|
-
"Steadphast connector publicOrigin must be an origin without a path."
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
return url.origin;
|
|
51
|
-
}
|
|
52
|
-
function parseStrictUrl(value, setting) {
|
|
53
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
54
|
-
throw new DiscoverConfigError(
|
|
55
|
-
`Steadphast connector ${setting} must be a non-empty absolute URL string.`
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
if (value.includes("?") || value.includes("#")) {
|
|
59
|
-
throw new DiscoverConfigError(
|
|
60
|
-
`Steadphast connector ${setting} must not contain a query or fragment.`
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
if (value.includes("@")) {
|
|
64
|
-
throw new DiscoverConfigError(
|
|
65
|
-
`Steadphast connector ${setting} must not contain userinfo.`
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
let url;
|
|
69
|
-
try {
|
|
70
|
-
url = new URL(value);
|
|
71
|
-
} catch {
|
|
72
|
-
throw new DiscoverConfigError(
|
|
73
|
-
`Steadphast connector ${setting} must be an absolute URL.`
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
if (url.hostname.length === 0) {
|
|
77
|
-
throw new DiscoverConfigError(
|
|
78
|
-
`Steadphast connector ${setting} must contain a host.`
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
if (url.username.length > 0 || url.password.length > 0) {
|
|
82
|
-
throw new DiscoverConfigError(
|
|
83
|
-
`Steadphast connector ${setting} must not contain userinfo.`
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
return url;
|
|
87
|
-
}
|
|
88
|
-
function connectorAssertionFor(mode) {
|
|
89
|
-
return mode.kind === "vercel" ? VERCEL_CONNECTOR_ASSERTION : SELF_HOSTED_CONNECTOR_ASSERTION;
|
|
90
|
-
}
|
|
91
|
-
function resolveDeploymentMode(mode) {
|
|
92
|
-
if (typeof mode !== "object" || mode === null) {
|
|
93
|
-
throw new DiscoverConfigError(
|
|
94
|
-
'Steadphast connector mode must be { kind: "vercel" } or { kind: "self-hosted", publicOrigin }.'
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
switch (mode.kind) {
|
|
98
|
-
case "vercel":
|
|
99
|
-
return { kind: "vercel" };
|
|
100
|
-
case "self-hosted":
|
|
101
|
-
return {
|
|
102
|
-
kind: "self-hosted",
|
|
103
|
-
publicOrigin: resolvePublicOrigin(mode.publicOrigin)
|
|
104
|
-
};
|
|
105
|
-
default:
|
|
106
|
-
throw new DiscoverConfigError(
|
|
107
|
-
'Steadphast connector mode.kind must be "vercel" or "self-hosted".'
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
1
|
// ../connector-core/src/assets.ts
|
|
113
2
|
var ALWAYS_TRACK_PATHS = /* @__PURE__ */ new Set(["/robots.txt", "/sitemap.xml"]);
|
|
114
3
|
var STATIC_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
@@ -182,6 +71,7 @@ var EXCLUDED_HEADER_IDENTITIES = /* @__PURE__ */ new Set([
|
|
|
182
71
|
"authorization",
|
|
183
72
|
"xauthorization",
|
|
184
73
|
"proxyauthorization",
|
|
74
|
+
"paymentauthorization",
|
|
185
75
|
"apikey",
|
|
186
76
|
"xapikey",
|
|
187
77
|
"apitoken",
|
|
@@ -208,21 +98,38 @@ var EXCLUDED_HEADER_IDENTITIES = /* @__PURE__ */ new Set([
|
|
|
208
98
|
"xcsrftoken",
|
|
209
99
|
"agenticpaymentcontainer",
|
|
210
100
|
"xvercelprotectionbypass",
|
|
101
|
+
// Vercel-minted request credentials (issue #705): project OIDC JWT and proxy signature.
|
|
102
|
+
"xverceloidctoken",
|
|
103
|
+
"xvercelproxysignature",
|
|
104
|
+
// Visitor location headers (x-vercel-ip-city, -latitude, -longitude, -postal-code, -country,
|
|
105
|
+
// -country-region) are deliberately not excluded: they are captured as evidence (issue #705).
|
|
211
106
|
"token",
|
|
212
107
|
"key"
|
|
213
108
|
]);
|
|
214
109
|
var EXCLUDED_HEADER_SUBSTRINGS = ["cryptogram", "networktoken"];
|
|
110
|
+
var PAYMENT_CREDENTIAL_MARKER_HEADER = "x-steadphast-payment-credential";
|
|
111
|
+
var PAYMENT_AUTHORIZATION_MARKER_VALUE = "payment-authorization";
|
|
215
112
|
function captureRequestHeaders(headers, options) {
|
|
216
113
|
const captured = /* @__PURE__ */ Object.create(null);
|
|
217
114
|
const additionalExclusions = new Set(
|
|
218
115
|
options?.excludedHeaders?.map((name) => name.trim().toLowerCase()) ?? []
|
|
219
116
|
);
|
|
117
|
+
let paymentCredential = false;
|
|
220
118
|
headers.forEach((value, name) => {
|
|
221
119
|
const lowerName = name.toLowerCase();
|
|
120
|
+
if (lowerName === PAYMENT_CREDENTIAL_MARKER_HEADER) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (collapseHeaderName(lowerName) === "paymentauthorization") {
|
|
124
|
+
paymentCredential = true;
|
|
125
|
+
}
|
|
222
126
|
if (!isExcludedHeader(lowerName) && !additionalExclusions.has(lowerName)) {
|
|
223
127
|
captured[lowerName] = value;
|
|
224
128
|
}
|
|
225
129
|
});
|
|
130
|
+
if (paymentCredential && !additionalExclusions.has(PAYMENT_CREDENTIAL_MARKER_HEADER)) {
|
|
131
|
+
captured[PAYMENT_CREDENTIAL_MARKER_HEADER] = PAYMENT_AUTHORIZATION_MARKER_VALUE;
|
|
132
|
+
}
|
|
226
133
|
return captured;
|
|
227
134
|
}
|
|
228
135
|
function parseForwardedChain(headerValue) {
|
|
@@ -247,8 +154,195 @@ function recordDroppedEvents(count) {
|
|
|
247
154
|
droppedEventCount += count;
|
|
248
155
|
}
|
|
249
156
|
|
|
157
|
+
// src/config.ts
|
|
158
|
+
var SELF_HOSTED_CLIENT_IP_HEADER = "x-steadphast-client-ip";
|
|
159
|
+
var SELF_HOSTED_REQUEST_ID_HEADER = "x-steadphast-request-id";
|
|
160
|
+
var MAX_SELF_HOSTED_CLIENT_IP_LENGTH = 45;
|
|
161
|
+
var VERCEL_CONNECTOR_ASSERTION = "vercel-routing-middleware";
|
|
162
|
+
var SELF_HOSTED_CONNECTOR_ASSERTION = "nextjs-self-hosted";
|
|
163
|
+
var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
|
|
164
|
+
var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
|
|
165
|
+
var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
|
|
166
|
+
var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
|
|
167
|
+
var DiscoverConfigError = class extends TypeError {
|
|
168
|
+
name = "DiscoverConfigError";
|
|
169
|
+
};
|
|
170
|
+
function validateApiKeyEnvVar(apiKeyEnvVar) {
|
|
171
|
+
if (apiKeyEnvVar?.startsWith("NEXT_PUBLIC_")) {
|
|
172
|
+
throw new DiscoverConfigError(
|
|
173
|
+
"Steadphast connector apiKeyEnvVar must reference a server-only environment variable."
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function resolveProductionIngestUrl(apiUrl) {
|
|
178
|
+
const url = parseStrictUrl(apiUrl, "apiUrl");
|
|
179
|
+
if (url.protocol !== "https:") {
|
|
180
|
+
throw new DiscoverConfigError(
|
|
181
|
+
"Steadphast connector apiUrl must use the https scheme."
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
if (url.pathname === LEGACY_CANONICAL_INGEST_PATHNAME) {
|
|
185
|
+
throw new DiscoverConfigError(
|
|
186
|
+
`Steadphast connector apiUrl must not target the canonical-event ingest route; use the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
if (url.pathname !== "/" && url.pathname !== ENVELOPE_INGEST_PATHNAME) {
|
|
190
|
+
throw new DiscoverConfigError(
|
|
191
|
+
`Steadphast connector apiUrl must be the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
return `${url.origin}${ENVELOPE_INGEST_PATHNAME}`;
|
|
195
|
+
}
|
|
196
|
+
function resolvePublicOrigin(publicOrigin) {
|
|
197
|
+
const url = parseStrictUrl(publicOrigin, "publicOrigin");
|
|
198
|
+
if (url.protocol !== "https:") {
|
|
199
|
+
throw new DiscoverConfigError(
|
|
200
|
+
"Steadphast connector publicOrigin must use the https scheme."
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (url.pathname !== "/") {
|
|
204
|
+
throw new DiscoverConfigError(
|
|
205
|
+
"Steadphast connector publicOrigin must be an origin without a path."
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
return url.origin;
|
|
209
|
+
}
|
|
210
|
+
function parseStrictUrl(value, setting) {
|
|
211
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
212
|
+
throw new DiscoverConfigError(
|
|
213
|
+
`Steadphast connector ${setting} must be a non-empty absolute URL string.`
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
if (value.includes("?") || value.includes("#")) {
|
|
217
|
+
throw new DiscoverConfigError(
|
|
218
|
+
`Steadphast connector ${setting} must not contain a query or fragment.`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
if (value.includes("@")) {
|
|
222
|
+
throw new DiscoverConfigError(
|
|
223
|
+
`Steadphast connector ${setting} must not contain userinfo.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
let url;
|
|
227
|
+
try {
|
|
228
|
+
url = new URL(value);
|
|
229
|
+
} catch {
|
|
230
|
+
throw new DiscoverConfigError(
|
|
231
|
+
`Steadphast connector ${setting} must be an absolute URL.`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
if (url.hostname.length === 0) {
|
|
235
|
+
throw new DiscoverConfigError(
|
|
236
|
+
`Steadphast connector ${setting} must contain a host.`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
if (url.username.length > 0 || url.password.length > 0) {
|
|
240
|
+
throw new DiscoverConfigError(
|
|
241
|
+
`Steadphast connector ${setting} must not contain userinfo.`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
return url;
|
|
245
|
+
}
|
|
246
|
+
function connectorAssertionFor(mode) {
|
|
247
|
+
return mode.kind === "vercel" ? VERCEL_CONNECTOR_ASSERTION : SELF_HOSTED_CONNECTOR_ASSERTION;
|
|
248
|
+
}
|
|
249
|
+
function resolveDeploymentMode(mode) {
|
|
250
|
+
if (typeof mode !== "object" || mode === null) {
|
|
251
|
+
throw new DiscoverConfigError(
|
|
252
|
+
'Steadphast connector mode must be { kind: "vercel" } or { kind: "self-hosted", publicOrigin }.'
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
switch (mode.kind) {
|
|
256
|
+
case "vercel":
|
|
257
|
+
return { kind: "vercel" };
|
|
258
|
+
case "self-hosted":
|
|
259
|
+
return {
|
|
260
|
+
kind: "self-hosted",
|
|
261
|
+
publicOrigin: resolvePublicOrigin(mode.publicOrigin)
|
|
262
|
+
};
|
|
263
|
+
default:
|
|
264
|
+
throw new DiscoverConfigError(
|
|
265
|
+
'Steadphast connector mode.kind must be "vercel" or "self-hosted".'
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function resolveApiKey(customEnvVar) {
|
|
270
|
+
const runtime = globalThis;
|
|
271
|
+
const env = runtime.process?.env;
|
|
272
|
+
return customEnvVar !== void 0 ? env?.[customEnvVar] : resolveApiEnvironmentValue(
|
|
273
|
+
env?.[STEADPHAST_API_KEY_ENV_VAR],
|
|
274
|
+
env?.[LEGACY_DISCOVER_API_KEY_ENV_VAR]
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
250
278
|
// src/middleware.ts
|
|
279
|
+
import { NextResponse as NextResponse2 } from "next/server";
|
|
280
|
+
|
|
281
|
+
// src/collector-serve.ts
|
|
251
282
|
import { NextResponse } from "next/server";
|
|
283
|
+
var NEXT_HEADER = "x-middleware-next";
|
|
284
|
+
var REWRITE_HEADER = "x-middleware-rewrite";
|
|
285
|
+
var OVERRIDE_HEADERS = "x-middleware-override-headers";
|
|
286
|
+
var OVERRIDE_PREFIX = "x-middleware-request-";
|
|
287
|
+
function isDocumentNavigation(request) {
|
|
288
|
+
if (request.method !== "GET") {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
const destination = request.headers.get("sec-fetch-dest");
|
|
292
|
+
if (destination !== null) {
|
|
293
|
+
return destination === "document";
|
|
294
|
+
}
|
|
295
|
+
return (request.headers.get("accept") ?? "").includes("text/html");
|
|
296
|
+
}
|
|
297
|
+
function stripCollectorHeaders(headers) {
|
|
298
|
+
let names;
|
|
299
|
+
for (const name of headers.keys()) {
|
|
300
|
+
if (name.startsWith(COLLECTOR_HEADER_PREFIX)) {
|
|
301
|
+
names ??= [];
|
|
302
|
+
names.push(name);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (!names) return false;
|
|
306
|
+
for (const name of names) headers.delete(name);
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
function forwardedRequestHeaders(request, context) {
|
|
310
|
+
const headers = new Headers(request.headers);
|
|
311
|
+
stripCollectorHeaders(headers);
|
|
312
|
+
if (context !== void 0) headers.set(COLLECTOR_CONTEXT_HEADER, context);
|
|
313
|
+
return headers;
|
|
314
|
+
}
|
|
315
|
+
function applyForwardedHeaders(result, forwarded) {
|
|
316
|
+
if (result === void 0 || result === null) {
|
|
317
|
+
return NextResponse.next({ request: { headers: forwarded } });
|
|
318
|
+
}
|
|
319
|
+
const headers = result.headers;
|
|
320
|
+
if (!headers.has(NEXT_HEADER) && !headers.has(REWRITE_HEADER)) {
|
|
321
|
+
return result;
|
|
322
|
+
}
|
|
323
|
+
const override = headers.get(OVERRIDE_HEADERS);
|
|
324
|
+
if (override === null) {
|
|
325
|
+
const names2 = [];
|
|
326
|
+
for (const [name, value] of forwarded) {
|
|
327
|
+
headers.set(`${OVERRIDE_PREFIX}${name}`, value);
|
|
328
|
+
names2.push(name);
|
|
329
|
+
}
|
|
330
|
+
headers.set(OVERRIDE_HEADERS, names2.join(","));
|
|
331
|
+
return result;
|
|
332
|
+
}
|
|
333
|
+
const names = override.split(",").map((name) => name.trim()).filter((name) => {
|
|
334
|
+
if (!name.toLowerCase().startsWith(COLLECTOR_HEADER_PREFIX)) return true;
|
|
335
|
+
headers.delete(`${OVERRIDE_PREFIX}${name}`);
|
|
336
|
+
return false;
|
|
337
|
+
});
|
|
338
|
+
const context = forwarded.get(COLLECTOR_CONTEXT_HEADER);
|
|
339
|
+
if (context !== null) {
|
|
340
|
+
headers.set(`${OVERRIDE_PREFIX}${COLLECTOR_CONTEXT_HEADER}`, context);
|
|
341
|
+
names.push(COLLECTOR_CONTEXT_HEADER);
|
|
342
|
+
}
|
|
343
|
+
headers.set(OVERRIDE_HEADERS, names.join(","));
|
|
344
|
+
return result;
|
|
345
|
+
}
|
|
252
346
|
|
|
253
347
|
// src/delivery.ts
|
|
254
348
|
var ACCEPTED_STATUS = 202;
|
|
@@ -335,7 +429,13 @@ var HTTP_METHOD_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
|
335
429
|
var SELF_HOSTED_REQUEST_ID_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;
|
|
336
430
|
var IPV4_PATTERN = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
|
|
337
431
|
var IPV6_CHARSET_PATTERN = /^[0-9A-Fa-f:.]+$/;
|
|
338
|
-
function
|
|
432
|
+
function finalizeEvidenceEnvelope(envelope, servedAtMs) {
|
|
433
|
+
const body = JSON.stringify(
|
|
434
|
+
servedAtMs === void 0 ? envelope : { ...envelope, collector_served: true, served_at: servedAtMs }
|
|
435
|
+
);
|
|
436
|
+
return utf8Length(body) > MAX_ENVELOPE_BYTES ? void 0 : body;
|
|
437
|
+
}
|
|
438
|
+
function prepareEvidenceEnvelope(request, options, capturedAt = /* @__PURE__ */ new Date()) {
|
|
339
439
|
const deployment = options.deployment;
|
|
340
440
|
const capturedAtIso = formatCapturedAt(capturedAt);
|
|
341
441
|
if (capturedAtIso === void 0) {
|
|
@@ -400,8 +500,10 @@ function serializeEvidenceEnvelope(request, options, capturedAt = /* @__PURE__ *
|
|
|
400
500
|
},
|
|
401
501
|
platform
|
|
402
502
|
};
|
|
403
|
-
|
|
404
|
-
|
|
503
|
+
return {
|
|
504
|
+
envelope,
|
|
505
|
+
recordId: platform.request_id === void 0 ? void 0 : `${recordIdPrefix}:${platform.request_id}`
|
|
506
|
+
};
|
|
405
507
|
}
|
|
406
508
|
function resolveExternalUrl(runtimeUrl, deployment) {
|
|
407
509
|
let url;
|
|
@@ -584,6 +686,172 @@ function utf8Length(value) {
|
|
|
584
686
|
return UTF8_ENCODER.encode(value).byteLength;
|
|
585
687
|
}
|
|
586
688
|
|
|
689
|
+
// src/nonce.ts
|
|
690
|
+
var LAYOUT_VERSION = 1;
|
|
691
|
+
var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
|
|
692
|
+
var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
|
|
693
|
+
var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
|
|
694
|
+
var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
|
|
695
|
+
var MAX_RID_BYTES = 512;
|
|
696
|
+
var MAX_KEY_ID_BYTES = 64;
|
|
697
|
+
var TAG_BYTES = 32;
|
|
698
|
+
var UTF8 = new TextEncoder();
|
|
699
|
+
function parseApiKey(apiKey) {
|
|
700
|
+
const separator = apiKey.indexOf(".");
|
|
701
|
+
if (separator <= 0 || separator === apiKey.length - 1) {
|
|
702
|
+
return void 0;
|
|
703
|
+
}
|
|
704
|
+
const keyId = apiKey.slice(0, separator);
|
|
705
|
+
const secret = apiKey.slice(separator + 1);
|
|
706
|
+
if (UTF8.encode(keyId).byteLength > MAX_KEY_ID_BYTES) {
|
|
707
|
+
return void 0;
|
|
708
|
+
}
|
|
709
|
+
return { keyId, secret };
|
|
710
|
+
}
|
|
711
|
+
function createNonceMinter(apiKey) {
|
|
712
|
+
const parsed = parseApiKey(apiKey);
|
|
713
|
+
if (parsed === void 0) {
|
|
714
|
+
return void 0;
|
|
715
|
+
}
|
|
716
|
+
const keyIdBytes = utf8(parsed.keyId);
|
|
717
|
+
let nonceKey;
|
|
718
|
+
return {
|
|
719
|
+
async mintRenderContext(rid, servedAtMs) {
|
|
720
|
+
const header = encodeHeader(rid, servedAtMs, keyIdBytes);
|
|
721
|
+
if (header === void 0) return void 0;
|
|
722
|
+
nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
|
|
723
|
+
const tag = new Uint8Array(
|
|
724
|
+
await crypto.subtle.sign(
|
|
725
|
+
"HMAC",
|
|
726
|
+
await nonceKey,
|
|
727
|
+
concat(utf8(RENDER_CONTEXT_DOMAIN), header)
|
|
728
|
+
)
|
|
729
|
+
);
|
|
730
|
+
const context = bytes(header.byteLength + TAG_BYTES);
|
|
731
|
+
context.set(header);
|
|
732
|
+
context.set(tag, header.byteLength);
|
|
733
|
+
return base64UrlNoPad(context);
|
|
734
|
+
},
|
|
735
|
+
async nonceFromRenderContext(context) {
|
|
736
|
+
if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
|
|
737
|
+
return void 0;
|
|
738
|
+
}
|
|
739
|
+
let decoded;
|
|
740
|
+
try {
|
|
741
|
+
const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
|
|
742
|
+
decoded = bytes(binary.length);
|
|
743
|
+
for (let i = 0; i < binary.length; i++)
|
|
744
|
+
decoded[i] = binary.charCodeAt(i);
|
|
745
|
+
} catch {
|
|
746
|
+
return void 0;
|
|
747
|
+
}
|
|
748
|
+
if (decoded.byteLength <= TAG_BYTES) return void 0;
|
|
749
|
+
const header = decoded.subarray(0, -TAG_BYTES);
|
|
750
|
+
nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
|
|
751
|
+
if (!await crypto.subtle.verify(
|
|
752
|
+
"HMAC",
|
|
753
|
+
await nonceKey,
|
|
754
|
+
decoded.subarray(-TAG_BYTES),
|
|
755
|
+
concat(utf8(RENDER_CONTEXT_DOMAIN), header)
|
|
756
|
+
))
|
|
757
|
+
return void 0;
|
|
758
|
+
const tag = new Uint8Array(
|
|
759
|
+
await crypto.subtle.sign("HMAC", await nonceKey, header)
|
|
760
|
+
);
|
|
761
|
+
decoded.set(tag, header.byteLength);
|
|
762
|
+
return base64UrlNoPad(decoded);
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
function encodeHeader(rid, servedAtMs, keyIdBytes) {
|
|
767
|
+
const ridBytes = utf8(rid);
|
|
768
|
+
if (ridBytes.byteLength === 0 || ridBytes.byteLength > MAX_RID_BYTES || !Number.isSafeInteger(servedAtMs) || servedAtMs < 0) {
|
|
769
|
+
return void 0;
|
|
770
|
+
}
|
|
771
|
+
const header = bytes(
|
|
772
|
+
1 + 2 + ridBytes.byteLength + 8 + 1 + keyIdBytes.byteLength
|
|
773
|
+
);
|
|
774
|
+
const view = new DataView(header.buffer);
|
|
775
|
+
let offset = 0;
|
|
776
|
+
header[offset] = LAYOUT_VERSION;
|
|
777
|
+
offset += 1;
|
|
778
|
+
view.setUint16(offset, ridBytes.byteLength);
|
|
779
|
+
offset += 2;
|
|
780
|
+
header.set(ridBytes, offset);
|
|
781
|
+
offset += ridBytes.byteLength;
|
|
782
|
+
view.setBigUint64(offset, BigInt(servedAtMs));
|
|
783
|
+
offset += 8;
|
|
784
|
+
header[offset] = keyIdBytes.byteLength;
|
|
785
|
+
offset += 1;
|
|
786
|
+
header.set(keyIdBytes, offset);
|
|
787
|
+
return header;
|
|
788
|
+
}
|
|
789
|
+
async function deriveNonceKey(parsed, keyIdBytes) {
|
|
790
|
+
const secretKey = await crypto.subtle.importKey(
|
|
791
|
+
"raw",
|
|
792
|
+
utf8(parsed.secret),
|
|
793
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
794
|
+
false,
|
|
795
|
+
["sign"]
|
|
796
|
+
);
|
|
797
|
+
const ikm = await crypto.subtle.sign(
|
|
798
|
+
"HMAC",
|
|
799
|
+
secretKey,
|
|
800
|
+
concat(utf8(API_KEY_VERIFIER_DOMAIN), keyIdBytes)
|
|
801
|
+
);
|
|
802
|
+
const hkdfKey = await crypto.subtle.importKey("raw", ikm, "HKDF", false, [
|
|
803
|
+
"deriveBits"
|
|
804
|
+
]);
|
|
805
|
+
const nonceKeyBits = await crypto.subtle.deriveBits(
|
|
806
|
+
{
|
|
807
|
+
name: "HKDF",
|
|
808
|
+
hash: "SHA-256",
|
|
809
|
+
salt: utf8(NONCE_KEY_SALT),
|
|
810
|
+
info: concat(utf8(NONCE_KEY_INFO), keyIdBytes)
|
|
811
|
+
},
|
|
812
|
+
hkdfKey,
|
|
813
|
+
TAG_BYTES * 8
|
|
814
|
+
);
|
|
815
|
+
return crypto.subtle.importKey(
|
|
816
|
+
"raw",
|
|
817
|
+
nonceKeyBits,
|
|
818
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
819
|
+
false,
|
|
820
|
+
["sign", "verify"]
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
function bytes(length) {
|
|
824
|
+
return new Uint8Array(new ArrayBuffer(length));
|
|
825
|
+
}
|
|
826
|
+
function utf8(text) {
|
|
827
|
+
return UTF8.encode(text);
|
|
828
|
+
}
|
|
829
|
+
function concat(prefix, suffix) {
|
|
830
|
+
const out = bytes(prefix.byteLength + 1 + suffix.byteLength);
|
|
831
|
+
out.set(prefix, 0);
|
|
832
|
+
out[prefix.byteLength] = 0;
|
|
833
|
+
out.set(suffix, prefix.byteLength + 1);
|
|
834
|
+
return out;
|
|
835
|
+
}
|
|
836
|
+
function base64UrlNoPad(bytes2) {
|
|
837
|
+
let binary = "";
|
|
838
|
+
for (const byte of bytes2) {
|
|
839
|
+
binary += String.fromCharCode(byte);
|
|
840
|
+
}
|
|
841
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
842
|
+
}
|
|
843
|
+
var NonceMinterCache = class {
|
|
844
|
+
#apiKey;
|
|
845
|
+
#minter;
|
|
846
|
+
for(apiKey) {
|
|
847
|
+
if (this.#apiKey !== apiKey) {
|
|
848
|
+
this.#apiKey = apiKey;
|
|
849
|
+
this.#minter = createNonceMinter(apiKey);
|
|
850
|
+
}
|
|
851
|
+
return this.#minter;
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
|
|
587
855
|
// src/middleware.ts
|
|
588
856
|
function withDiscover(config, handler) {
|
|
589
857
|
return buildMiddleware(
|
|
@@ -595,8 +863,10 @@ function withDiscover(config, handler) {
|
|
|
595
863
|
function buildMiddleware(config, ingestUrl, handler) {
|
|
596
864
|
validateApiKeyEnvVar(config.apiKeyEnvVar);
|
|
597
865
|
const settings = snapshotSettings(config, ingestUrl);
|
|
866
|
+
const minters = new NonceMinterCache();
|
|
598
867
|
let didWarnMissingApiKey = false;
|
|
599
868
|
return (request, event) => {
|
|
869
|
+
const scrubbed = stripCollectorHeaders(request.headers);
|
|
600
870
|
if (settings.captureAllPaths || !isSkippableStaticAsset(request.url)) {
|
|
601
871
|
const apiKey = resolveApiKey(settings.apiKeyEnvVar);
|
|
602
872
|
if (apiKey === void 0 || apiKey.length === 0) {
|
|
@@ -604,11 +874,26 @@ function buildMiddleware(config, ingestUrl, handler) {
|
|
|
604
874
|
console.warn(missingApiKeyDiagnostic(settings.apiKeyEnvVar));
|
|
605
875
|
didWarnMissingApiKey = true;
|
|
606
876
|
}
|
|
877
|
+
} else if (settings.collector) {
|
|
878
|
+
return captureWithCollector(
|
|
879
|
+
settings,
|
|
880
|
+
minters.for(apiKey),
|
|
881
|
+
apiKey,
|
|
882
|
+
request,
|
|
883
|
+
event,
|
|
884
|
+
handler,
|
|
885
|
+
scrubbed
|
|
886
|
+
);
|
|
607
887
|
} else {
|
|
608
888
|
capture(settings, apiKey, request, event);
|
|
609
889
|
}
|
|
610
890
|
}
|
|
611
|
-
return
|
|
891
|
+
return scrubbed ? delegateWithHeaders(
|
|
892
|
+
handler,
|
|
893
|
+
request,
|
|
894
|
+
event,
|
|
895
|
+
new Headers(request.headers)
|
|
896
|
+
) : delegate(handler, request, event);
|
|
612
897
|
};
|
|
613
898
|
}
|
|
614
899
|
function snapshotSettings(config, ingestUrl) {
|
|
@@ -616,6 +901,7 @@ function snapshotSettings(config, ingestUrl) {
|
|
|
616
901
|
return {
|
|
617
902
|
apiKeyEnvVar: config.apiKeyEnvVar,
|
|
618
903
|
captureAllPaths: config.captureAllPaths === true,
|
|
904
|
+
collector: config.collector === true,
|
|
619
905
|
connectorAssertion: connectorAssertionFor(deployment),
|
|
620
906
|
endpoint: ingestUrl,
|
|
621
907
|
envelopeOptions: {
|
|
@@ -627,7 +913,16 @@ function snapshotSettings(config, ingestUrl) {
|
|
|
627
913
|
};
|
|
628
914
|
}
|
|
629
915
|
function capture(settings, apiKey, request, event) {
|
|
630
|
-
|
|
916
|
+
ship2(
|
|
917
|
+
settings,
|
|
918
|
+
apiKey,
|
|
919
|
+
prepareEvidenceEnvelope(request, settings.envelopeOptions),
|
|
920
|
+
void 0,
|
|
921
|
+
event
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
function ship2(settings, apiKey, prepared, servedAtMs, event) {
|
|
925
|
+
const body = prepared === void 0 ? void 0 : finalizeEvidenceEnvelope(prepared.envelope, servedAtMs);
|
|
631
926
|
if (body === void 0) {
|
|
632
927
|
recordDroppedEvents(1);
|
|
633
928
|
return;
|
|
@@ -641,23 +936,45 @@ function capture(settings, apiKey, request, event) {
|
|
|
641
936
|
})
|
|
642
937
|
);
|
|
643
938
|
}
|
|
939
|
+
async function captureWithCollector(settings, minter, apiKey, request, event, handler, scrubbed) {
|
|
940
|
+
const prepared = prepareEvidenceEnvelope(request, settings.envelopeOptions);
|
|
941
|
+
const armed = prepared?.recordId !== void 0 && minter !== void 0 && isDocumentNavigation(request);
|
|
942
|
+
const servedAt = armed ? Date.now() : void 0;
|
|
943
|
+
const context = armed && prepared?.recordId !== void 0 && servedAt !== void 0 ? await minter.mintRenderContext(prepared.recordId, servedAt) : void 0;
|
|
944
|
+
if (context === void 0) {
|
|
945
|
+
ship2(settings, apiKey, prepared, void 0, event);
|
|
946
|
+
return scrubbed ? delegateWithHeaders(
|
|
947
|
+
handler,
|
|
948
|
+
request,
|
|
949
|
+
event,
|
|
950
|
+
forwardedRequestHeaders(request, void 0)
|
|
951
|
+
) : delegate(handler, request, event);
|
|
952
|
+
}
|
|
953
|
+
ship2(settings, apiKey, prepared, servedAt, event);
|
|
954
|
+
return delegateWithHeaders(
|
|
955
|
+
handler,
|
|
956
|
+
request,
|
|
957
|
+
event,
|
|
958
|
+
forwardedRequestHeaders(request, context)
|
|
959
|
+
);
|
|
960
|
+
}
|
|
644
961
|
function delegate(handler, request, event) {
|
|
645
962
|
if (handler === void 0) {
|
|
646
|
-
return
|
|
963
|
+
return NextResponse2.next();
|
|
647
964
|
}
|
|
648
965
|
return handler(request, event);
|
|
649
966
|
}
|
|
650
|
-
function
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
}
|
|
654
|
-
function resolveApiKey(customEnvVar) {
|
|
655
|
-
if (customEnvVar !== void 0) {
|
|
656
|
-
return readRuntimeEnv(customEnvVar);
|
|
967
|
+
async function delegateWithHeaders(handler, request, event, forwarded) {
|
|
968
|
+
if (handler === void 0) {
|
|
969
|
+
return NextResponse2.next({ request: { headers: forwarded } });
|
|
657
970
|
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
971
|
+
const forwardedRequest = new request.constructor(
|
|
972
|
+
request,
|
|
973
|
+
{ headers: forwarded }
|
|
974
|
+
);
|
|
975
|
+
return applyForwardedHeaders(
|
|
976
|
+
await handler(forwardedRequest, event),
|
|
977
|
+
forwarded
|
|
661
978
|
);
|
|
662
979
|
}
|
|
663
980
|
export {
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App Router collector entry. Server-owned configuration enables rendering and supplies the
|
|
3
|
+
* destination; authenticated middleware context authorizes server-side beacon nonce minting.
|
|
4
|
+
* This entry is separate so middleware never imports next/headers or React.
|
|
5
|
+
*/
|
|
6
|
+
import type { ReactElement } from "react";
|
|
7
|
+
import { type DiscoverNextConfig } from "./config.js";
|
|
8
|
+
export interface DiscoverCollectorProps {
|
|
9
|
+
/** Server-owned tenant settings shared with withDiscover. Missing settings fail closed. */
|
|
10
|
+
config?: DiscoverNextConfig;
|
|
11
|
+
/** Optional server-owned Content Security Policy nonce. Never copied from visitor headers. */
|
|
12
|
+
nonce?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function DiscoverCollector(props?: DiscoverCollectorProps): Promise<ReactElement | null>;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// src/collector-render.ts
|
|
2
|
+
import { headers } from "next/headers";
|
|
3
|
+
import { createElement } from "react";
|
|
4
|
+
|
|
5
|
+
// src/collector/bundle.ts
|
|
6
|
+
var COLLECTOR_SOURCE = `(function(G,ce){var ue=2e3,le=1500,fe=250,de=500,pe=Date.now(),me=typeof performance<"u"?performance.now():0;function J(e,n){var a=typeof globalThis<"u"?globalThis:self,o=a.navigator,i={},v=[],t=null,L=!1,_=/^function (?:get |set )?[\\w$]*\\(\\) \\{\\s*\\[native code\\]\\s*\\}$/;function u(s,c){try{return s()}catch{return c}}function w(){L||(L=!0,clearTimeout(t),n(i))}function d(s,c){if(typeof c=="function"){var l=Function.prototype.toString,p=!1,A,k,U=!1,P=!1;try{_.test(l.call(c))||(p=!0),A=Reflect.ownKeys(c),(A.length!==2||A.indexOf("length")===-1||A.indexOf("name")===-1)&&(p=!0),k=Object.getOwnPropertyDescriptor(c,"name"),(!k||k.writable!==!1)&&(p=!0);try{new c}catch(h){U=h instanceof TypeError}U||(p=!0);try{Object.setPrototypeOf(c,c)}catch{P=!0}P||(p=!0,Object.setPrototypeOf(c,Function.prototype))}catch{p=!0}p&&v.push(s)}}function Oe(s,c){var l=s?Object.getOwnPropertyDescriptor(s.prototype,c):void 0;return l?l.get:void 0}function j(s,c){return s?s.prototype[c]:void 0}i.ua=u(()=>String(o.userAgent)),i.platform=u(()=>String(o.platform)),i.languages=u(()=>Array.prototype.slice.call(o.languages,0,8).map(String)),i.tz=u(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),i.cores=u(()=>o.hardwareConcurrency),i.memory=u(()=>o.deviceMemory),i.brands=u(()=>o.userAgentData.brands.map(s=>s.brand+" "+s.version)),i.webdriver=u(()=>o.webdriver),i.webdriver_own=u(()=>Object.prototype.hasOwnProperty.call(o,"webdriver")),i.headless_ua=u(()=>/HeadlessChrome|PhantomJS|SlimerJS/.test(o.userAgent)),i.clock={date_native:u(()=>_.test(Function.prototype.toString.call(Date.now))),perf_native:u(()=>_.test(Function.prototype.toString.call(a.performance.now)))},i.webgl=u(()=>{var s=e==="worker"?new OffscreenCanvas(8,8):a.document.createElement("canvas"),c=s.getContext("webgl")||s.getContext("webgl2");if(!c)return{ctx:!1};var l=c.getExtension("WEBGL_debug_renderer_info");return{vendor:l?c.getParameter(l.UNMASKED_VENDOR_WEBGL):void 0,renderer:l?c.getParameter(l.UNMASKED_RENDERER_WEBGL):void 0,ctx:!0}},{ctx:!1});var xe=e==="worker"?a.WorkerNavigator:a.Navigator;d("Function.prototype.toString",Function.prototype.toString),d("Date.now",Date.now),d("performance.now",a.performance&&a.performance.now),["webdriver","plugins","languages","hardwareConcurrency","deviceMemory","platform","userAgent"].forEach(s=>{d((e==="worker"?"WorkerNavigator.":"Navigator.")+s+"#get",Oe(xe,s))}),e!=="worker"&&(d("WebGLRenderingContext.getParameter",j(a.WebGLRenderingContext,"getParameter")),d("Permissions.query",j(a.Permissions,"query")),d("HTMLCanvasElement.toDataURL",j(a.HTMLCanvasElement,"toDataURL")),d("CanvasRenderingContext2D.getImageData",j(a.CanvasRenderingContext2D,"getImageData"))),e!=="worker"&&(i.plugins=u(()=>o.plugins.length),i.screen=u(()=>({w:a.screen.width,h:a.screen.height,dpr:a.devicePixelRatio,outer_zero:a.outerWidth===0||a.outerHeight===0}))),e==="main"&&(i.chrome=u(()=>typeof a.chrome=="object"&&a.chrome!==null),i.rtt=u(()=>o.connection.rtt),i.pdf_viewer=u(()=>o.pdfViewerEnabled),i.share=u(()=>typeof o.share=="function"),i.feature_major=Ce(a),i.os_fonts=u(()=>De(a.document))),i.proto=v;var B=u(()=>o.userAgentData.getHighEntropyValues(["architecture","bitness","platformVersion","fullVersionList"]));return B&&typeof B.then=="function"?(t=setTimeout(w,300),B.then(s=>{i.uach={arch:s.architecture,bitness:s.bitness,platform_version:s.platformVersion,full_version_list:(s.fullVersionList||[]).map(c=>c.brand+" "+c.version)},w()},()=>{w()})):w(),()=>{L=!0,clearTimeout(t)};function Ce(s){for(var c=[[141,()=>typeof Math.sumPrecise=="function"],[140,()=>typeof Uint8Array.fromBase64=="function"],[136,()=>typeof RegExp.escape=="function"],[135,()=>typeof s.Float16Array=="function"],[134,()=>typeof Error.isError=="function"],[128,()=>typeof Promise.try=="function"],[126,()=>typeof URL.parse=="function"],[122,()=>typeof Set.prototype.union=="function"],[122,()=>typeof s.Iterator=="function"&&typeof s.Iterator.prototype.map=="function"],[121,()=>typeof Array.fromAsync=="function"],[120,()=>typeof URL.canParse=="function"],[119,()=>typeof Promise.withResolvers=="function"],[117,()=>typeof Object.groupBy=="function"],[110,()=>typeof Array.prototype.toSorted=="function"],[98,()=>typeof s.structuredClone=="function"]],l=0;l<c.length;l+=1)if(u(c[l][1],!1))return c[l][0];return 0}function De(s){var c={mac:["Helvetica Neue","Menlo","Monaco","Apple Color Emoji","SF Pro","Geneva","Avenir"],win:["Segoe UI","Calibri","Consolas","Tahoma","Cambria","Candara"],linux:["DejaVu Sans","Liberation Sans","Ubuntu","Noto Sans","Cantarell","Liberation Mono"]},l=s.createElement("canvas"),p=l.getContext("2d"),A="mmmmmmmmmmlli WAVE 0123 @#%",k=["monospace","sans-serif","serif"],U=k.map(h=>(p.font="24px "+h,p.measureText(A).width)),P={};return Object.keys(c).forEach(h=>{var se=0;c[h].forEach(Re=>{var Le=k.some((Pe,Me)=>(p.font="24px '"+Re+"', "+Pe,p.measureText(A).width!==U[Me]));Le&&(se+=1)}),P[h]=se}),P}}var r={v:1,nonce:G,t:{}},y=null,O=null,x=null,z=!1,C=!1,g=!1,H=!1,K=0,q=0,Z=0,$=!1,D=null,b=null,M=null,f=null,W=null,Y=[],Q=[],F=null,X,ee=m(()=>document.currentScript.nonce,""),te=/^[A-Za-z0-9+/_-]+={0,2}$/.test(ee)?ee:G,ve=document.scripts.length,ge=document.styleSheets.length,re=m(()=>Object.getOwnPropertyNames(window),[]);function m(e,n){try{return e()}catch{return n}}function N(e,n){Y.push(setTimeout(()=>{g||e()},n))}function S(e,n,a,o){e.addEventListener(n,a,o),Q.push([e,n,a,o])}function we(){Y.forEach(clearTimeout),Q.forEach(e=>{e[0].removeEventListener(e[1],e[2],e[3])}),F!==null&&m(()=>cancelAnimationFrame(F)),D&&D.disconnect(),W&&W(),b&&b.terminate(),M&&URL.revokeObjectURL(M),f&&f.parentNode&&f.parentNode.removeChild(f)}var he=/pptr:|__puppeteer_evaluation_script__|__pyppeteer_evaluation_script__|puppeteer-extra|playwright|__playwright_utility_world__|utility|selenium|webdriver/i,ye=/cdc_|selenium|webdriver|__nightmare|callPhantom|domAutomationController|__pw|__playwright|_phantom|__fxdriver|__driver|__lastWatirAlert|__webdriver_script|puppeteer|_Selenium_IDE_Recorder/i,V=[];function T(e){var n=m(()=>String(new Error().stack||""),"");he.test(n)&&V.indexOf(e)===-1&&V.push(e)}T("sync"),m(()=>{var e={};Object.defineProperty(e,"marker",{get:()=>(T("getter"),0)}),e.marker}),N(()=>{T("timeout")},0),m(()=>{F=requestAnimationFrame(()=>{T("raf")})}),m(()=>{var e=new Proxy({},{ownKeys:()=>(K+=1,[])});console.debug(e)}),m(()=>{D=new MutationObserver(e=>{q+=e.length}),D.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),N(()=>{D.disconnect()},de)}),S(window,"click",e=>{e.isTrusted===!1&&(Z+=1)},!0),["keydown","pointerdown","mousedown","touchstart","input"].forEach(e=>{S(window,e,n=>{n.isTrusted&&($=!0)},!0)}),W=J("main",e=>{g||(y=e,E())});var ne="("+J.toString()+")";if(typeof Worker!="function"||typeof Blob!="function"||typeof URL.createObjectURL!="function")z=!0;else try{var be="var s=Date.now()-"+Date.now()+";"+ne+'("worker",function(r){r.started=s;r.clock_delta=Date.now();postMessage(r)})';M=URL.createObjectURL(new Blob([be],{type:"text/javascript"})),b=new Worker(M),b.onmessage=e=>{if(!g){var n=e.data;n.clock_delta-=Date.now(),n.started=Math.max(0,n.started),O=n,b.terminate(),E()}},b.onerror=()=>{g||(C=!0,b.terminate(),E())}}catch{C=!0}try{f=document.createElement("iframe"),f.setAttribute("sandbox","allow-scripts"),f.style.display="none",f.setAttribute("aria-hidden","true");var _e='var b=document.createElement("script");b.text="window.__sp_t0_csp=1";document.head.appendChild(b);var bypass=window.__sp_t0_csp===1;delete window.__sp_t0_csp;b.parentNode.removeChild(b);'+ne+'("iframe",function(r){r.clock_delta=Date.now();parent.postMessage({__sp_t0:r,csp_bypass:bypass},"*")})';f.srcdoc=\`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-\`+te+\`'"><script nonce="\`+te+'">'+_e+"<\\/script>",S(window,"message",e=>{if(!(g||e.source!==f.contentWindow||!e.data||!e.data.__sp_t0)){var n=e.data.__sp_t0;n.clock_delta-=Date.now(),x=n,typeof e.data.csp_bypass=="boolean"&&(X=e.data.csp_bypass),E()}}),f.onerror=()=>{g||(C=!0,E())},(document.body||document.documentElement).appendChild(f)}catch{C=!0}function ae(){H=!0,N(R,fe),E()}document.readyState==="loading"?S(window,"DOMContentLoaded",ae):ae(),N(R,le),S(window,"pagehide",()=>R("early-exit"));function oe(){document.visibilityState==="hidden"&&R("background-tab")}S(document,"visibilitychange",oe),oe();function E(){H&&y&&O&&x&&R()}function Ae(e,n,a){var o=[];if(!e)return o;function i(t,L,_){t&&Object.keys(_).forEach(u=>{var w=_[u](e),d=_[u](t);w!=null&&d!==void 0&&d!==null&&JSON.stringify(w)!==JSON.stringify(d)&&o.push(L+u)})}var v={platform:t=>t.platform,languages:t=>t.languages,hardwareConcurrency:t=>t.cores,deviceMemory:t=>t.memory,brands:t=>t.brands};return i(n,"A7.",v),i(n,"",{"A10.vendor":t=>t.webgl&&t.webgl.vendor,"A10.renderer":t=>t.webgl&&t.webgl.renderer,"A3w.userAgent":t=>t.ua,"A29w.timeZone":t=>t.tz,"A4w.architecture":t=>t.uach&&t.uach.arch,"A4w.bitness":t=>t.uach&&t.uach.bitness,"A4w.platformVersion":t=>t.uach&&t.uach.platform_version,"A4w.fullVersionList":t=>t.uach&&t.uach.full_version_list}),i(a,"A8.",v),i(a,"",{"A8.userAgent":t=>t.ua,"A8.webdriver":t=>t.webdriver,"A8.timeZone":t=>t.tz,"A8.plugins":t=>t.plugins,"A8.dpr":t=>t.screen&&t.screen.dpr,"A8.screenW":t=>t.screen&&t.screen.w,"A8.renderer":t=>t.webgl&&t.webgl.renderer}),o}function ie(e){return!e||!y||["ua","uach","webgl"].forEach(n=>{JSON.stringify(e[n])===JSON.stringify(y[n])&&delete e[n]}),e}function I(e){if(e){var n=e.proto;return delete e.proto,n}}function Se(){var e=m(()=>{var v=Object.getOwnPropertyNames(window);return v.filter(t=>re.indexOf(t)===-1)},[]),n=m(()=>re.concat(e,Object.getOwnPropertyNames(document)).filter(v=>ye.test(v)),[]),a=I(y),o=I(O),i=I(x);r.t.exec=Math.max(0,Math.round(me)),r.t.sent=Math.max(0,Date.now()-pe),r.main=y||void 0,r.worker=ie(O)||void 0,r.iframe=ie(x)||void 0,r.proto={main:a||[],worker:o,iframe:i},r.globals={late:e.slice(0,32),automation:n.slice(0,16)},r.markers={stack:V,console_trap:K,csp_bypass:X},r.dom={mutations_500:q,sheets_added:Math.max(0,document.styleSheets.length-ge),scripts_added:Math.max(0,document.scripts.length-ve)},r.events={untrusted_clicks:Z,any_input:$}}function Ee(e){for(var n=0,a=0;a<e.length;a+=1){var o=e.charCodeAt(a);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319?(n+=4,a+=1):n+=3}return n}function ke(){function e(){return r.xrealm=Ae(r.main,r.worker,r.iframe),JSON.stringify(r)}for(var n=e(),a=[()=>{r.globals.late=r.globals.late.slice(0,8)},()=>{r.iframe&&delete r.iframe.uach},()=>{r.worker&&delete r.worker.uach},()=>{r.main&&r.main.uach&&delete r.main.uach.full_version_list},()=>{r.iframe&&delete r.iframe.webgl},()=>{r.worker&&delete r.worker.webgl},()=>{r.iframe&&delete r.iframe.ua},()=>{r.worker&&delete r.worker.ua},()=>{r.proto.main=r.proto.main.slice(0,4)},()=>{delete r.iframe},()=>{delete r.worker},()=>{r.main&&delete r.main.webgl},()=>{r.main&&delete r.main.ua},()=>{delete r.globals},()=>{delete r.main},()=>{delete r.proto}],o=0;o<a.length&&Ee(n)>ue;o+=1)a[o](),r.availability==="available"&&(r.availability="insufficient-observation"),n=e();return n}function R(e){if(!g){g=!0,r.availability=e||(document.visibilityState==="hidden"?"background-tab":z?"unsupported-api":C?"script-failure":y&&O&&x?"available":"insufficient-observation"),we(),Se();var n=ke();m(()=>{fetch(ce,{method:"POST",body:n,keepalive:!0,credentials:"omit",headers:{"content-type":"text/plain"}}).catch(()=>{})})}}})`;
|
|
7
|
+
|
|
8
|
+
// ../connector-core/src/api-environment.ts
|
|
9
|
+
var STEADPHAST_API_KEY_ENV_VAR = "STEADPHAST_API_KEY";
|
|
10
|
+
var LEGACY_DISCOVER_API_KEY_ENV_VAR = "DISCOVER_API_KEY";
|
|
11
|
+
function resolveApiEnvironmentValue(canonicalValue, legacyValue) {
|
|
12
|
+
return canonicalValue ?? legacyValue;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/config.ts
|
|
16
|
+
var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
|
|
17
|
+
var BEACON_PATHNAME = "/v1/client/t0";
|
|
18
|
+
var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
|
|
19
|
+
var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
|
|
20
|
+
var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
|
|
21
|
+
var DiscoverConfigError = class extends TypeError {
|
|
22
|
+
name = "DiscoverConfigError";
|
|
23
|
+
};
|
|
24
|
+
function validateApiKeyEnvVar(apiKeyEnvVar) {
|
|
25
|
+
if (apiKeyEnvVar?.startsWith("NEXT_PUBLIC_")) {
|
|
26
|
+
throw new DiscoverConfigError(
|
|
27
|
+
"Steadphast connector apiKeyEnvVar must reference a server-only environment variable."
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function resolveProductionIngestUrl(apiUrl) {
|
|
32
|
+
const url = parseStrictUrl(apiUrl, "apiUrl");
|
|
33
|
+
if (url.protocol !== "https:") {
|
|
34
|
+
throw new DiscoverConfigError(
|
|
35
|
+
"Steadphast connector apiUrl must use the https scheme."
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
if (url.pathname === LEGACY_CANONICAL_INGEST_PATHNAME) {
|
|
39
|
+
throw new DiscoverConfigError(
|
|
40
|
+
`Steadphast connector apiUrl must not target the canonical-event ingest route; use the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (url.pathname !== "/" && url.pathname !== ENVELOPE_INGEST_PATHNAME) {
|
|
44
|
+
throw new DiscoverConfigError(
|
|
45
|
+
`Steadphast connector apiUrl must be the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return `${url.origin}${ENVELOPE_INGEST_PATHNAME}`;
|
|
49
|
+
}
|
|
50
|
+
function parseStrictUrl(value, setting) {
|
|
51
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
52
|
+
throw new DiscoverConfigError(
|
|
53
|
+
`Steadphast connector ${setting} must be a non-empty absolute URL string.`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (value.includes("?") || value.includes("#")) {
|
|
57
|
+
throw new DiscoverConfigError(
|
|
58
|
+
`Steadphast connector ${setting} must not contain a query or fragment.`
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
if (value.includes("@")) {
|
|
62
|
+
throw new DiscoverConfigError(
|
|
63
|
+
`Steadphast connector ${setting} must not contain userinfo.`
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
let url;
|
|
67
|
+
try {
|
|
68
|
+
url = new URL(value);
|
|
69
|
+
} catch {
|
|
70
|
+
throw new DiscoverConfigError(
|
|
71
|
+
`Steadphast connector ${setting} must be an absolute URL.`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (url.hostname.length === 0) {
|
|
75
|
+
throw new DiscoverConfigError(
|
|
76
|
+
`Steadphast connector ${setting} must contain a host.`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
if (url.username.length > 0 || url.password.length > 0) {
|
|
80
|
+
throw new DiscoverConfigError(
|
|
81
|
+
`Steadphast connector ${setting} must not contain userinfo.`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return url;
|
|
85
|
+
}
|
|
86
|
+
function resolveApiKey(customEnvVar) {
|
|
87
|
+
const runtime = globalThis;
|
|
88
|
+
const env = runtime.process?.env;
|
|
89
|
+
return customEnvVar !== void 0 ? env?.[customEnvVar] : resolveApiEnvironmentValue(
|
|
90
|
+
env?.[STEADPHAST_API_KEY_ENV_VAR],
|
|
91
|
+
env?.[LEGACY_DISCOVER_API_KEY_ENV_VAR]
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/nonce.ts
|
|
96
|
+
var LAYOUT_VERSION = 1;
|
|
97
|
+
var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
|
|
98
|
+
var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
|
|
99
|
+
var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
|
|
100
|
+
var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
|
|
101
|
+
var MAX_RID_BYTES = 512;
|
|
102
|
+
var MAX_KEY_ID_BYTES = 64;
|
|
103
|
+
var TAG_BYTES = 32;
|
|
104
|
+
var UTF8 = new TextEncoder();
|
|
105
|
+
function parseApiKey(apiKey) {
|
|
106
|
+
const separator = apiKey.indexOf(".");
|
|
107
|
+
if (separator <= 0 || separator === apiKey.length - 1) {
|
|
108
|
+
return void 0;
|
|
109
|
+
}
|
|
110
|
+
const keyId = apiKey.slice(0, separator);
|
|
111
|
+
const secret = apiKey.slice(separator + 1);
|
|
112
|
+
if (UTF8.encode(keyId).byteLength > MAX_KEY_ID_BYTES) {
|
|
113
|
+
return void 0;
|
|
114
|
+
}
|
|
115
|
+
return { keyId, secret };
|
|
116
|
+
}
|
|
117
|
+
function createNonceMinter(apiKey) {
|
|
118
|
+
const parsed = parseApiKey(apiKey);
|
|
119
|
+
if (parsed === void 0) {
|
|
120
|
+
return void 0;
|
|
121
|
+
}
|
|
122
|
+
const keyIdBytes = utf8(parsed.keyId);
|
|
123
|
+
let nonceKey;
|
|
124
|
+
return {
|
|
125
|
+
async mintRenderContext(rid, servedAtMs) {
|
|
126
|
+
const header = encodeHeader(rid, servedAtMs, keyIdBytes);
|
|
127
|
+
if (header === void 0) return void 0;
|
|
128
|
+
nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
|
|
129
|
+
const tag = new Uint8Array(
|
|
130
|
+
await crypto.subtle.sign(
|
|
131
|
+
"HMAC",
|
|
132
|
+
await nonceKey,
|
|
133
|
+
concat(utf8(RENDER_CONTEXT_DOMAIN), header)
|
|
134
|
+
)
|
|
135
|
+
);
|
|
136
|
+
const context = bytes(header.byteLength + TAG_BYTES);
|
|
137
|
+
context.set(header);
|
|
138
|
+
context.set(tag, header.byteLength);
|
|
139
|
+
return base64UrlNoPad(context);
|
|
140
|
+
},
|
|
141
|
+
async nonceFromRenderContext(context) {
|
|
142
|
+
if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
|
|
143
|
+
return void 0;
|
|
144
|
+
}
|
|
145
|
+
let decoded;
|
|
146
|
+
try {
|
|
147
|
+
const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
|
|
148
|
+
decoded = bytes(binary.length);
|
|
149
|
+
for (let i = 0; i < binary.length; i++)
|
|
150
|
+
decoded[i] = binary.charCodeAt(i);
|
|
151
|
+
} catch {
|
|
152
|
+
return void 0;
|
|
153
|
+
}
|
|
154
|
+
if (decoded.byteLength <= TAG_BYTES) return void 0;
|
|
155
|
+
const header = decoded.subarray(0, -TAG_BYTES);
|
|
156
|
+
nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
|
|
157
|
+
if (!await crypto.subtle.verify(
|
|
158
|
+
"HMAC",
|
|
159
|
+
await nonceKey,
|
|
160
|
+
decoded.subarray(-TAG_BYTES),
|
|
161
|
+
concat(utf8(RENDER_CONTEXT_DOMAIN), header)
|
|
162
|
+
))
|
|
163
|
+
return void 0;
|
|
164
|
+
const tag = new Uint8Array(
|
|
165
|
+
await crypto.subtle.sign("HMAC", await nonceKey, header)
|
|
166
|
+
);
|
|
167
|
+
decoded.set(tag, header.byteLength);
|
|
168
|
+
return base64UrlNoPad(decoded);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function encodeHeader(rid, servedAtMs, keyIdBytes) {
|
|
173
|
+
const ridBytes = utf8(rid);
|
|
174
|
+
if (ridBytes.byteLength === 0 || ridBytes.byteLength > MAX_RID_BYTES || !Number.isSafeInteger(servedAtMs) || servedAtMs < 0) {
|
|
175
|
+
return void 0;
|
|
176
|
+
}
|
|
177
|
+
const header = bytes(
|
|
178
|
+
1 + 2 + ridBytes.byteLength + 8 + 1 + keyIdBytes.byteLength
|
|
179
|
+
);
|
|
180
|
+
const view = new DataView(header.buffer);
|
|
181
|
+
let offset = 0;
|
|
182
|
+
header[offset] = LAYOUT_VERSION;
|
|
183
|
+
offset += 1;
|
|
184
|
+
view.setUint16(offset, ridBytes.byteLength);
|
|
185
|
+
offset += 2;
|
|
186
|
+
header.set(ridBytes, offset);
|
|
187
|
+
offset += ridBytes.byteLength;
|
|
188
|
+
view.setBigUint64(offset, BigInt(servedAtMs));
|
|
189
|
+
offset += 8;
|
|
190
|
+
header[offset] = keyIdBytes.byteLength;
|
|
191
|
+
offset += 1;
|
|
192
|
+
header.set(keyIdBytes, offset);
|
|
193
|
+
return header;
|
|
194
|
+
}
|
|
195
|
+
async function deriveNonceKey(parsed, keyIdBytes) {
|
|
196
|
+
const secretKey = await crypto.subtle.importKey(
|
|
197
|
+
"raw",
|
|
198
|
+
utf8(parsed.secret),
|
|
199
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
200
|
+
false,
|
|
201
|
+
["sign"]
|
|
202
|
+
);
|
|
203
|
+
const ikm = await crypto.subtle.sign(
|
|
204
|
+
"HMAC",
|
|
205
|
+
secretKey,
|
|
206
|
+
concat(utf8(API_KEY_VERIFIER_DOMAIN), keyIdBytes)
|
|
207
|
+
);
|
|
208
|
+
const hkdfKey = await crypto.subtle.importKey("raw", ikm, "HKDF", false, [
|
|
209
|
+
"deriveBits"
|
|
210
|
+
]);
|
|
211
|
+
const nonceKeyBits = await crypto.subtle.deriveBits(
|
|
212
|
+
{
|
|
213
|
+
name: "HKDF",
|
|
214
|
+
hash: "SHA-256",
|
|
215
|
+
salt: utf8(NONCE_KEY_SALT),
|
|
216
|
+
info: concat(utf8(NONCE_KEY_INFO), keyIdBytes)
|
|
217
|
+
},
|
|
218
|
+
hkdfKey,
|
|
219
|
+
TAG_BYTES * 8
|
|
220
|
+
);
|
|
221
|
+
return crypto.subtle.importKey(
|
|
222
|
+
"raw",
|
|
223
|
+
nonceKeyBits,
|
|
224
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
225
|
+
false,
|
|
226
|
+
["sign", "verify"]
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
function bytes(length) {
|
|
230
|
+
return new Uint8Array(new ArrayBuffer(length));
|
|
231
|
+
}
|
|
232
|
+
function utf8(text) {
|
|
233
|
+
return UTF8.encode(text);
|
|
234
|
+
}
|
|
235
|
+
function concat(prefix, suffix) {
|
|
236
|
+
const out = bytes(prefix.byteLength + 1 + suffix.byteLength);
|
|
237
|
+
out.set(prefix, 0);
|
|
238
|
+
out[prefix.byteLength] = 0;
|
|
239
|
+
out.set(suffix, prefix.byteLength + 1);
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
function base64UrlNoPad(bytes2) {
|
|
243
|
+
let binary = "";
|
|
244
|
+
for (const byte of bytes2) {
|
|
245
|
+
binary += String.fromCharCode(byte);
|
|
246
|
+
}
|
|
247
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
248
|
+
}
|
|
249
|
+
var NonceMinterCache = class {
|
|
250
|
+
#apiKey;
|
|
251
|
+
#minter;
|
|
252
|
+
for(apiKey) {
|
|
253
|
+
if (this.#apiKey !== apiKey) {
|
|
254
|
+
this.#apiKey = apiKey;
|
|
255
|
+
this.#minter = createNonceMinter(apiKey);
|
|
256
|
+
}
|
|
257
|
+
return this.#minter;
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// src/collector-render.ts
|
|
262
|
+
var minters = new NonceMinterCache();
|
|
263
|
+
function collectorScript(nonce, endpoint) {
|
|
264
|
+
const embed = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
|
|
265
|
+
return `${COLLECTOR_SOURCE}(${embed(nonce)},${embed(endpoint)});`;
|
|
266
|
+
}
|
|
267
|
+
async function renderCollector(config, endpoint, cspNonce) {
|
|
268
|
+
if (config.collector !== true) return null;
|
|
269
|
+
validateApiKeyEnvVar(config.apiKeyEnvVar);
|
|
270
|
+
const context = (await headers()).get(COLLECTOR_CONTEXT_HEADER);
|
|
271
|
+
if (context === null) return null;
|
|
272
|
+
const apiKey = resolveApiKey(config.apiKeyEnvVar);
|
|
273
|
+
if (apiKey === void 0) return null;
|
|
274
|
+
const minter = minters.for(apiKey);
|
|
275
|
+
if (minter === void 0) return null;
|
|
276
|
+
const nonce = await minter.nonceFromRenderContext(context);
|
|
277
|
+
if (nonce === void 0) return null;
|
|
278
|
+
return createElement("script", {
|
|
279
|
+
nonce: cspNonce ?? nonce,
|
|
280
|
+
// biome-ignore lint/security/noDangerouslySetInnerHtml: package-owned collector with JSON-encoded, script-escaped arguments; no visitor nonce or destination is used.
|
|
281
|
+
dangerouslySetInnerHTML: { __html: collectorScript(nonce, endpoint) }
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/server.ts
|
|
286
|
+
async function DiscoverCollector(props = {}) {
|
|
287
|
+
if (props.config?.collector !== true) return null;
|
|
288
|
+
const endpoint = `${new URL(resolveProductionIngestUrl(props.config.apiUrl)).origin}${BEACON_PATHNAME}`;
|
|
289
|
+
return renderCollector(props.config, endpoint, props.nonce);
|
|
290
|
+
}
|
|
291
|
+
export {
|
|
292
|
+
DiscoverCollector
|
|
293
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@steadphast/connector-nextjs",
|
|
3
3
|
"description": "Next.js Middleware and Proxy connector for Steadphast: captures request metadata before it reaches your app and sends it to Steadphast for AI and bot traffic classification, without touching the response.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Steadphast",
|
|
7
7
|
"homepage": "https://steadphast.ai",
|
|
@@ -25,18 +25,21 @@
|
|
|
25
25
|
"dist/index.d.ts",
|
|
26
26
|
"dist/config.d.ts",
|
|
27
27
|
"dist/middleware.d.ts",
|
|
28
|
+
"dist/server.js",
|
|
29
|
+
"dist/server.d.ts",
|
|
28
30
|
"LICENSE",
|
|
29
31
|
"NOTICE",
|
|
30
32
|
"README.md"
|
|
31
33
|
],
|
|
32
34
|
"scripts": {
|
|
33
|
-
"build": "rm -rf dist && tsc -p tsconfig.build.json && esbuild src/index.ts src/internal-loopback.ts --bundle --format=esm --platform=neutral --target=es2022 --outdir=dist --external:next/server",
|
|
35
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && esbuild src/index.ts src/server.ts src/internal-loopback.ts src/internal-loopback-server.ts --bundle --format=esm --platform=neutral --target=es2022 --outdir=dist --external:next/server --external:next/headers --external:react",
|
|
34
36
|
"prepublishOnly": "node -e \"if(process.env.STEADPHAST_CONNECTOR_RELEASE!=='1'){console.error('refusing to publish: only the publish-connector-nextjs workflow releases this package (it sets STEADPHAST_CONNECTOR_RELEASE=1 after every gate passes).');process.exit(1)}\"",
|
|
35
37
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
36
|
-
"lint": "biome check src package.json tsconfig.json tsconfig.build.json vitest.config.ts",
|
|
38
|
+
"lint": "biome check src scripts package.json tsconfig.json tsconfig.build.json vitest.config.ts",
|
|
37
39
|
"test": "vitest run",
|
|
38
40
|
"test:coverage": "vitest run --coverage",
|
|
39
|
-
"test:perf": "vitest run --reporter=verbose --slowTestThreshold=300"
|
|
41
|
+
"test:perf": "vitest run --reporter=verbose --slowTestThreshold=300",
|
|
42
|
+
"build:collector": "node scripts/build-collector.mjs"
|
|
40
43
|
},
|
|
41
44
|
"main": "./dist/index.js",
|
|
42
45
|
"types": "./dist/index.d.ts",
|
|
@@ -45,19 +48,27 @@
|
|
|
45
48
|
"types": "./dist/index.d.ts",
|
|
46
49
|
"import": "./dist/index.js",
|
|
47
50
|
"default": "./dist/index.js"
|
|
51
|
+
},
|
|
52
|
+
"./server": {
|
|
53
|
+
"types": "./dist/server.d.ts",
|
|
54
|
+
"import": "./dist/server.js",
|
|
55
|
+
"default": "./dist/server.js"
|
|
48
56
|
}
|
|
49
57
|
},
|
|
50
58
|
"peerDependencies": {
|
|
51
|
-
"next": "^15.0.0 || ^16.0.0"
|
|
59
|
+
"next": "^15.0.0 || ^16.0.0",
|
|
60
|
+
"react": "^19.0.0"
|
|
52
61
|
},
|
|
53
62
|
"devDependencies": {
|
|
54
63
|
"@discover/connector-core": "workspace:*",
|
|
55
64
|
"@edge-runtime/vm": "5.0.0",
|
|
56
|
-
"@
|
|
57
|
-
"
|
|
58
|
-
"
|
|
65
|
+
"@types/react": "19.2.18",
|
|
66
|
+
"@types/react-dom": "19.2.4",
|
|
67
|
+
"@vitest/coverage-v8": "4.1.12",
|
|
68
|
+
"esbuild": "0.28.2",
|
|
69
|
+
"next": "15.5.28",
|
|
59
70
|
"react": "19.2.8",
|
|
60
71
|
"react-dom": "19.2.8",
|
|
61
|
-
"vitest": "4.1.
|
|
72
|
+
"vitest": "4.1.12"
|
|
62
73
|
}
|
|
63
74
|
}
|