@astrasyncai/adapter-edge 0.0.0 → 1.1.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/dist/fastly.js ADDED
@@ -0,0 +1,193 @@
1
+ // src/fastly.ts
2
+ import { evaluateEdgeRequest } from "@astrasyncai/verification-gateway/edge-core";
3
+
4
+ // src/config.ts
5
+ import {
6
+ getEdgeConfig,
7
+ DEFAULT_EDGE_CONFIG
8
+ } from "@astrasyncai/verification-gateway/edge-config";
9
+ var DEFAULT_API_BASE_URL = "https://astrasync.ai/api";
10
+ function defaultLogger(prefix) {
11
+ return (level, message, data) => {
12
+ console[level === "info" ? "log" : level](`[${prefix}] ${message}`, data ?? "");
13
+ };
14
+ }
15
+ function resolveOptions(options, env, logPrefix) {
16
+ const e = env ?? {};
17
+ return {
18
+ ...options,
19
+ apiBaseUrl: options.apiBaseUrl ?? e.ASTRASYNC_API_BASE_URL ?? DEFAULT_API_BASE_URL,
20
+ counterpartyId: options.counterpartyId ?? e.ASTRASYNC_COUNTERPARTY_ID,
21
+ counterpartyUrl: options.counterpartyUrl ?? e.ASTRASYNC_COUNTERPARTY_URL,
22
+ apiKey: options.apiKey ?? e.ASTRASYNC_API_KEY,
23
+ log: options.log ?? defaultLogger(logPrefix)
24
+ };
25
+ }
26
+ function isConfigured(resolved) {
27
+ if (resolved.counterpartyId && resolved.counterpartyUrl) return true;
28
+ resolved.log(
29
+ "error",
30
+ "counterpartyId/counterpartyUrl are not configured \u2014 passing all traffic through. Set the ASTRASYNC_COUNTERPARTY_ID / ASTRASYNC_COUNTERPARTY_URL environment variables or pass them as options."
31
+ );
32
+ return false;
33
+ }
34
+ async function loadConfig(resolved) {
35
+ try {
36
+ return await getEdgeConfig(
37
+ { apiBaseUrl: resolved.apiBaseUrl, apiKey: resolved.apiKey },
38
+ resolved.counterpartyId,
39
+ { ttlMs: resolved.configTtlMs }
40
+ );
41
+ } catch {
42
+ return resolved.fallbackConfig ?? DEFAULT_EDGE_CONFIG;
43
+ }
44
+ }
45
+
46
+ // src/web.ts
47
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
48
+ async function readBodyCapped(request, cap) {
49
+ if (request.method === "GET" || request.method === "HEAD") return { truncated: false };
50
+ const body = request.clone().body;
51
+ if (!body) return { truncated: false };
52
+ const reader = body.getReader();
53
+ const chunks = [];
54
+ let total = 0;
55
+ let truncated = false;
56
+ for (; ; ) {
57
+ const { done, value } = await reader.read();
58
+ if (done) break;
59
+ if (total + value.byteLength > cap) {
60
+ chunks.push(value.subarray(0, cap - total));
61
+ total = cap;
62
+ truncated = true;
63
+ void reader.cancel().catch(() => {
64
+ });
65
+ break;
66
+ }
67
+ chunks.push(value);
68
+ total += value.byteLength;
69
+ }
70
+ if (total === 0 && !truncated) return { truncated: false };
71
+ const joined = new Uint8Array(total);
72
+ let offset = 0;
73
+ for (const chunk of chunks) {
74
+ joined.set(chunk, offset);
75
+ offset += chunk.byteLength;
76
+ }
77
+ return { text: new TextDecoder().decode(joined), truncated };
78
+ }
79
+ async function normalizeWebRequest(request, options = {}) {
80
+ const url = new URL(request.url);
81
+ const headers = {};
82
+ request.headers.forEach((value, name) => {
83
+ headers[name] = value;
84
+ });
85
+ const body = await readBodyCapped(request, options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
86
+ const connection = options.connection ?? {};
87
+ return {
88
+ method: request.method,
89
+ uri: url.pathname,
90
+ querystring: url.search.startsWith("?") ? url.search.slice(1) : url.search,
91
+ headers,
92
+ ...body.text !== void 0 && { bodyText: body.text },
93
+ ...body.truncated && { bodyTruncated: true },
94
+ ...options.clientIp && { clientIp: options.clientIp },
95
+ ...Object.keys(connection).length > 0 && { connection }
96
+ };
97
+ }
98
+ function applyGatewayPass(headers, pass) {
99
+ const out = new Headers(headers);
100
+ for (const prefix of pass.stripHeaderPrefixes) {
101
+ const p = prefix.toLowerCase();
102
+ for (const name of [...out.keys()]) {
103
+ if (name.startsWith(p)) out.delete(name);
104
+ }
105
+ }
106
+ for (const [name, value] of Object.entries(pass.injectHeaders)) {
107
+ out.set(name, value);
108
+ }
109
+ return out;
110
+ }
111
+ function buildPassRequest(request, pass) {
112
+ if (pass.stripHeaderPrefixes.length === 0 && Object.keys(pass.injectHeaders).length === 0) {
113
+ return request;
114
+ }
115
+ return new Request(request, { headers: applyGatewayPass(request.headers, pass) });
116
+ }
117
+ function toJsonResponse(application) {
118
+ return new Response(JSON.stringify(application.bodyJson), {
119
+ status: application.status,
120
+ headers: { "content-type": "application/json", ...application.headers }
121
+ });
122
+ }
123
+
124
+ // src/fastly.ts
125
+ async function collectFastlyConnection(clientIp, geo) {
126
+ const out = {};
127
+ if (clientIp) out.ip = clientIp;
128
+ if (!geo || !clientIp) return out;
129
+ try {
130
+ const specifier = "fastly:geolocation";
131
+ const mod = await import(
132
+ /* @vite-ignore */
133
+ specifier
134
+ );
135
+ const g = mod.getGeolocationForIpAddress(clientIp);
136
+ if (g?.country_code) out.country = g.country_code;
137
+ if (g?.city) out.city = g.city;
138
+ if (g?.as_number != null) out.asn = String(g.as_number);
139
+ if (g?.as_name) out.asOrg = g.as_name;
140
+ if (g?.region) out.region = g.region;
141
+ if (g?.metro_code != null) out.metroCode = String(g.metro_code);
142
+ if (g?.utc_offset != null) out.utcOffset = String(g.utc_offset);
143
+ } catch {
144
+ }
145
+ return out;
146
+ }
147
+ function createGatewayHandler(options) {
148
+ if (!options.originBackend) {
149
+ throw new Error(
150
+ "@astrasyncai/adapter-edge/fastly: `originBackend` is required \u2014 Fastly Compute fetches must name a backend configured on the service."
151
+ );
152
+ }
153
+ const backendInit = { backend: options.originBackend };
154
+ return async function handleFetchEvent(event) {
155
+ const request = event.request;
156
+ const resolved = resolveOptions(options, void 0, "astrasync-edge/fastly");
157
+ try {
158
+ if (!isConfigured(resolved)) return fetch(request, backendInit);
159
+ const clientIp = request.headers.get("fastly-client-ip") ?? event.client?.address ?? void 0;
160
+ const config = await loadConfig(resolved);
161
+ const normalized = await normalizeWebRequest(request, {
162
+ maxBodyBytes: resolved.maxBodyBytes,
163
+ clientIp,
164
+ connection: await collectFastlyConnection(clientIp, options.geo)
165
+ });
166
+ const { application } = await evaluateEdgeRequest(
167
+ {
168
+ apiBaseUrl: resolved.apiBaseUrl,
169
+ counterpartyId: resolved.counterpartyId,
170
+ counterpartyUrl: resolved.counterpartyUrl,
171
+ budgets: resolved.budgets,
172
+ random: resolved.random,
173
+ log: resolved.log,
174
+ ...event.waitUntil && { waitUntil: (p) => event.waitUntil(p) }
175
+ },
176
+ normalized,
177
+ config,
178
+ resolved.apiKey
179
+ );
180
+ if (application.action === "respond") return toJsonResponse(application);
181
+ return fetch(buildPassRequest(request, application), backendInit);
182
+ } catch (err) {
183
+ resolved.log("error", "gateway error \u2014 passing request through", {
184
+ error: err instanceof Error ? err.message : String(err)
185
+ });
186
+ return fetch(request, backendInit);
187
+ }
188
+ };
189
+ }
190
+ export {
191
+ createGatewayHandler
192
+ };
193
+ //# sourceMappingURL=fastly.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fastly.ts","../src/config.ts","../src/web.ts"],"sourcesContent":["/**\n * AstraSync Trusted Agent Gateway — Fastly Compute (JavaScript) adapter.\n *\n * ```ts\n * import { createGatewayHandler } from '@astrasyncai/adapter-edge/fastly';\n *\n * const gateway = createGatewayHandler({\n * originBackend: 'origin', // the backend name configured on your service\n * counterpartyId: 'ASTRAE-…',\n * counterpartyUrl: 'https://example.shop',\n * apiKey: '…',\n * });\n *\n * addEventListener('fetch', (event) => event.respondWith(gateway(event)));\n * ```\n *\n * Fastly Compute requires every `fetch` to name a configured backend, so\n * `originBackend` is REQUIRED (the AstraSync API must also be reachable —\n * see the README for the api backend setup). Fastly has no ambient\n * environment map; configure via options.\n *\n * Geolocation enrichment (`fastly:geolocation`) is available behind the\n * opt-in `geo` flag: the import is dynamic, so the base build carries no\n * `fastly:*` imports and runs in any test runner.\n */\n\nimport { evaluateEdgeRequest } from '@astrasyncai/verification-gateway/edge-core';\nimport { resolveOptions, isConfigured, loadConfig } from './config';\nimport type { EdgeGatewayOptions } from './types';\nimport { normalizeWebRequest, buildPassRequest, toJsonResponse } from './web';\n\nexport type { EdgeGatewayOptions, GatewayPass } from './types';\n\nexport interface FastlyGatewayOptions extends EdgeGatewayOptions {\n /**\n * REQUIRED. The name of the backend (as configured on the Fastly\n * service) that origin-bound traffic is forwarded to — Fastly Compute\n * fetches must name a backend explicitly.\n */\n originBackend: string;\n /**\n * Opt-in geolocation enrichment via the `fastly:geolocation` runtime\n * module (country/city/ASN on the connection capture). Off by default so\n * the base build has no `fastly:*` imports.\n */\n geo?: boolean;\n}\n\n/** Structural subset of the Fastly Compute fetch event. */\nexport interface FastlyFetchEvent {\n request: Request;\n client?: { address?: string };\n waitUntil?(promise: Promise<unknown>): void;\n}\n\nexport type FastlyGatewayHandler = (event: FastlyFetchEvent) => Promise<Response>;\n\ninterface FastlyGeolocation {\n country_code?: string | null;\n city?: string | null;\n as_number?: number | null;\n as_name?: string | null;\n region?: string | null;\n metro_code?: number | null;\n utc_offset?: number | null;\n}\n\nasync function collectFastlyConnection(\n clientIp: string | undefined,\n geo: boolean | undefined\n): Promise<Record<string, string>> {\n const out: Record<string, string> = {};\n if (clientIp) out.ip = clientIp;\n if (!geo || !clientIp) return out;\n try {\n // Dynamic, variable-specifier import: only resolved inside the Fastly\n // runtime, invisible to bundlers/test runners when `geo` is off.\n const specifier = 'fastly:geolocation';\n const mod = (await import(/* @vite-ignore */ specifier)) as {\n getGeolocationForIpAddress(ip: string): FastlyGeolocation | null;\n };\n const g = mod.getGeolocationForIpAddress(clientIp);\n if (g?.country_code) out.country = g.country_code;\n if (g?.city) out.city = g.city;\n if (g?.as_number != null) out.asn = String(g.as_number);\n if (g?.as_name) out.asOrg = g.as_name;\n if (g?.region) out.region = g.region;\n if (g?.metro_code != null) out.metroCode = String(g.metro_code);\n // utc_offset is minutes-from-UTC (e.g. 600), not an IANA zone — keep the\n // raw numeric form; the shared timeZone key carries IANA zones only.\n if (g?.utc_offset != null) out.utcOffset = String(g.utc_offset);\n } catch {\n // Geolocation unavailable (non-Fastly runtime) — the partial block is fine.\n }\n return out;\n}\n\n/**\n * Create the fetch-event handler. Pass traffic is forwarded with\n * `fetch(mutatedRequest, { backend: originBackend })`; enforce-mode\n * denials short-circuit with a machine-readable JSON response. Telemetry\n * beacons are scheduled through `event.waitUntil` when available.\n */\nexport function createGatewayHandler(options: FastlyGatewayOptions): FastlyGatewayHandler {\n if (!options.originBackend) {\n throw new Error(\n '@astrasyncai/adapter-edge/fastly: `originBackend` is required — Fastly Compute ' +\n 'fetches must name a backend configured on the service.'\n );\n }\n const backendInit = { backend: options.originBackend } as RequestInit;\n\n return async function handleFetchEvent(event) {\n const request = event.request;\n const resolved = resolveOptions(options, undefined, 'astrasync-edge/fastly');\n try {\n if (!isConfigured(resolved)) return fetch(request, backendInit);\n\n const clientIp =\n request.headers.get('fastly-client-ip') ?? event.client?.address ?? undefined;\n const config = await loadConfig(resolved);\n const normalized = await normalizeWebRequest(request, {\n maxBodyBytes: resolved.maxBodyBytes,\n clientIp,\n connection: await collectFastlyConnection(clientIp, options.geo),\n });\n\n const { application } = await evaluateEdgeRequest(\n {\n apiBaseUrl: resolved.apiBaseUrl,\n counterpartyId: resolved.counterpartyId,\n counterpartyUrl: resolved.counterpartyUrl,\n budgets: resolved.budgets,\n random: resolved.random,\n log: resolved.log,\n ...(event.waitUntil && { waitUntil: (p: Promise<unknown>) => event.waitUntil!(p) }),\n },\n normalized,\n config,\n resolved.apiKey\n );\n\n if (application.action === 'respond') return toJsonResponse(application);\n return fetch(buildPassRequest(request, application), backendInit);\n } catch (err) {\n // Fail-open, unconditionally: the gateway must never take the site down.\n resolved.log('error', 'gateway error — passing request through', {\n error: err instanceof Error ? err.message : String(err),\n });\n return fetch(request, backendInit);\n }\n };\n}\n","/**\n * Option/environment resolution and dashboard EdgeConfig loading shared by\n * the platform adapters.\n */\n\nimport {\n getEdgeConfig,\n DEFAULT_EDGE_CONFIG,\n type EdgeConfig,\n} from '@astrasyncai/verification-gateway/edge-config';\nimport type { EdgeLogger } from '@astrasyncai/verification-gateway/edge-core';\nimport type { EdgeGatewayOptions } from './types';\n\nexport const DEFAULT_API_BASE_URL = 'https://astrasync.ai/api';\n\nexport interface ResolvedGatewayOptions extends EdgeGatewayOptions {\n apiBaseUrl: string;\n log: EdgeLogger;\n}\n\nexport function defaultLogger(prefix: string): EdgeLogger {\n return (level, message, data) => {\n console[level === 'info' ? 'log' : level](`[${prefix}] ${message}`, data ?? '');\n };\n}\n\n/**\n * Merge explicit options with runtime environment variables (options win)\n * and apply defaults. `env` is the platform's environment map — Cloudflare\n * passes the worker `env` binding object, Vercel passes `process.env`,\n * Fastly Compute has no ambient env map (configure via options).\n */\nexport function resolveOptions(\n options: EdgeGatewayOptions,\n env: Record<string, string | undefined> | undefined,\n logPrefix: string\n): ResolvedGatewayOptions {\n const e = env ?? {};\n return {\n ...options,\n apiBaseUrl: options.apiBaseUrl ?? e.ASTRASYNC_API_BASE_URL ?? DEFAULT_API_BASE_URL,\n counterpartyId: options.counterpartyId ?? e.ASTRASYNC_COUNTERPARTY_ID,\n counterpartyUrl: options.counterpartyUrl ?? e.ASTRASYNC_COUNTERPARTY_URL,\n apiKey: options.apiKey ?? e.ASTRASYNC_API_KEY,\n log: options.log ?? defaultLogger(logPrefix),\n };\n}\n\n/**\n * Missing identity means the gateway cannot evaluate anything — it fails\n * OPEN (all traffic passes untouched) and says why, once per request.\n */\nexport function isConfigured(\n resolved: ResolvedGatewayOptions\n): resolved is ResolvedGatewayOptions & { counterpartyId: string; counterpartyUrl: string } {\n if (resolved.counterpartyId && resolved.counterpartyUrl) return true;\n resolved.log(\n 'error',\n 'counterpartyId/counterpartyUrl are not configured — passing all traffic through. ' +\n 'Set the ASTRASYNC_COUNTERPARTY_ID / ASTRASYNC_COUNTERPARTY_URL environment variables ' +\n 'or pass them as options.'\n );\n return false;\n}\n\n/**\n * Load the effective EdgeConfig. Delegates caching/fallback/degradation to\n * the SDK (60s TTL, stale-while-revalidate, enforce→observe degradation on\n * prolonged staleness) and never throws.\n */\nexport async function loadConfig(\n resolved: ResolvedGatewayOptions & { counterpartyId: string }\n): Promise<EdgeConfig> {\n try {\n return await getEdgeConfig(\n { apiBaseUrl: resolved.apiBaseUrl, apiKey: resolved.apiKey },\n resolved.counterpartyId,\n { ttlMs: resolved.configTtlMs }\n );\n } catch {\n return resolved.fallbackConfig ?? DEFAULT_EDGE_CONFIG;\n }\n}\n","/**\n * Shared web-standard platform I/O: converts a fetch-API `Request` into\n * the edge core's `NormalizedRequest`, and applies the core's abstract\n * outcome application back onto fetch-API primitives.\n */\n\nimport type {\n NormalizedRequest,\n OutcomeApplication,\n} from '@astrasyncai/verification-gateway/edge-core';\nimport type { GatewayPass } from './types';\n\n/** Default request-body read cap for commerce-protocol detection. */\nexport const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;\n\nexport interface WebNormalizeOptions {\n /** Body read cap in bytes. Default {@link DEFAULT_MAX_BODY_BYTES}. */\n maxBodyBytes?: number;\n /** Client IP as the platform reports it. */\n clientIp?: string;\n /** Connection-layer metadata the platform collected (country, asn, …). */\n connection?: Record<string, string>;\n}\n\nasync function readBodyCapped(\n request: Request,\n cap: number\n): Promise<{ text?: string; truncated: boolean }> {\n if (request.method === 'GET' || request.method === 'HEAD') return { truncated: false };\n const body = request.clone().body;\n if (!body) return { truncated: false };\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n let truncated = false;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (total + value.byteLength > cap) {\n chunks.push(value.subarray(0, cap - total));\n total = cap;\n truncated = true;\n // Fire-and-forget: cancelling one branch of a cloned (tee'd) body can\n // only settle once the other branch is consumed — never await it.\n void reader.cancel().catch(() => {});\n break;\n }\n chunks.push(value);\n total += value.byteLength;\n }\n if (total === 0 && !truncated) return { truncated: false };\n\n const joined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { text: new TextDecoder().decode(joined), truncated };\n}\n\n/**\n * Normalize a fetch-API `Request` into the edge core's request shape.\n * Header names are already lowercased (and multi-valued headers joined\n * with `\", \"`) by the `Headers` class. The body is read from a CLONE — the\n * original request stays forwardable to the origin — and capped at\n * `maxBodyBytes` (detection sees a flagged, truncated prefix beyond it).\n */\nexport async function normalizeWebRequest(\n request: Request,\n options: WebNormalizeOptions = {}\n): Promise<NormalizedRequest> {\n const url = new URL(request.url);\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name] = value;\n });\n const body = await readBodyCapped(request, options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);\n const connection = options.connection ?? {};\n return {\n method: request.method,\n uri: url.pathname,\n querystring: url.search.startsWith('?') ? url.search.slice(1) : url.search,\n headers,\n ...(body.text !== undefined && { bodyText: body.text }),\n ...(body.truncated && { bodyTruncated: true }),\n ...(options.clientIp && { clientIp: options.clientIp }),\n ...(Object.keys(connection).length > 0 && { connection }),\n };\n}\n\n/**\n * Apply a pass application to a header set: strip every header matching\n * one of the spoofable prefixes, then set the injected trust headers.\n * Returns a NEW `Headers` instance; the input is not mutated.\n */\nexport function applyGatewayPass(headers: Headers, pass: GatewayPass): Headers {\n const out = new Headers(headers);\n for (const prefix of pass.stripHeaderPrefixes) {\n const p = prefix.toLowerCase();\n for (const name of [...out.keys()]) {\n if (name.startsWith(p)) out.delete(name);\n }\n }\n for (const [name, value] of Object.entries(pass.injectHeaders)) {\n out.set(name, value);\n }\n return out;\n}\n\n/**\n * Build the origin-bound request for a pass application: the same request\n * with spoofable headers stripped and trust headers injected.\n */\nexport function buildPassRequest(request: Request, pass: GatewayPass): Request {\n if (pass.stripHeaderPrefixes.length === 0 && Object.keys(pass.injectHeaders).length === 0) {\n return request;\n }\n return new Request(request, { headers: applyGatewayPass(request.headers, pass) });\n}\n\n/** Build the short-circuit JSON response for a respond application. */\nexport function toJsonResponse(\n application: Extract<OutcomeApplication, { action: 'respond' }>\n): Response {\n return new Response(JSON.stringify(application.bodyJson), {\n status: application.status,\n headers: { 'content-type': 'application/json', ...application.headers },\n });\n}\n"],"mappings":";AA0BA,SAAS,2BAA2B;;;ACrBpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAIA,IAAM,uBAAuB;AAO7B,SAAS,cAAc,QAA4B;AACxD,SAAO,CAAC,OAAO,SAAS,SAAS;AAC/B,YAAQ,UAAU,SAAS,QAAQ,KAAK,EAAE,IAAI,MAAM,KAAK,OAAO,IAAI,QAAQ,EAAE;AAAA,EAChF;AACF;AAQO,SAAS,eACd,SACA,KACA,WACwB;AACxB,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY,QAAQ,cAAc,EAAE,0BAA0B;AAAA,IAC9D,gBAAgB,QAAQ,kBAAkB,EAAE;AAAA,IAC5C,iBAAiB,QAAQ,mBAAmB,EAAE;AAAA,IAC9C,QAAQ,QAAQ,UAAU,EAAE;AAAA,IAC5B,KAAK,QAAQ,OAAO,cAAc,SAAS;AAAA,EAC7C;AACF;AAMO,SAAS,aACd,UAC0F;AAC1F,MAAI,SAAS,kBAAkB,SAAS,gBAAiB,QAAO;AAChE,WAAS;AAAA,IACP;AAAA,IACA;AAAA,EAGF;AACA,SAAO;AACT;AAOA,eAAsB,WACpB,UACqB;AACrB,MAAI;AACF,WAAO,MAAM;AAAA,MACX,EAAE,YAAY,SAAS,YAAY,QAAQ,SAAS,OAAO;AAAA,MAC3D,SAAS;AAAA,MACT,EAAE,OAAO,SAAS,YAAY;AAAA,IAChC;AAAA,EACF,QAAQ;AACN,WAAO,SAAS,kBAAkB;AAAA,EACpC;AACF;;;ACrEO,IAAM,yBAAyB,OAAO;AAW7C,eAAe,eACb,SACA,KACgD;AAChD,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,OAAQ,QAAO,EAAE,WAAW,MAAM;AACrF,QAAM,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S;AAAA,UACjB,KAAK,SAAS;AAAA,UACd,GAAI,MAAM,aAAa,EAAE,WAAW,CAAC,MAAwB,MAAM,UAAW,CAAC,EAAE;AAAA,QACnF;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX;AAEA,UAAI,YAAY,WAAW,UAAW,QAAO,eAAe,WAAW;AACvE,aAAO,MAAM,iBAAiB,SAAS,WAAW,GAAG,WAAW;AAAA,IAClE,SAAS,KAAK;AAEZ,eAAS,IAAI,SAAS,gDAA2C;AAAA,QAC/D,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AACD,aAAO,MAAM,SAAS,WAAW;AAAA,IACnC;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,13 @@
1
+ export { E as EdgeGatewayOptions, G as GatewayPass } from './types-7lIOikBV.js';
2
+ export { D as DEFAULT_MAX_BODY_BYTES, W as WebNormalizeOptions, a as applyGatewayPass, b as buildPassRequest, n as normalizeWebRequest, t as toJsonResponse } from './web-BjPu7biw.js';
3
+ export { Classification, EdgeDecision, EdgeLogger, EffectivePolicy, NormalizedRequest, OutcomeApplication, TierOutcome, TrafficTier } from '@astrasyncai/verification-gateway/edge-core';
4
+ import '@astrasyncai/verification-gateway/edge-config';
5
+
6
+ /**
7
+ * Option/environment resolution and dashboard EdgeConfig loading shared by
8
+ * the platform adapters.
9
+ */
10
+
11
+ declare const DEFAULT_API_BASE_URL = "https://astrasync.ai/api";
12
+
13
+ export { DEFAULT_API_BASE_URL };
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ // src/config.ts
2
+ import {
3
+ getEdgeConfig,
4
+ DEFAULT_EDGE_CONFIG
5
+ } from "@astrasyncai/verification-gateway/edge-config";
6
+ var DEFAULT_API_BASE_URL = "https://astrasync.ai/api";
7
+
8
+ // src/web.ts
9
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
10
+ async function readBodyCapped(request, cap) {
11
+ if (request.method === "GET" || request.method === "HEAD") return { truncated: false };
12
+ const body = request.clone().body;
13
+ if (!body) return { truncated: false };
14
+ const reader = body.getReader();
15
+ const chunks = [];
16
+ let total = 0;
17
+ let truncated = false;
18
+ for (; ; ) {
19
+ const { done, value } = await reader.read();
20
+ if (done) break;
21
+ if (total + value.byteLength > cap) {
22
+ chunks.push(value.subarray(0, cap - total));
23
+ total = cap;
24
+ truncated = true;
25
+ void reader.cancel().catch(() => {
26
+ });
27
+ break;
28
+ }
29
+ chunks.push(value);
30
+ total += value.byteLength;
31
+ }
32
+ if (total === 0 && !truncated) return { truncated: false };
33
+ const joined = new Uint8Array(total);
34
+ let offset = 0;
35
+ for (const chunk of chunks) {
36
+ joined.set(chunk, offset);
37
+ offset += chunk.byteLength;
38
+ }
39
+ return { text: new TextDecoder().decode(joined), truncated };
40
+ }
41
+ async function normalizeWebRequest(request, options = {}) {
42
+ const url = new URL(request.url);
43
+ const headers = {};
44
+ request.headers.forEach((value, name) => {
45
+ headers[name] = value;
46
+ });
47
+ const body = await readBodyCapped(request, options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
48
+ const connection = options.connection ?? {};
49
+ return {
50
+ method: request.method,
51
+ uri: url.pathname,
52
+ querystring: url.search.startsWith("?") ? url.search.slice(1) : url.search,
53
+ headers,
54
+ ...body.text !== void 0 && { bodyText: body.text },
55
+ ...body.truncated && { bodyTruncated: true },
56
+ ...options.clientIp && { clientIp: options.clientIp },
57
+ ...Object.keys(connection).length > 0 && { connection }
58
+ };
59
+ }
60
+ function applyGatewayPass(headers, pass) {
61
+ const out = new Headers(headers);
62
+ for (const prefix of pass.stripHeaderPrefixes) {
63
+ const p = prefix.toLowerCase();
64
+ for (const name of [...out.keys()]) {
65
+ if (name.startsWith(p)) out.delete(name);
66
+ }
67
+ }
68
+ for (const [name, value] of Object.entries(pass.injectHeaders)) {
69
+ out.set(name, value);
70
+ }
71
+ return out;
72
+ }
73
+ function buildPassRequest(request, pass) {
74
+ if (pass.stripHeaderPrefixes.length === 0 && Object.keys(pass.injectHeaders).length === 0) {
75
+ return request;
76
+ }
77
+ return new Request(request, { headers: applyGatewayPass(request.headers, pass) });
78
+ }
79
+ function toJsonResponse(application) {
80
+ return new Response(JSON.stringify(application.bodyJson), {
81
+ status: application.status,
82
+ headers: { "content-type": "application/json", ...application.headers }
83
+ });
84
+ }
85
+ export {
86
+ DEFAULT_API_BASE_URL,
87
+ DEFAULT_MAX_BODY_BYTES,
88
+ applyGatewayPass,
89
+ buildPassRequest,
90
+ normalizeWebRequest,
91
+ toJsonResponse
92
+ };
93
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config.ts","../src/web.ts"],"sourcesContent":["/**\n * Option/environment resolution and dashboard EdgeConfig loading shared by\n * the platform adapters.\n */\n\nimport {\n getEdgeConfig,\n DEFAULT_EDGE_CONFIG,\n type EdgeConfig,\n} from '@astrasyncai/verification-gateway/edge-config';\nimport type { EdgeLogger } from '@astrasyncai/verification-gateway/edge-core';\nimport type { EdgeGatewayOptions } from './types';\n\nexport const DEFAULT_API_BASE_URL = 'https://astrasync.ai/api';\n\nexport interface ResolvedGatewayOptions extends EdgeGatewayOptions {\n apiBaseUrl: string;\n log: EdgeLogger;\n}\n\nexport function defaultLogger(prefix: string): EdgeLogger {\n return (level, message, data) => {\n console[level === 'info' ? 'log' : level](`[${prefix}] ${message}`, data ?? '');\n };\n}\n\n/**\n * Merge explicit options with runtime environment variables (options win)\n * and apply defaults. `env` is the platform's environment map — Cloudflare\n * passes the worker `env` binding object, Vercel passes `process.env`,\n * Fastly Compute has no ambient env map (configure via options).\n */\nexport function resolveOptions(\n options: EdgeGatewayOptions,\n env: Record<string, string | undefined> | undefined,\n logPrefix: string\n): ResolvedGatewayOptions {\n const e = env ?? {};\n return {\n ...options,\n apiBaseUrl: options.apiBaseUrl ?? e.ASTRASYNC_API_BASE_URL ?? DEFAULT_API_BASE_URL,\n counterpartyId: options.counterpartyId ?? e.ASTRASYNC_COUNTERPARTY_ID,\n counterpartyUrl: options.counterpartyUrl ?? e.ASTRASYNC_COUNTERPARTY_URL,\n apiKey: options.apiKey ?? e.ASTRASYNC_API_KEY,\n log: options.log ?? defaultLogger(logPrefix),\n };\n}\n\n/**\n * Missing identity means the gateway cannot evaluate anything — it fails\n * OPEN (all traffic passes untouched) and says why, once per request.\n */\nexport function isConfigured(\n resolved: ResolvedGatewayOptions\n): resolved is ResolvedGatewayOptions & { counterpartyId: string; counterpartyUrl: string } {\n if (resolved.counterpartyId && resolved.counterpartyUrl) return true;\n resolved.log(\n 'error',\n 'counterpartyId/counterpartyUrl are not configured — passing all traffic through. ' +\n 'Set the ASTRASYNC_COUNTERPARTY_ID / ASTRASYNC_COUNTERPARTY_URL environment variables ' +\n 'or pass them as options.'\n );\n return false;\n}\n\n/**\n * Load the effective EdgeConfig. Delegates caching/fallback/degradation to\n * the SDK (60s TTL, stale-while-revalidate, enforce→observe degradation on\n * prolonged staleness) and never throws.\n */\nexport async function loadConfig(\n resolved: ResolvedGatewayOptions & { counterpartyId: string }\n): Promise<EdgeConfig> {\n try {\n return await getEdgeConfig(\n { apiBaseUrl: resolved.apiBaseUrl, apiKey: resolved.apiKey },\n resolved.counterpartyId,\n { ttlMs: resolved.configTtlMs }\n );\n } catch {\n return resolved.fallbackConfig ?? DEFAULT_EDGE_CONFIG;\n }\n}\n","/**\n * Shared web-standard platform I/O: converts a fetch-API `Request` into\n * the edge core's `NormalizedRequest`, and applies the core's abstract\n * outcome application back onto fetch-API primitives.\n */\n\nimport type {\n NormalizedRequest,\n OutcomeApplication,\n} from '@astrasyncai/verification-gateway/edge-core';\nimport type { GatewayPass } from './types';\n\n/** Default request-body read cap for commerce-protocol detection. */\nexport const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;\n\nexport interface WebNormalizeOptions {\n /** Body read cap in bytes. Default {@link DEFAULT_MAX_BODY_BYTES}. */\n maxBodyBytes?: number;\n /** Client IP as the platform reports it. */\n clientIp?: string;\n /** Connection-layer metadata the platform collected (country, asn, …). */\n connection?: Record<string, string>;\n}\n\nasync function readBodyCapped(\n request: Request,\n cap: number\n): Promise<{ text?: string; truncated: boolean }> {\n if (request.method === 'GET' || request.method === 'HEAD') return { truncated: false };\n const body = request.clone().body;\n if (!body) return { truncated: false };\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n let truncated = false;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (total + value.byteLength > cap) {\n chunks.push(value.subarray(0, cap - total));\n total = cap;\n truncated = true;\n // Fire-and-forget: cancelling one branch of a cloned (tee'd) body can\n // only settle once the other branch is consumed — never await it.\n void reader.cancel().catch(() => {});\n break;\n }\n chunks.push(value);\n total += value.byteLength;\n }\n if (total === 0 && !truncated) return { truncated: false };\n\n const joined = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n joined.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { text: new TextDecoder().decode(joined), truncated };\n}\n\n/**\n * Normalize a fetch-API `Request` into the edge core's request shape.\n * Header names are already lowercased (and multi-valued headers joined\n * with `\", \"`) by the `Headers` class. The body is read from a CLONE — the\n * original request stays forwardable to the origin — and capped at\n * `maxBodyBytes` (detection sees a flagged, truncated prefix beyond it).\n */\nexport async function normalizeWebRequest(\n request: Request,\n options: WebNormalizeOptions = {}\n): Promise<NormalizedRequest> {\n const url = new URL(request.url);\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name] = value;\n });\n const body = await readBodyCapped(request, options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);\n const connection = options.connection ?? {};\n return {\n method: request.method,\n uri: url.pathname,\n querystring: url.search.startsWith('?') ? url.search.slice(1) : url.search,\n headers,\n ...(body.text !== undefined && { bodyText: body.text }),\n ...(body.truncated && { bodyTruncated: true }),\n ...(options.clientIp && { clientIp: options.clientIp }),\n ...(Object.keys(connection).length > 0 && { connection }),\n };\n}\n\n/**\n * Apply a pass application to a header set: strip every header matching\n * one of the spoofable prefixes, then set the injected trust headers.\n * Returns a NEW `Headers` instance; the input is not mutated.\n */\nexport function applyGatewayPass(headers: Headers, pass: GatewayPass): Headers {\n const out = new Headers(headers);\n for (const prefix of pass.stripHeaderPrefixes) {\n const p = prefix.toLowerCase();\n for (const name of [...out.keys()]) {\n if (name.startsWith(p)) out.delete(name);\n }\n }\n for (const [name, value] of Object.entries(pass.injectHeaders)) {\n out.set(name, value);\n }\n return out;\n}\n\n/**\n * Build the origin-bound request for a pass application: the same request\n * with spoofable headers stripped and trust headers injected.\n */\nexport function buildPassRequest(request: Request, pass: GatewayPass): Request {\n if (pass.stripHeaderPrefixes.length === 0 && Object.keys(pass.injectHeaders).length === 0) {\n return request;\n }\n return new Request(request, { headers: applyGatewayPass(request.headers, pass) });\n}\n\n/** Build the short-circuit JSON response for a respond application. */\nexport function toJsonResponse(\n application: Extract<OutcomeApplication, { action: 'respond' }>\n): Response {\n return new Response(JSON.stringify(application.bodyJson), {\n status: application.status,\n headers: { 'content-type': 'application/json', ...application.headers },\n });\n}\n"],"mappings":";AAKA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAIA,IAAM,uBAAuB;;;ACA7B,IAAM,yBAAyB,OAAO;AAW7C,eAAe,eACb,SACA,KACgD;AAChD,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,OAAQ,QAAO,EAAE,WAAW,MAAM;AACrF,QAAM,OAAO,QAAQ,MAAM,EAAE;AAC7B,MAAI,CAAC,KAAM,QAAO,EAAE,WAAW,MAAM;AAErC,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,SAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI,YAAY;AAChB,aAAS;AACP,UAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,QAAI,KAAM;AACV,QAAI,QAAQ,MAAM,aAAa,KAAK;AAClC,aAAO,KAAK,MAAM,SAAS,GAAG,MAAM,KAAK,CAAC;AAC1C,cAAQ;AACR,k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M,IAAI,OAAO,YAAY;AAC7B,eAAW,QAAQ,CAAC,GAAG,IAAI,KAAK,CAAC,GAAG;AAClC,UAAI,KAAK,WAAW,CAAC,EAAG,KAAI,OAAO,IAAI;AAAA,IACzC;AAAA,EACF;AACA,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,KAAK,aAAa,GAAG;AAC9D,QAAI,IAAI,MAAM,KAAK;AAAA,EACrB;AACA,SAAO;AACT;AAMO,SAAS,iBAAiB,SAAkB,MAA4B;AAC7E,MAAI,KAAK,oBAAoB,WAAW,KAAK,OAAO,KAAK,KAAK,aAAa,EAAE,WAAW,GAAG;AACzF,WAAO;AAAA,EACT;AACA,SAAO,IAAI,QAAQ,SAAS,EAAE,SAAS,iBAAiB,QAAQ,SAAS,IAAI,EAAE,CAAC;AAClF;AAGO,SAAS,eACd,aACU;AACV,SAAO,IAAI,SAAS,KAAK,UAAU,YAAY,QAAQ,GAAG;AAAA,IACxD,QAAQ,YAAY;AAAA,IACpB,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,YAAY,QAAQ;AAAA,EACxE,CAAC;AACH;","names":[]}
@@ -0,0 +1,59 @@
1
+ import { EdgeConfig } from '@astrasyncai/verification-gateway/edge-config';
2
+ import { EdgeCoreOptions, EdgeLogger, OutcomeApplication } from '@astrasyncai/verification-gateway/edge-core';
3
+
4
+ /**
5
+ * AstraSync Trusted Agent Gateway — shared option and result types for the
6
+ * web-standard edge adapters (Vercel Edge, Cloudflare Workers, Fastly
7
+ * Compute).
8
+ */
9
+
10
+ /**
11
+ * The pass variant of the gateway's outcome application: forward the
12
+ * request to the origin after stripping every header matching one of
13
+ * `stripHeaderPrefixes` and setting each header in `injectHeaders`.
14
+ */
15
+ type GatewayPass = Extract<OutcomeApplication, {
16
+ action: 'pass';
17
+ }>;
18
+ /**
19
+ * Options shared by every adapter in this package. All identity fields are
20
+ * optional here because platforms with runtime environment variables
21
+ * (Cloudflare `env`, Vercel `process.env`) can supply them as
22
+ * `ASTRASYNC_API_KEY`, `ASTRASYNC_API_BASE_URL`, `ASTRASYNC_COUNTERPARTY_ID`
23
+ * and `ASTRASYNC_COUNTERPARTY_URL`; explicit option values always win.
24
+ * A gateway missing `counterpartyId`/`counterpartyUrl` after resolution
25
+ * fails open: it logs an error and passes all traffic through untouched.
26
+ */
27
+ interface EdgeGatewayOptions {
28
+ /** AstraSync API base. Default `https://astrasync.ai/api`. */
29
+ apiBaseUrl?: string;
30
+ /** The protected property's ASTRAE endpoint id. */
31
+ counterpartyId?: string;
32
+ /** Canonical public URL of the protected property, e.g. `https://example.shop`. */
33
+ counterpartyUrl?: string;
34
+ /** Merchant API key (`kya_*`). Observe mode degrades gracefully without one. */
35
+ apiKey?: string;
36
+ /** Edge-config cache TTL (ms). Default 60s (SDK default). */
37
+ configTtlMs?: number;
38
+ /** Time budgets (ms) — see the edge core defaults. */
39
+ budgets?: EdgeCoreOptions['budgets'];
40
+ /**
41
+ * Compile-time fallback config used before the first successful
42
+ * edge-config fetch and whenever the backend is unreachable with a cold
43
+ * cache. Defaults to the SDK's DEFAULT_EDGE_CONFIG (observe/classify).
44
+ */
45
+ fallbackConfig?: EdgeConfig;
46
+ /**
47
+ * Maximum request-body bytes read for commerce-protocol detection.
48
+ * Bodies beyond the cap are forwarded intact to the origin but detection
49
+ * sees a truncated prefix (flagged, so the backend downgrades rather
50
+ * than hard-fails). Default 1 MiB.
51
+ */
52
+ maxBodyBytes?: number;
53
+ /** Random source for beacon sampling — injectable for tests. */
54
+ random?: () => number;
55
+ /** Structured log sink. Defaults to console. */
56
+ log?: EdgeLogger;
57
+ }
58
+
59
+ export type { EdgeGatewayOptions as E, GatewayPass as G };
@@ -0,0 +1,63 @@
1
+ import { G as GatewayPass, E as EdgeGatewayOptions } from './types-7lIOikBV.js';
2
+ export { a as applyGatewayPass } from './web-BjPu7biw.js';
3
+ import '@astrasyncai/verification-gateway/edge-config';
4
+ import '@astrasyncai/verification-gateway/edge-core';
5
+
6
+ /**
7
+ * AstraSync Trusted Agent Gateway — Vercel Edge Middleware adapter.
8
+ *
9
+ * This package deliberately does NOT import `next`, so the middleware
10
+ * cannot return `NextResponse.next()` itself. It returns either a
11
+ * `Response` (enforce-mode short-circuit — return it as-is) or a
12
+ * {@link GatewayPass} describing the header changes to apply before
13
+ * continuing. Wire it up with a two-line wrapper:
14
+ *
15
+ * ```ts
16
+ * // middleware.ts
17
+ * import { NextResponse, type NextRequest } from 'next/server';
18
+ * import { createGatewayMiddleware, applyGatewayPass } from '@astrasyncai/adapter-edge/vercel';
19
+ *
20
+ * const gateway = createGatewayMiddleware();
21
+ *
22
+ * export async function middleware(request: NextRequest) {
23
+ * const result = await gateway(request);
24
+ * if (result instanceof Response) return result;
25
+ * return NextResponse.next({ request: { headers: applyGatewayPass(request.headers, result) } });
26
+ * }
27
+ * ```
28
+ *
29
+ * Alternatively pass a `next` factory in the options to get back a plain
30
+ * `Response | undefined` middleware.
31
+ *
32
+ * Configuration comes from `process.env` (`ASTRASYNC_API_KEY`,
33
+ * `ASTRASYNC_COUNTERPARTY_ID`, `ASTRASYNC_COUNTERPARTY_URL`, optional
34
+ * `ASTRASYNC_API_BASE_URL`) or explicit options, which win.
35
+ */
36
+
37
+ interface VercelGatewayOptions extends EdgeGatewayOptions {
38
+ /**
39
+ * Optional continue-factory. When provided, pass outcomes return
40
+ * `next(pass, request)` instead of the raw {@link GatewayPass} — e.g.
41
+ * `(pass, req) => NextResponse.next({ request: { headers: applyGatewayPass(req.headers, pass) } })`.
42
+ * Kept injectable so this package stays dependency-free of `next`.
43
+ */
44
+ next?: (pass: GatewayPass, request: Request) => Response | undefined;
45
+ }
46
+ /** Structural subset of Vercel's middleware fetch event (for waitUntil). */
47
+ interface VercelFetchEvent {
48
+ waitUntil?(promise: Promise<unknown>): void;
49
+ }
50
+ type VercelGatewayMiddleware = (request: Request, event?: VercelFetchEvent) => Promise<Response | GatewayPass | undefined>;
51
+ /**
52
+ * Connection-layer signals Vercel exposes as request headers. Absent
53
+ * values are simply omitted.
54
+ */
55
+ declare function collectVercelConnection(request: Request): Record<string, string>;
56
+ /**
57
+ * Create the middleware. NEVER blocks traffic outside enforce mode and
58
+ * fails open (an untouched pass) on any internal error. Telemetry beacons
59
+ * are scheduled through `event.waitUntil` when the runtime provides one.
60
+ */
61
+ declare function createGatewayMiddleware(options?: VercelGatewayOptions): VercelGatewayMiddleware;
62
+
63
+ export { EdgeGatewayOptions, GatewayPass, type VercelFetchEvent, type VercelGatewayMiddleware, type VercelGatewayOptions, collectVercelConnection, createGatewayMiddleware };
package/dist/vercel.js ADDED
@@ -0,0 +1,184 @@
1
+ // src/vercel.ts
2
+ import { evaluateEdgeRequest } from "@astrasyncai/verification-gateway/edge-core";
3
+
4
+ // src/config.ts
5
+ import {
6
+ getEdgeConfig,
7
+ DEFAULT_EDGE_CONFIG
8
+ } from "@astrasyncai/verification-gateway/edge-config";
9
+ var DEFAULT_API_BASE_URL = "https://astrasync.ai/api";
10
+ function defaultLogger(prefix) {
11
+ return (level, message, data) => {
12
+ console[level === "info" ? "log" : level](`[${prefix}] ${message}`, data ?? "");
13
+ };
14
+ }
15
+ function resolveOptions(options, env, logPrefix) {
16
+ const e = env ?? {};
17
+ return {
18
+ ...options,
19
+ apiBaseUrl: options.apiBaseUrl ?? e.ASTRASYNC_API_BASE_URL ?? DEFAULT_API_BASE_URL,
20
+ counterpartyId: options.counterpartyId ?? e.ASTRASYNC_COUNTERPARTY_ID,
21
+ counterpartyUrl: options.counterpartyUrl ?? e.ASTRASYNC_COUNTERPARTY_URL,
22
+ apiKey: options.apiKey ?? e.ASTRASYNC_API_KEY,
23
+ log: options.log ?? defaultLogger(logPrefix)
24
+ };
25
+ }
26
+ function isConfigured(resolved) {
27
+ if (resolved.counterpartyId && resolved.counterpartyUrl) return true;
28
+ resolved.log(
29
+ "error",
30
+ "counterpartyId/counterpartyUrl are not configured \u2014 passing all traffic through. Set the ASTRASYNC_COUNTERPARTY_ID / ASTRASYNC_COUNTERPARTY_URL environment variables or pass them as options."
31
+ );
32
+ return false;
33
+ }
34
+ async function loadConfig(resolved) {
35
+ try {
36
+ return await getEdgeConfig(
37
+ { apiBaseUrl: resolved.apiBaseUrl, apiKey: resolved.apiKey },
38
+ resolved.counterpartyId,
39
+ { ttlMs: resolved.configTtlMs }
40
+ );
41
+ } catch {
42
+ return resolved.fallbackConfig ?? DEFAULT_EDGE_CONFIG;
43
+ }
44
+ }
45
+
46
+ // src/web.ts
47
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
48
+ async function readBodyCapped(request, cap) {
49
+ if (request.method === "GET" || request.method === "HEAD") return { truncated: false };
50
+ const body = request.clone().body;
51
+ if (!body) return { truncated: false };
52
+ const reader = body.getReader();
53
+ const chunks = [];
54
+ let total = 0;
55
+ let truncated = false;
56
+ for (; ; ) {
57
+ const { done, value } = await reader.read();
58
+ if (done) break;
59
+ if (total + value.byteLength > cap) {
60
+ chunks.push(value.subarray(0, cap - total));
61
+ total = cap;
62
+ truncated = true;
63
+ void reader.cancel().catch(() => {
64
+ });
65
+ break;
66
+ }
67
+ chunks.push(value);
68
+ total += value.byteLength;
69
+ }
70
+ if (total === 0 && !truncated) return { truncated: false };
71
+ const joined = new Uint8Array(total);
72
+ let offset = 0;
73
+ for (const chunk of chunks) {
74
+ joined.set(chunk, offset);
75
+ offset += chunk.byteLength;
76
+ }
77
+ return { text: new TextDecoder().decode(joined), truncated };
78
+ }
79
+ async function normalizeWebRequest(request, options = {}) {
80
+ const url = new URL(request.url);
81
+ const headers = {};
82
+ request.headers.forEach((value, name) => {
83
+ headers[name] = value;
84
+ });
85
+ const body = await readBodyCapped(request, options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
86
+ const connection = options.connection ?? {};
87
+ return {
88
+ method: request.method,
89
+ uri: url.pathname,
90
+ querystring: url.search.startsWith("?") ? url.search.slice(1) : url.search,
91
+ headers,
92
+ ...body.text !== void 0 && { bodyText: body.text },
93
+ ...body.truncated && { bodyTruncated: true },
94
+ ...options.clientIp && { clientIp: options.clientIp },
95
+ ...Object.keys(connection).length > 0 && { connection }
96
+ };
97
+ }
98
+ function applyGatewayPass(headers, pass) {
99
+ const out = new Headers(headers);
100
+ for (const prefix of pass.stripHeaderPrefixes) {
101
+ const p = prefix.toLowerCase();
102
+ for (const name of [...out.keys()]) {
103
+ if (name.startsWith(p)) out.delete(name);
104
+ }
105
+ }
106
+ for (const [name, value] of Object.entries(pass.injectHeaders)) {
107
+ out.set(name, value);
108
+ }
109
+ return out;
110
+ }
111
+ function toJsonResponse(application) {
112
+ return new Response(JSON.stringify(application.bodyJson), {
113
+ status: application.status,
114
+ headers: { "content-type": "application/json", ...application.headers }
115
+ });
116
+ }
117
+
118
+ // src/vercel.ts
119
+ var UNTOUCHED_PASS = Object.freeze({
120
+ action: "pass",
121
+ injectHeaders: {},
122
+ stripHeaderPrefixes: []
123
+ });
124
+ function collectVercelConnection(request) {
125
+ const out = {};
126
+ const put = (key, headerName) => {
127
+ const v = request.headers.get(headerName);
128
+ if (v) out[key] = v;
129
+ };
130
+ put("ip", "x-real-ip");
131
+ put("country", "x-vercel-ip-country");
132
+ put("region", "x-vercel-ip-country-region");
133
+ put("city", "x-vercel-ip-city");
134
+ put("timeZone", "x-vercel-ip-timezone");
135
+ put("continent", "x-vercel-ip-continent");
136
+ put("ja4", "x-vercel-ja4-digest");
137
+ return out;
138
+ }
139
+ function createGatewayMiddleware(options = {}) {
140
+ return async function middleware(request, event) {
141
+ const resolved = resolveOptions(
142
+ options,
143
+ typeof process !== "undefined" ? process.env : void 0,
144
+ "astrasync-edge/vercel"
145
+ );
146
+ const pass = (result) => options.next ? options.next(result, request) : result;
147
+ try {
148
+ if (!isConfigured(resolved)) return pass(UNTOUCHED_PASS);
149
+ const config = await loadConfig(resolved);
150
+ const normalized = await normalizeWebRequest(request, {
151
+ maxBodyBytes: resolved.maxBodyBytes,
152
+ clientIp: request.headers.get("x-real-ip") ?? void 0,
153
+ connection: collectVercelConnection(request)
154
+ });
155
+ const { application } = await evaluateEdgeRequest(
156
+ {
157
+ apiBaseUrl: resolved.apiBaseUrl,
158
+ counterpartyId: resolved.counterpartyId,
159
+ counterpartyUrl: resolved.counterpartyUrl,
160
+ budgets: resolved.budgets,
161
+ random: resolved.random,
162
+ log: resolved.log,
163
+ ...event?.waitUntil && { waitUntil: (p) => event.waitUntil(p) }
164
+ },
165
+ normalized,
166
+ config,
167
+ resolved.apiKey
168
+ );
169
+ if (application.action === "respond") return toJsonResponse(application);
170
+ return pass(application);
171
+ } catch (err) {
172
+ resolved.log("error", "gateway error \u2014 passing request through", {
173
+ error: err instanceof Error ? err.message : String(err)
174
+ });
175
+ return pass(UNTOUCHED_PASS);
176
+ }
177
+ };
178
+ }
179
+ export {
180
+ applyGatewayPass,
181
+ collectVercelConnection,
182
+ createGatewayMiddleware
183
+ };
184
+ //# sourceMappingURL=vercel.js.map