@astrasyncai/adapter-edge 0.0.0 → 1.0.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 +156 -0
- package/dist/cloudflare.d.ts +42 -0
- package/dist/cloudflare.js +185 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/fastly.d.ts +63 -0
- package/dist/fastly.js +189 -0
- package/dist/fastly.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +93 -0
- package/dist/index.js.map +1 -0
- package/dist/types-7lIOikBV.d.ts +59 -0
- package/dist/vercel.d.ts +63 -0
- package/dist/vercel.js +181 -0
- package/dist/vercel.js.map +1 -0
- package/dist/web-BjPu7biw.d.ts +44 -0
- package/package.json +63 -3
package/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# @astrasyncai/adapter-edge
|
|
2
|
+
|
|
3
|
+
**AstraSync Trusted Agent Gateway** — edge adapters for **Vercel Edge**,
|
|
4
|
+
**Cloudflare Workers**, and **Fastly Compute**. The gateway classifies and
|
|
5
|
+
verifies inbound AI-agent traffic in front of your existing site. Zero site
|
|
6
|
+
changes; **observe-only by default**.
|
|
7
|
+
|
|
8
|
+
Every request is classified into a visibility tier — verified AstraSync
|
|
9
|
+
agents, identified-but-unregistered agents (payment-rail credentials such as
|
|
10
|
+
Visa Intelligent Commerce, Mastercard Agent Pay, Visa TAP, Web Bot Auth,
|
|
11
|
+
ACP, UCP, AP2, MPP, x402, or platform-agent UAs like Claude and ChatGPT),
|
|
12
|
+
anonymous bots, and humans. Humans and static assets are untouched — zero
|
|
13
|
+
API calls, zero added latency. Cryptographic verification of rail
|
|
14
|
+
credentials happens **server-side** at AstraSync's verify-access; the edge
|
|
15
|
+
only sniffs and forwards raw artifacts.
|
|
16
|
+
|
|
17
|
+
**Fail-open guarantee:** if the gateway can't reach AstraSync it always
|
|
18
|
+
falls back to observe + pass-through. An unreachable backend — or a
|
|
19
|
+
misconfigured gateway — can never break your site.
|
|
20
|
+
|
|
21
|
+
All three adapters share the same engine
|
|
22
|
+
(`@astrasyncai/verification-gateway/edge-core`) as the Lambda@Edge adapter
|
|
23
|
+
(`@astrasyncai/adapter-lambda`); use that package for CloudFront.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install @astrasyncai/adapter-edge
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
### Cloudflare Workers
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// src/worker.ts
|
|
37
|
+
import { createGatewayHandler } from '@astrasyncai/adapter-edge/cloudflare';
|
|
38
|
+
|
|
39
|
+
export default { fetch: createGatewayHandler() };
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Set the environment bindings on the worker (`wrangler.toml` vars +
|
|
43
|
+
`wrangler secret put ASTRASYNC_API_KEY`):
|
|
44
|
+
|
|
45
|
+
```toml
|
|
46
|
+
[vars]
|
|
47
|
+
ASTRASYNC_COUNTERPARTY_ID = "ASTRAE-…"
|
|
48
|
+
ASTRASYNC_COUNTERPARTY_URL = "https://example.shop"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Deploy the worker on the routes you want covered. Pass traffic is forwarded
|
|
52
|
+
to your origin with `fetch()`; telemetry runs in `ctx.waitUntil`, off the
|
|
53
|
+
latency path.
|
|
54
|
+
|
|
55
|
+
### Vercel Edge Middleware
|
|
56
|
+
|
|
57
|
+
This package does not import `next`, so the middleware returns either a
|
|
58
|
+
`Response` (return it as-is) or a **pass signal** you apply with the
|
|
59
|
+
provided helper — a two-line wrapper:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// middleware.ts
|
|
63
|
+
import { NextResponse, type NextRequest } from 'next/server';
|
|
64
|
+
import { createGatewayMiddleware, applyGatewayPass } from '@astrasyncai/adapter-edge/vercel';
|
|
65
|
+
|
|
66
|
+
const gateway = createGatewayMiddleware();
|
|
67
|
+
|
|
68
|
+
export async function middleware(request: NextRequest) {
|
|
69
|
+
const result = await gateway(request);
|
|
70
|
+
if (result instanceof Response) return result;
|
|
71
|
+
return NextResponse.next({ request: { headers: applyGatewayPass(request.headers, result) } });
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Configuration comes from `process.env` (`ASTRASYNC_COUNTERPARTY_ID`,
|
|
76
|
+
`ASTRASYNC_COUNTERPARTY_URL`, `ASTRASYNC_API_KEY`) or explicit options.
|
|
77
|
+
Alternatively pass a `next` factory option to get back a plain
|
|
78
|
+
`Response | undefined` middleware.
|
|
79
|
+
|
|
80
|
+
### Fastly Compute (JavaScript)
|
|
81
|
+
|
|
82
|
+
Fastly requires every `fetch` to name a **configured backend**, so
|
|
83
|
+
`originBackend` is required — create a backend for your origin (and one
|
|
84
|
+
for `astrasync.ai` so verification calls can leave the service):
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// src/index.ts
|
|
88
|
+
import { createGatewayHandler } from '@astrasyncai/adapter-edge/fastly';
|
|
89
|
+
|
|
90
|
+
const gateway = createGatewayHandler({
|
|
91
|
+
originBackend: 'origin',
|
|
92
|
+
counterpartyId: 'ASTRAE-…',
|
|
93
|
+
counterpartyUrl: 'https://example.shop',
|
|
94
|
+
apiKey: '…', // e.g. from a Fastly secret store lookup at startup
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
addEventListener('fetch', (event) => event.respondWith(gateway(event)));
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Optional geolocation enrichment (country/city/ASN) via the Fastly runtime
|
|
101
|
+
is behind the `geo: true` flag; the `fastly:geolocation` import is dynamic,
|
|
102
|
+
so the base build stays runtime-neutral.
|
|
103
|
+
|
|
104
|
+
## Configuration
|
|
105
|
+
|
|
106
|
+
| Option | Env var | Default | Notes |
|
|
107
|
+
| ----------------- | ---------------------------- | -------------------------- | ------------------------------------------------------------------------- |
|
|
108
|
+
| `counterpartyId` | `ASTRASYNC_COUNTERPARTY_ID` | — | Your property's `ASTRAE-…` endpoint id. Missing ⇒ fail-open pass-through. |
|
|
109
|
+
| `counterpartyUrl` | `ASTRASYNC_COUNTERPARTY_URL` | — | Canonical public URL of the property. |
|
|
110
|
+
| `apiKey` | `ASTRASYNC_API_KEY` | — | Merchant `kya_*` key. Observe mode degrades gracefully without it. |
|
|
111
|
+
| `apiBaseUrl` | `ASTRASYNC_API_BASE_URL` | `https://astrasync.ai/api` | |
|
|
112
|
+
| `configTtlMs` | — | 60 000 | Dashboard edge-config refresh interval. |
|
|
113
|
+
| `budgets` | — | 300 / 1500 / 3000 ms | Beacon / observe-verify / enforce-verify time budgets. |
|
|
114
|
+
| `maxBodyBytes` | — | 1 MiB | Body read cap for commerce-protocol detection. |
|
|
115
|
+
| `fallbackConfig` | — | observe/classify | Used before the first config fetch succeeds. |
|
|
116
|
+
| `originBackend` | — | — | **Fastly only, required.** Named backend for origin traffic. |
|
|
117
|
+
| `geo` | — | `false` | **Fastly only.** Opt-in `fastly:geolocation` enrichment. |
|
|
118
|
+
| `next` | — | — | **Vercel only.** Continue-factory for pass outcomes. |
|
|
119
|
+
|
|
120
|
+
Mode (`observe`/`enforce`), check depth (`classify`/`authenticate`/
|
|
121
|
+
`authorize`), per-path rules, and bot-telemetry sampling are configured on
|
|
122
|
+
the endpoint's **Edge verification** panel in the AstraSync dashboard — no
|
|
123
|
+
redeploys. The gateway refreshes its config every ~60s, and configs stale
|
|
124
|
+
for more than 24h automatically degrade enforce back to observe.
|
|
125
|
+
|
|
126
|
+
## Capture matrix
|
|
127
|
+
|
|
128
|
+
Beyond the sanitized header capture (identical on every platform — secrets
|
|
129
|
+
stripped, credential headers reduced to a safe format prefix), each
|
|
130
|
+
platform contributes the connection-layer signals it can see:
|
|
131
|
+
|
|
132
|
+
| Signal | Cloudflare Workers | Vercel Edge | Fastly Compute | (Lambda@Edge) |
|
|
133
|
+
| ------------ | ------------------------- | -------------------------------------- | ------------------ | -------------- |
|
|
134
|
+
| Client IP | `CF-Connecting-IP` | `x-real-ip` | `Fastly-Client-IP` | viewer address |
|
|
135
|
+
| Country | `request.cf.country` | `x-vercel-ip-country` | `geo` flag | viewer headers |
|
|
136
|
+
| Region/City | `request.cf.city` | `x-vercel-ip-country-region` / `-city` | `geo` flag | viewer headers |
|
|
137
|
+
| ASN | `request.cf.asn` | — | `geo` flag | viewer headers |
|
|
138
|
+
| TLS version | `request.cf.tlsVersion` | — | — | viewer headers |
|
|
139
|
+
| HTTP version | `request.cf.httpProtocol` | — | — | viewer headers |
|
|
140
|
+
| PoP/colo | `request.cf.colo` | — | — | — |
|
|
141
|
+
|
|
142
|
+
Everything captured surfaces on the endpoint's traffic feed in the
|
|
143
|
+
AstraSync dashboard.
|
|
144
|
+
|
|
145
|
+
## Enforce mode
|
|
146
|
+
|
|
147
|
+
Requests that fail verification on enforced paths get a machine-readable
|
|
148
|
+
`403` with registration guidance; human-approval flows return `202` with
|
|
149
|
+
step-up polling info. Allowed agent requests reach your origin with trust
|
|
150
|
+
attestation headers (`X-AstraSync-Trust-Score`, `X-AstraSync-Agent-Id`,
|
|
151
|
+
`X-AstraSync-Developer-Id`, `X-AstraSync-Permissions`) — inbound spoofs of
|
|
152
|
+
`x-astrasync-*` headers are stripped in both modes.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT © AstraSync
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { E as EdgeGatewayOptions } from './types-7lIOikBV.js';
|
|
2
|
+
export { G as GatewayPass } from './types-7lIOikBV.js';
|
|
3
|
+
import '@astrasyncai/verification-gateway/edge-config';
|
|
4
|
+
import '@astrasyncai/verification-gateway/edge-core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* AstraSync Trusted Agent Gateway — Cloudflare Workers adapter.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { createGatewayHandler } from '@astrasyncai/adapter-edge/cloudflare';
|
|
11
|
+
*
|
|
12
|
+
* export default { fetch: createGatewayHandler() };
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* Configuration comes from the worker's environment bindings
|
|
16
|
+
* (`ASTRASYNC_API_KEY`, `ASTRASYNC_COUNTERPARTY_ID`,
|
|
17
|
+
* `ASTRASYNC_COUNTERPARTY_URL`, optional `ASTRASYNC_API_BASE_URL`) or from
|
|
18
|
+
* explicit options, which win. The handler NEVER blocks traffic outside
|
|
19
|
+
* enforce mode and fails open on any internal error.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** Structural subset of the Workers `ExecutionContext`. */
|
|
23
|
+
interface CloudflareExecutionContext {
|
|
24
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
25
|
+
}
|
|
26
|
+
type CloudflareEnv = Record<string, unknown>;
|
|
27
|
+
type CloudflareFetchHandler = (request: Request, env?: CloudflareEnv, ctx?: CloudflareExecutionContext) => Promise<Response>;
|
|
28
|
+
/**
|
|
29
|
+
* Connection-layer signals Cloudflare exposes on `request.cf` plus the
|
|
30
|
+
* `CF-Connecting-IP` header. Absent values are simply omitted.
|
|
31
|
+
*/
|
|
32
|
+
declare function collectCloudflareConnection(request: Request): Record<string, string>;
|
|
33
|
+
/**
|
|
34
|
+
* Create the worker `fetch` handler. Pass traffic is forwarded to the
|
|
35
|
+
* origin with `fetch(mutatedRequest)` (spoofable trust headers stripped,
|
|
36
|
+
* attestation headers injected); enforce-mode denials short-circuit with a
|
|
37
|
+
* machine-readable JSON response. Telemetry beacons are scheduled through
|
|
38
|
+
* `ctx.waitUntil`, so they never add request latency.
|
|
39
|
+
*/
|
|
40
|
+
declare function createGatewayHandler(options?: EdgeGatewayOptions): CloudflareFetchHandler;
|
|
41
|
+
|
|
42
|
+
export { type CloudflareEnv, type CloudflareExecutionContext, type CloudflareFetchHandler, EdgeGatewayOptions, collectCloudflareConnection, createGatewayHandler };
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// src/cloudflare.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/cloudflare.ts
|
|
125
|
+
function collectCloudflareConnection(request) {
|
|
126
|
+
const cf = request.cf;
|
|
127
|
+
const out = {};
|
|
128
|
+
const ip = request.headers.get("cf-connecting-ip");
|
|
129
|
+
if (ip) out.ip = ip;
|
|
130
|
+
if (!cf) return out;
|
|
131
|
+
if (cf.country) out.country = cf.country;
|
|
132
|
+
if (cf.city) out.city = cf.city;
|
|
133
|
+
if (cf.asn !== void 0 && cf.asn !== null && cf.asn !== "") out.asn = String(cf.asn);
|
|
134
|
+
if (cf.tlsVersion) out.tlsVersion = cf.tlsVersion;
|
|
135
|
+
if (cf.httpProtocol) out.httpVersion = cf.httpProtocol;
|
|
136
|
+
if (cf.colo) out.colo = cf.colo;
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
function envStrings(env) {
|
|
140
|
+
const out = {};
|
|
141
|
+
for (const [key, value] of Object.entries(env ?? {})) {
|
|
142
|
+
if (typeof value === "string") out[key] = value;
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
function createGatewayHandler(options = {}) {
|
|
147
|
+
return async function fetchHandler(request, env, ctx) {
|
|
148
|
+
const resolved = resolveOptions(options, envStrings(env), "astrasync-edge/cloudflare");
|
|
149
|
+
try {
|
|
150
|
+
if (!isConfigured(resolved)) return fetch(request);
|
|
151
|
+
const config = await loadConfig(resolved);
|
|
152
|
+
const normalized = await normalizeWebRequest(request, {
|
|
153
|
+
maxBodyBytes: resolved.maxBodyBytes,
|
|
154
|
+
clientIp: request.headers.get("cf-connecting-ip") ?? void 0,
|
|
155
|
+
connection: collectCloudflareConnection(request)
|
|
156
|
+
});
|
|
157
|
+
const { application } = await evaluateEdgeRequest(
|
|
158
|
+
{
|
|
159
|
+
apiBaseUrl: resolved.apiBaseUrl,
|
|
160
|
+
counterpartyId: resolved.counterpartyId,
|
|
161
|
+
counterpartyUrl: resolved.counterpartyUrl,
|
|
162
|
+
budgets: resolved.budgets,
|
|
163
|
+
random: resolved.random,
|
|
164
|
+
log: resolved.log,
|
|
165
|
+
...ctx && { waitUntil: (p) => ctx.waitUntil(p) }
|
|
166
|
+
},
|
|
167
|
+
normalized,
|
|
168
|
+
config,
|
|
169
|
+
resolved.apiKey
|
|
170
|
+
);
|
|
171
|
+
if (application.action === "respond") return toJsonResponse(application);
|
|
172
|
+
return fetch(buildPassRequest(request, application));
|
|
173
|
+
} catch (err) {
|
|
174
|
+
resolved.log("error", "gateway error \u2014 passing request through", {
|
|
175
|
+
error: err instanceof Error ? err.message : String(err)
|
|
176
|
+
});
|
|
177
|
+
return fetch(request);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
export {
|
|
182
|
+
collectCloudflareConnection,
|
|
183
|
+
createGatewayHandler
|
|
184
|
+
};
|
|
185
|
+
//# sourceMappingURL=cloudflare.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cloudflare.ts","../src/config.ts","../src/web.ts"],"sourcesContent":["/**\n * AstraSync Trusted Agent Gateway — Cloudflare Workers adapter.\n *\n * ```ts\n * import { createGatewayHandler } from '@astrasyncai/adapter-edge/cloudflare';\n *\n * export default { fetch: createGatewayHandler() };\n * ```\n *\n * Configuration comes from the worker's environment bindings\n * (`ASTRASYNC_API_KEY`, `ASTRASYNC_COUNTERPARTY_ID`,\n * `ASTRASYNC_COUNTERPARTY_URL`, optional `ASTRASYNC_API_BASE_URL`) or from\n * explicit options, which win. The handler NEVER blocks traffic outside\n * enforce mode and fails open on any internal error.\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\n/** The subset of `request.cf` connection properties the gateway captures. */\ninterface CfConnectionProperties {\n country?: string;\n asn?: number | string;\n tlsVersion?: string;\n httpProtocol?: string;\n city?: string;\n colo?: string;\n}\n\n/** Structural subset of the Workers `ExecutionContext`. */\nexport interface CloudflareExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type CloudflareEnv = Record<string, unknown>;\n\nexport type CloudflareFetchHandler = (\n request: Request,\n env?: CloudflareEnv,\n ctx?: CloudflareExecutionContext\n) => Promise<Response>;\n\n/**\n * Connection-layer signals Cloudflare exposes on `request.cf` plus the\n * `CF-Connecting-IP` header. Absent values are simply omitted.\n */\nexport function collectCloudflareConnection(request: Request): Record<string, string> {\n const cf = (request as Request & { cf?: CfConnectionProperties }).cf;\n const out: Record<string, string> = {};\n const ip = request.headers.get('cf-connecting-ip');\n if (ip) out.ip = ip;\n if (!cf) return out;\n if (cf.country) out.country = cf.country;\n if (cf.city) out.city = cf.city;\n if (cf.asn !== undefined && cf.asn !== null && cf.asn !== '') out.asn = String(cf.asn);\n if (cf.tlsVersion) out.tlsVersion = cf.tlsVersion;\n if (cf.httpProtocol) out.httpVersion = cf.httpProtocol;\n if (cf.colo) out.colo = cf.colo;\n return out;\n}\n\nfunction envStrings(env: CloudflareEnv | undefined): Record<string, string | undefined> {\n const out: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(env ?? {})) {\n if (typeof value === 'string') out[key] = value;\n }\n return out;\n}\n\n/**\n * Create the worker `fetch` handler. Pass traffic is forwarded to the\n * origin with `fetch(mutatedRequest)` (spoofable trust headers stripped,\n * attestation headers injected); enforce-mode denials short-circuit with a\n * machine-readable JSON response. Telemetry beacons are scheduled through\n * `ctx.waitUntil`, so they never add request latency.\n */\nexport function createGatewayHandler(options: EdgeGatewayOptions = {}): CloudflareFetchHandler {\n return async function fetchHandler(request, env, ctx) {\n const resolved = resolveOptions(options, envStrings(env), 'astrasync-edge/cloudflare');\n try {\n if (!isConfigured(resolved)) return fetch(request);\n\n const config = await loadConfig(resolved);\n const normalized = await normalizeWebRequest(request, {\n maxBodyBytes: resolved.maxBodyBytes,\n clientIp: request.headers.get('cf-connecting-ip') ?? undefined,\n connection: collectCloudflareConnection(request),\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 ...(ctx && { waitUntil: (p: Promise<unknown>) => ctx.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));\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);\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":";AAgBA,SAAS,2BAA2B;;;ACXpC;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,E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AA,QACpD,cAAc,SAAS;AAAA,QACvB,UAAU,QAAQ,QAAQ,IAAI,kBAAkB,KAAK;AAAA,QACrD,YAAY,4BAA4B,OAAO;AAAA,MACjD,CAAC;AAED,YAAM,EAAE,YAAY,IAAI,MAAM;AAAA,QAC5B;AAAA,UACE,YAAY,SAAS;AAAA,UACrB,gBAAgB,SAAS;AAAA,UACzB,iBAAiB,SAAS;AAAA,UAC1B,SAAS,SAAS;AAAA,UAClB,QAAQ,SAAS;AAAA,UACjB,KAAK,SAAS;AAAA,UACd,GAAI,OAAO,EAAE,WAAW,CAAC,MAAwB,IAAI,UAAU,CAAC,EAAE;AAAA,QACpE;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX;AAEA,UAAI,YAAY,WAAW,UAAW,QAAO,eAAe,WAAW;AACvE,aAAO,MAAM,iBAAiB,SAAS,WAAW,CAAC;AAAA,IACrD,SAAS,KAAK;AAEZ,eAAS,IAAI,SAAS,gDAA2C;AAAA,QAC/D,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AACD,aAAO,MAAM,OAAO;AAAA,IACtB;AAAA,EACF;AACF;","names":[]}
|
package/dist/fastly.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { E as EdgeGatewayOptions } from './types-7lIOikBV.js';
|
|
2
|
+
export { G as GatewayPass } from './types-7lIOikBV.js';
|
|
3
|
+
import '@astrasyncai/verification-gateway/edge-config';
|
|
4
|
+
import '@astrasyncai/verification-gateway/edge-core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* AstraSync Trusted Agent Gateway — Fastly Compute (JavaScript) adapter.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { createGatewayHandler } from '@astrasyncai/adapter-edge/fastly';
|
|
11
|
+
*
|
|
12
|
+
* const gateway = createGatewayHandler({
|
|
13
|
+
* originBackend: 'origin', // the backend name configured on your service
|
|
14
|
+
* counterpartyId: 'ASTRAE-…',
|
|
15
|
+
* counterpartyUrl: 'https://example.shop',
|
|
16
|
+
* apiKey: '…',
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* addEventListener('fetch', (event) => event.respondWith(gateway(event)));
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* Fastly Compute requires every `fetch` to name a configured backend, so
|
|
23
|
+
* `originBackend` is REQUIRED (the AstraSync API must also be reachable —
|
|
24
|
+
* see the README for the api backend setup). Fastly has no ambient
|
|
25
|
+
* environment map; configure via options.
|
|
26
|
+
*
|
|
27
|
+
* Geolocation enrichment (`fastly:geolocation`) is available behind the
|
|
28
|
+
* opt-in `geo` flag: the import is dynamic, so the base build carries no
|
|
29
|
+
* `fastly:*` imports and runs in any test runner.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
interface FastlyGatewayOptions extends EdgeGatewayOptions {
|
|
33
|
+
/**
|
|
34
|
+
* REQUIRED. The name of the backend (as configured on the Fastly
|
|
35
|
+
* service) that origin-bound traffic is forwarded to — Fastly Compute
|
|
36
|
+
* fetches must name a backend explicitly.
|
|
37
|
+
*/
|
|
38
|
+
originBackend: string;
|
|
39
|
+
/**
|
|
40
|
+
* Opt-in geolocation enrichment via the `fastly:geolocation` runtime
|
|
41
|
+
* module (country/city/ASN on the connection capture). Off by default so
|
|
42
|
+
* the base build has no `fastly:*` imports.
|
|
43
|
+
*/
|
|
44
|
+
geo?: boolean;
|
|
45
|
+
}
|
|
46
|
+
/** Structural subset of the Fastly Compute fetch event. */
|
|
47
|
+
interface FastlyFetchEvent {
|
|
48
|
+
request: Request;
|
|
49
|
+
client?: {
|
|
50
|
+
address?: string;
|
|
51
|
+
};
|
|
52
|
+
waitUntil?(promise: Promise<unknown>): void;
|
|
53
|
+
}
|
|
54
|
+
type FastlyGatewayHandler = (event: FastlyFetchEvent) => Promise<Response>;
|
|
55
|
+
/**
|
|
56
|
+
* Create the fetch-event handler. Pass traffic is forwarded with
|
|
57
|
+
* `fetch(mutatedRequest, { backend: originBackend })`; enforce-mode
|
|
58
|
+
* denials short-circuit with a machine-readable JSON response. Telemetry
|
|
59
|
+
* beacons are scheduled through `event.waitUntil` when available.
|
|
60
|
+
*/
|
|
61
|
+
declare function createGatewayHandler(options: FastlyGatewayOptions): FastlyGatewayHandler;
|
|
62
|
+
|
|
63
|
+
export { EdgeGatewayOptions, type FastlyFetchEvent, type FastlyGatewayHandler, type FastlyGatewayOptions, createGatewayHandler };
|
package/dist/fastly.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
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
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
function createGatewayHandler(options) {
|
|
144
|
+
if (!options.originBackend) {
|
|
145
|
+
throw new Error(
|
|
146
|
+
"@astrasyncai/adapter-edge/fastly: `originBackend` is required \u2014 Fastly Compute fetches must name a backend configured on the service."
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const backendInit = { backend: options.originBackend };
|
|
150
|
+
return async function handleFetchEvent(event) {
|
|
151
|
+
const request = event.request;
|
|
152
|
+
const resolved = resolveOptions(options, void 0, "astrasync-edge/fastly");
|
|
153
|
+
try {
|
|
154
|
+
if (!isConfigured(resolved)) return fetch(request, backendInit);
|
|
155
|
+
const clientIp = request.headers.get("fastly-client-ip") ?? event.client?.address ?? void 0;
|
|
156
|
+
const config = await loadConfig(resolved);
|
|
157
|
+
const normalized = await normalizeWebRequest(request, {
|
|
158
|
+
maxBodyBytes: resolved.maxBodyBytes,
|
|
159
|
+
clientIp,
|
|
160
|
+
connection: await collectFastlyConnection(clientIp, options.geo)
|
|
161
|
+
});
|
|
162
|
+
const { application } = await evaluateEdgeRequest(
|
|
163
|
+
{
|
|
164
|
+
apiBaseUrl: resolved.apiBaseUrl,
|
|
165
|
+
counterpartyId: resolved.counterpartyId,
|
|
166
|
+
counterpartyUrl: resolved.counterpartyUrl,
|
|
167
|
+
budgets: resolved.budgets,
|
|
168
|
+
random: resolved.random,
|
|
169
|
+
log: resolved.log,
|
|
170
|
+
...event.waitUntil && { waitUntil: (p) => event.waitUntil(p) }
|
|
171
|
+
},
|
|
172
|
+
normalized,
|
|
173
|
+
config,
|
|
174
|
+
resolved.apiKey
|
|
175
|
+
);
|
|
176
|
+
if (application.action === "respond") return toJsonResponse(application);
|
|
177
|
+
return fetch(buildPassRequest(request, application), backendInit);
|
|
178
|
+
} catch (err) {
|
|
179
|
+
resolved.log("error", "gateway error \u2014 passing request through", {
|
|
180
|
+
error: err instanceof Error ? err.message : String(err)
|
|
181
|
+
});
|
|
182
|
+
return fetch(request, backendInit);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
export {
|
|
187
|
+
createGatewayHandler
|
|
188
|
+
};
|
|
189
|
+
//# 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}\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 } 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,OAAO,QAAQ,MAAM,EAAE;AAC7B,MAAI,CAAC,KAAM,QAAO,EAAE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AClE,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":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -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;AAA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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 };
|
package/dist/vercel.d.ts
ADDED
|
@@ -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,181 @@
|
|
|
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
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
function createGatewayMiddleware(options = {}) {
|
|
137
|
+
return async function middleware(request, event) {
|
|
138
|
+
const resolved = resolveOptions(
|
|
139
|
+
options,
|
|
140
|
+
typeof process !== "undefined" ? process.env : void 0,
|
|
141
|
+
"astrasync-edge/vercel"
|
|
142
|
+
);
|
|
143
|
+
const pass = (result) => options.next ? options.next(result, request) : result;
|
|
144
|
+
try {
|
|
145
|
+
if (!isConfigured(resolved)) return pass(UNTOUCHED_PASS);
|
|
146
|
+
const config = await loadConfig(resolved);
|
|
147
|
+
const normalized = await normalizeWebRequest(request, {
|
|
148
|
+
maxBodyBytes: resolved.maxBodyBytes,
|
|
149
|
+
clientIp: request.headers.get("x-real-ip") ?? void 0,
|
|
150
|
+
connection: collectVercelConnection(request)
|
|
151
|
+
});
|
|
152
|
+
const { application } = await evaluateEdgeRequest(
|
|
153
|
+
{
|
|
154
|
+
apiBaseUrl: resolved.apiBaseUrl,
|
|
155
|
+
counterpartyId: resolved.counterpartyId,
|
|
156
|
+
counterpartyUrl: resolved.counterpartyUrl,
|
|
157
|
+
budgets: resolved.budgets,
|
|
158
|
+
random: resolved.random,
|
|
159
|
+
log: resolved.log,
|
|
160
|
+
...event?.waitUntil && { waitUntil: (p) => event.waitUntil(p) }
|
|
161
|
+
},
|
|
162
|
+
normalized,
|
|
163
|
+
config,
|
|
164
|
+
resolved.apiKey
|
|
165
|
+
);
|
|
166
|
+
if (application.action === "respond") return toJsonResponse(application);
|
|
167
|
+
return pass(application);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
resolved.log("error", "gateway error \u2014 passing request through", {
|
|
170
|
+
error: err instanceof Error ? err.message : String(err)
|
|
171
|
+
});
|
|
172
|
+
return pass(UNTOUCHED_PASS);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
export {
|
|
177
|
+
applyGatewayPass,
|
|
178
|
+
collectVercelConnection,
|
|
179
|
+
createGatewayMiddleware
|
|
180
|
+
};
|
|
181
|
+
//# sourceMappingURL=vercel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vercel.ts","../src/config.ts","../src/web.ts"],"sourcesContent":["/**\n * AstraSync Trusted Agent Gateway — Vercel Edge Middleware adapter.\n *\n * This package deliberately does NOT import `next`, so the middleware\n * cannot return `NextResponse.next()` itself. It returns either a\n * `Response` (enforce-mode short-circuit — return it as-is) or a\n * {@link GatewayPass} describing the header changes to apply before\n * continuing. Wire it up with a two-line wrapper:\n *\n * ```ts\n * // middleware.ts\n * import { NextResponse, type NextRequest } from 'next/server';\n * import { createGatewayMiddleware, applyGatewayPass } from '@astrasyncai/adapter-edge/vercel';\n *\n * const gateway = createGatewayMiddleware();\n *\n * export async function middleware(request: NextRequest) {\n * const result = await gateway(request);\n * if (result instanceof Response) return result;\n * return NextResponse.next({ request: { headers: applyGatewayPass(request.headers, result) } });\n * }\n * ```\n *\n * Alternatively pass a `next` factory in the options to get back a plain\n * `Response | undefined` middleware.\n *\n * Configuration comes from `process.env` (`ASTRASYNC_API_KEY`,\n * `ASTRASYNC_COUNTERPARTY_ID`, `ASTRASYNC_COUNTERPARTY_URL`, optional\n * `ASTRASYNC_API_BASE_URL`) or explicit options, which win.\n */\n\nimport { evaluateEdgeRequest } from '@astrasyncai/verification-gateway/edge-core';\nimport { resolveOptions, isConfigured, loadConfig } from './config';\nimport type { EdgeGatewayOptions, GatewayPass } from './types';\nimport { normalizeWebRequest, applyGatewayPass, toJsonResponse } from './web';\n\nexport { applyGatewayPass };\nexport type { EdgeGatewayOptions, GatewayPass } from './types';\n\nexport interface VercelGatewayOptions extends EdgeGatewayOptions {\n /**\n * Optional continue-factory. When provided, pass outcomes return\n * `next(pass, request)` instead of the raw {@link GatewayPass} — e.g.\n * `(pass, req) => NextResponse.next({ request: { headers: applyGatewayPass(req.headers, pass) } })`.\n * Kept injectable so this package stays dependency-free of `next`.\n */\n next?: (pass: GatewayPass, request: Request) => Response | undefined;\n}\n\n/** Structural subset of Vercel's middleware fetch event (for waitUntil). */\nexport interface VercelFetchEvent {\n waitUntil?(promise: Promise<unknown>): void;\n}\n\nexport type VercelGatewayMiddleware = (\n request: Request,\n event?: VercelFetchEvent\n) => Promise<Response | GatewayPass | undefined>;\n\nconst UNTOUCHED_PASS: GatewayPass = Object.freeze({\n action: 'pass' as const,\n injectHeaders: {},\n stripHeaderPrefixes: [],\n});\n\n/**\n * Connection-layer signals Vercel exposes as request headers. Absent\n * values are simply omitted.\n */\nexport function collectVercelConnection(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n const put = (key: string, headerName: string) => {\n const v = request.headers.get(headerName);\n if (v) out[key] = v;\n };\n put('ip', 'x-real-ip');\n put('country', 'x-vercel-ip-country');\n put('region', 'x-vercel-ip-country-region');\n put('city', 'x-vercel-ip-city');\n return out;\n}\n\n/**\n * Create the middleware. NEVER blocks traffic outside enforce mode and\n * fails open (an untouched pass) on any internal error. Telemetry beacons\n * are scheduled through `event.waitUntil` when the runtime provides one.\n */\nexport function createGatewayMiddleware(\n options: VercelGatewayOptions = {}\n): VercelGatewayMiddleware {\n return async function middleware(request, event) {\n const resolved = resolveOptions(\n options,\n typeof process !== 'undefined' ? process.env : undefined,\n 'astrasync-edge/vercel'\n );\n const pass = (result: GatewayPass): Response | GatewayPass | undefined =>\n options.next ? options.next(result, request) : result;\n try {\n if (!isConfigured(resolved)) return pass(UNTOUCHED_PASS);\n\n const config = await loadConfig(resolved);\n const normalized = await normalizeWebRequest(request, {\n maxBodyBytes: resolved.maxBodyBytes,\n clientIp: request.headers.get('x-real-ip') ?? undefined,\n connection: collectVercelConnection(request),\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 pass(application);\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 pass(UNTOUCHED_PASS);\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":";AA+BA,SAAS,2BAA2B;;;AC1BpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAIA,IAAM,u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QAAQ,OAAO,QAAQ,KAAK,QAAQ,OAAO,IAAI;AACjD,QAAI;AACF,UAAI,CAAC,aAAa,QAAQ,EAAG,QAAO,KAAK,cAAc;AAEvD,YAAM,SAAS,MAAM,WAAW,QAAQ;AACxC,YAAM,aAAa,MAAM,oBAAoB,SAAS;AAAA,QACpD,cAAc,SAAS;AAAA,QACvB,UAAU,QAAQ,QAAQ,IAAI,WAAW,KAAK;AAAA,QAC9C,YAAY,wBAAwB,OAAO;AAAA,MAC7C,CAAC;AAED,YAAM,EAAE,YAAY,IAAI,MAAM;AAAA,QAC5B;AAAA,UACE,YAAY,SAAS;AAAA,UACrB,gBAAgB,SAAS;AAAA,UACzB,iBAAiB,SAAS;AAAA,UAC1B,SAAS,SAAS;AAAA,UAClB,QAAQ,SAAS;AAAA,UACjB,KAAK,SAAS;AAAA,UACd,GAAI,OAAO,aAAa,EAAE,WAAW,CAAC,MAAwB,MAAM,UAAW,CAAC,EAAE;AAAA,QACpF;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX;AAEA,UAAI,YAAY,WAAW,UAAW,QAAO,eAAe,WAAW;AACvE,aAAO,KAAK,WAAW;AAAA,IACzB,SAAS,KAAK;AAEZ,eAAS,IAAI,SAAS,gDAA2C;AAAA,QAC/D,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AACD,aAAO,KAAK,cAAc;AAAA,IAC5B;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { NormalizedRequest, OutcomeApplication } from '@astrasyncai/verification-gateway/edge-core';
|
|
2
|
+
import { G as GatewayPass } from './types-7lIOikBV.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Shared web-standard platform I/O: converts a fetch-API `Request` into
|
|
6
|
+
* the edge core's `NormalizedRequest`, and applies the core's abstract
|
|
7
|
+
* outcome application back onto fetch-API primitives.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Default request-body read cap for commerce-protocol detection. */
|
|
11
|
+
declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
12
|
+
interface WebNormalizeOptions {
|
|
13
|
+
/** Body read cap in bytes. Default {@link DEFAULT_MAX_BODY_BYTES}. */
|
|
14
|
+
maxBodyBytes?: number;
|
|
15
|
+
/** Client IP as the platform reports it. */
|
|
16
|
+
clientIp?: string;
|
|
17
|
+
/** Connection-layer metadata the platform collected (country, asn, …). */
|
|
18
|
+
connection?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Normalize a fetch-API `Request` into the edge core's request shape.
|
|
22
|
+
* Header names are already lowercased (and multi-valued headers joined
|
|
23
|
+
* with `", "`) by the `Headers` class. The body is read from a CLONE — the
|
|
24
|
+
* original request stays forwardable to the origin — and capped at
|
|
25
|
+
* `maxBodyBytes` (detection sees a flagged, truncated prefix beyond it).
|
|
26
|
+
*/
|
|
27
|
+
declare function normalizeWebRequest(request: Request, options?: WebNormalizeOptions): Promise<NormalizedRequest>;
|
|
28
|
+
/**
|
|
29
|
+
* Apply a pass application to a header set: strip every header matching
|
|
30
|
+
* one of the spoofable prefixes, then set the injected trust headers.
|
|
31
|
+
* Returns a NEW `Headers` instance; the input is not mutated.
|
|
32
|
+
*/
|
|
33
|
+
declare function applyGatewayPass(headers: Headers, pass: GatewayPass): Headers;
|
|
34
|
+
/**
|
|
35
|
+
* Build the origin-bound request for a pass application: the same request
|
|
36
|
+
* with spoofable headers stripped and trust headers injected.
|
|
37
|
+
*/
|
|
38
|
+
declare function buildPassRequest(request: Request, pass: GatewayPass): Request;
|
|
39
|
+
/** Build the short-circuit JSON response for a respond application. */
|
|
40
|
+
declare function toJsonResponse(application: Extract<OutcomeApplication, {
|
|
41
|
+
action: 'respond';
|
|
42
|
+
}>): Response;
|
|
43
|
+
|
|
44
|
+
export { DEFAULT_MAX_BODY_BYTES as D, type WebNormalizeOptions as W, applyGatewayPass as a, buildPassRequest as b, normalizeWebRequest as n, toJsonResponse as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astrasyncai/adapter-edge",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "AstraSync Trusted Agent Gateway — edge adapters for Vercel Edge, Cloudflare Workers, and Fastly Compute",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./vercel": {
|
|
12
|
+
"types": "./dist/vercel.d.ts",
|
|
13
|
+
"import": "./dist/vercel.js"
|
|
14
|
+
},
|
|
15
|
+
"./cloudflare": {
|
|
16
|
+
"types": "./dist/cloudflare.d.ts",
|
|
17
|
+
"import": "./dist/cloudflare.js"
|
|
18
|
+
},
|
|
19
|
+
"./fastly": {
|
|
20
|
+
"types": "./dist/fastly.d.ts",
|
|
21
|
+
"import": "./dist/fastly.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup",
|
|
30
|
+
"lint": "eslint src --ext .ts",
|
|
31
|
+
"typecheck": "tsc --noEmit",
|
|
32
|
+
"test": "vitest run",
|
|
33
|
+
"test:watch": "vitest watch",
|
|
34
|
+
"clean": "rm -rf dist",
|
|
35
|
+
"check:dts-leaks": "node scripts/check-dts-leaks.mjs",
|
|
36
|
+
"prepublishOnly": "npm run clean && npm run typecheck && npm run build && npm run check:dts-leaks"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"astrasync",
|
|
40
|
+
"trusted-agent-gateway",
|
|
41
|
+
"kya",
|
|
42
|
+
"edge",
|
|
43
|
+
"cloudflare-workers",
|
|
44
|
+
"vercel-edge",
|
|
45
|
+
"fastly-compute",
|
|
46
|
+
"agent-verification",
|
|
47
|
+
"bot-detection"
|
|
48
|
+
],
|
|
49
|
+
"author": "AstraSync",
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "https://github.com/AstraSync-KYA/KYA-Platform.git",
|
|
54
|
+
"directory": "packages/adapter-edge"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@astrasyncai/verification-gateway": "^4.1.0"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/node": "^20.10.0",
|
|
61
|
+
"eslint": "^8.56.0",
|
|
62
|
+
"tsup": "^8.0.1",
|
|
63
|
+
"typescript": "^5.3.3",
|
|
64
|
+
"vitest": "^4.0.18"
|
|
65
|
+
}
|
|
6
66
|
}
|