@astrasyncai/adapter-lambda 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
+ // src/handler.ts
2
+ import { evaluateEdgeRequest } from "@astrasyncai/verification-gateway/edge-core";
3
+
1
4
  // src/cf.ts
2
- import {
3
- sanitizeHeaders
4
- } from "@astrasyncai/verification-gateway/metadata-capture";
5
+ import { buildObservedMetadata as buildObservedMetadataCore } from "@astrasyncai/verification-gateway/edge-core";
5
6
  function getRequest(event) {
6
7
  return event.Records[0].cf.request;
7
8
  }
@@ -16,6 +17,14 @@ function flattenHeaders(headers) {
16
17
  }
17
18
  return out;
18
19
  }
20
+ function flattenHeadersSingle(headers) {
21
+ const out = {};
22
+ for (const [name, entries] of Object.entries(headers)) {
23
+ if (!entries?.length) continue;
24
+ out[name] = entries.map((e) => e.value).join(", ");
25
+ }
26
+ return out;
27
+ }
19
28
  function decodeBody(request) {
20
29
  const body = request.body;
21
30
  if (!body?.data) return { truncated: false };
@@ -49,18 +58,33 @@ function collectConnectionMetadata(request) {
49
58
  if (devices.length) out.device = devices.join(",");
50
59
  return out;
51
60
  }
52
- function buildObservedMetadata(request) {
53
- const { headers, apiKeyFormat, platformHeaders } = sanitizeHeaders(
54
- flattenHeaders(request.headers)
55
- );
61
+ function toNormalizedRequest(request) {
62
+ const body = decodeBody(request);
56
63
  const connection = collectConnectionMetadata(request);
64
+ const clientIp = getHeader(request, "cloudfront-viewer-address")?.split(":")[0];
57
65
  return {
58
- headers,
59
- ...apiKeyFormat && { apiKeyFormat },
60
- ...platformHeaders && { platformHeaders },
66
+ method: request.method,
67
+ uri: request.uri,
68
+ querystring: request.querystring ?? "",
69
+ headers: flattenHeadersSingle(request.headers),
70
+ ...body.text !== void 0 && { bodyText: body.text },
71
+ ...body.truncated && { bodyTruncated: true },
72
+ ...clientIp && { clientIp },
61
73
  ...Object.keys(connection).length > 0 && { connection }
62
74
  };
63
75
  }
76
+ function applyCoreOutcome(request, application) {
77
+ if (application.action === "respond") {
78
+ return jsonResponse(application.status, application.bodyJson, application.headers);
79
+ }
80
+ for (const prefix of application.stripHeaderPrefixes) {
81
+ stripHeadersByPrefix(request, prefix);
82
+ }
83
+ for (const [name, value] of Object.entries(application.injectHeaders)) {
84
+ setHeader(request, name, value);
85
+ }
86
+ return request;
87
+ }
64
88
  function normalizeOriginHost(request) {
65
89
  const originDomain = request.origin?.custom?.domainName ?? request.origin?.s3?.domainName ?? void 0;
66
90
  if (!originDomain) return;
@@ -144,475 +168,6 @@ function _resetConfigCaches() {
144
168
  secretCache.clear();
145
169
  }
146
170
 
147
- // src/classify.ts
148
- import { extractCredentials } from "@astrasyncai/verification-gateway/verify";
149
- import { detectPlatformFingerprint } from "@astrasyncai/verification-gateway/platform-signatures";
150
- import { matchEdgePathRule } from "@astrasyncai/verification-gateway/edge-config";
151
- import { sanitizeHeaders as sanitizeHeaders2 } from "@astrasyncai/verification-gateway/metadata-capture";
152
-
153
- // src/detect.ts
154
- var SD_JWT_PATTERN = /^eyJ[\w-]+\.[\w-]*\.[\w-]+~/;
155
- function sniffJwtHeader(compact) {
156
- try {
157
- const seg = compact.split(".")[0];
158
- return JSON.parse(Buffer.from(seg, "base64url").toString("utf8"));
159
- } catch {
160
- return void 0;
161
- }
162
- }
163
- function parseJsonBody(body) {
164
- if (!body.text) return void 0;
165
- try {
166
- const parsed = JSON.parse(body.text);
167
- return typeof parsed === "object" && parsed !== null ? parsed : void 0;
168
- } catch {
169
- return void 0;
170
- }
171
- }
172
- function detectCommerce(request, host, body) {
173
- const url = requestUrl(request, host);
174
- const method = request.method;
175
- const headers = flattenHeaders(request.headers);
176
- const jsonBody = parseJsonBody(body);
177
- const truncated = body.truncated ? { bodyTruncated: true } : {};
178
- const authHeader = getHeader(request, "authorization");
179
- const bearer = authHeader?.replace(/^Bearer\s+/i, "");
180
- const mandateHeader = getHeader(request, "x-payment-mandate") ?? getHeader(request, "payment-mandate");
181
- const sdJwtCandidate = [mandateHeader, bearer].find((v) => v && SD_JWT_PATTERN.test(v));
182
- if (sdJwtCandidate) {
183
- const typ = sniffJwtHeader(sdJwtCandidate)?.typ;
184
- return {
185
- protocol: "vi-sd-jwt",
186
- artifacts: { viSdJwt: sdJwtCandidate },
187
- evidence: { typ, ...truncated }
188
- };
189
- }
190
- const signature = getHeader(request, "signature");
191
- const signatureInput = getHeader(request, "signature-input");
192
- if (signature && signatureInput) {
193
- const signatureAgent = getHeader(request, "signature-agent");
194
- const registryHint = getHeader(request, "x-agent-registry");
195
- const lowerInput = signatureInput.toLowerCase();
196
- const protocol = signatureAgent ? "rfc9421-web-bot-auth" : registryHint?.toLowerCase().includes("visa") || lowerInput.includes("visa") ? "rfc9421-tap" : registryHint?.toLowerCase().includes("mastercard") || lowerInput.includes("mastercard") ? "rfc9421-agent-pay" : "rfc9421";
197
- return {
198
- protocol,
199
- artifacts: {
200
- rfc9421: { headers, method, url, ...body.text && { body: body.text } }
201
- },
202
- evidence: {
203
- ...signatureAgent && { signatureAgent },
204
- ...registryHint && { registryHint },
205
- keyid: signatureInput.match(/keyid="([^"]+)"/)?.[1],
206
- ...truncated
207
- }
208
- };
209
- }
210
- const acpTimestamp = getHeader(request, "timestamp");
211
- if (signature && !signatureInput && (acpTimestamp || getHeader(request, "idempotency-key"))) {
212
- return {
213
- protocol: "acp",
214
- artifacts: {
215
- acpRequest: {
216
- method,
217
- url,
218
- headers,
219
- ...body.text && { rawBody: body.text },
220
- ...jsonBody && { body: jsonBody }
221
- }
222
- },
223
- evidence: { hasTimestamp: Boolean(acpTimestamp), ...truncated }
224
- };
225
- }
226
- if (/\/checkout[-_]sessions(\/|$)/.test(request.uri)) {
227
- return {
228
- protocol: "ucp",
229
- artifacts: { ucpRequest: { method, url, ...jsonBody && { body: jsonBody } } },
230
- evidence: { path: request.uri, ...truncated }
231
- };
232
- }
233
- if (jsonBody) {
234
- const intent = jsonBody.intent_mandate ?? jsonBody.intentMandate;
235
- const cart = jsonBody.cart_mandate ?? jsonBody.cartMandate;
236
- const payment = jsonBody.payment_mandate ?? jsonBody.paymentMandate;
237
- if (typeof intent === "string" || typeof cart === "string" || typeof payment === "string") {
238
- return {
239
- protocol: "ap2",
240
- artifacts: {
241
- ap2Mandates: {
242
- ...typeof intent === "string" && { intent },
243
- ...typeof cart === "string" && { cart },
244
- ...typeof payment === "string" && { payment }
245
- }
246
- },
247
- evidence: {
248
- mandatesPresent: [
249
- typeof intent === "string" && "intent",
250
- typeof cart === "string" && "cart",
251
- typeof payment === "string" && "payment"
252
- ].filter(Boolean),
253
- ...truncated
254
- }
255
- };
256
- }
257
- }
258
- if (authHeader && /^Payment\s+/i.test(authHeader)) {
259
- return {
260
- protocol: "mpp",
261
- artifacts: {
262
- mppRequest: {
263
- method,
264
- url,
265
- headers,
266
- ...body.text && { rawBody: body.text },
267
- ...jsonBody && { body: jsonBody }
268
- }
269
- },
270
- evidence: truncated
271
- };
272
- }
273
- if (getHeader(request, "x-payment")) {
274
- return {
275
- protocol: "x402",
276
- artifacts: {
277
- x402Request: { method, url, headers, ...jsonBody && { body: jsonBody } }
278
- },
279
- evidence: truncated
280
- };
281
- }
282
- return void 0;
283
- }
284
-
285
- // src/classify.ts
286
- var STATIC_EXTENSIONS = /\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|mp4|webm|pdf|txt|xml)$/i;
287
- var BOT_UA_PATTERN = /curl|wget|python-requests|python-urllib|node-fetch|axios|got|okhttp|go-http-client|libwww|httpie|java\/|ruby|php|scrapy|headless|phantomjs|selenium|playwright|puppeteer|bot|crawler|spider|slurp/i;
288
- var BROWSER_UA_PATTERN = /mozilla\/\d/i;
289
- function resolvePolicy(config, path) {
290
- if (STATIC_EXTENSIONS.test(path)) {
291
- return { mode: config.mode, depth: config.depth, skip: true };
292
- }
293
- const rule = matchEdgePathRule(config.pathRules, path);
294
- if (!rule) return { mode: config.mode, depth: config.depth, skip: false };
295
- return {
296
- mode: rule.mode ?? config.mode,
297
- depth: rule.depth ?? config.depth,
298
- skip: rule.skip === true
299
- };
300
- }
301
- function classify(request, host, depth) {
302
- const userAgent = getHeader(request, "user-agent") ?? "";
303
- const flat = flattenHeaders(request.headers);
304
- const credentials = extractCredentials(flat, {});
305
- if (credentials.astraId || credentials.apiKey || credentials.jwt) {
306
- return { tier: "verified", protocol: "x-astra" };
307
- }
308
- const { apiKeyFormat, platformHeaders } = sanitizeHeaders2(flat);
309
- const detectionInput = { userAgent, apiKeyFormat, platformHeaders };
310
- if (depth !== "classify") {
311
- const commerce = detectCommerce(request, host, decodeBody(request));
312
- if (commerce) {
313
- return {
314
- tier: "identified",
315
- protocol: commerce.protocol,
316
- artifacts: commerce.artifacts,
317
- evidence: commerce.evidence,
318
- fingerprint: detectPlatformFingerprint(detectionInput)
319
- };
320
- }
321
- }
322
- const fingerprint = detectPlatformFingerprint(detectionInput);
323
- if (fingerprint) {
324
- return { tier: "identified", protocol: "platform-ua", fingerprint };
325
- }
326
- if (!userAgent || BOT_UA_PATTERN.test(userAgent) || !BROWSER_UA_PATTERN.test(userAgent)) {
327
- return { tier: "anonymous-bot", evidence: { userAgent: userAgent || "(none)" } };
328
- }
329
- if (!getHeader(request, "sec-fetch-mode") && !getHeader(request, "accept-language")) {
330
- return { tier: "anonymous-bot", evidence: { userAgent, spoofedBrowser: true } };
331
- }
332
- return { tier: "human" };
333
- }
334
-
335
- // src/pipeline.ts
336
- import { verify, extractCredentials as extractCredentials2 } from "@astrasyncai/verification-gateway/verify";
337
- import { resolveHttpPdlss } from "@astrasyncai/verification-gateway/http-pdlss";
338
-
339
- // src/events.ts
340
- import { reportUnregisteredAttempt } from "@astrasyncai/verification-gateway/verify";
341
- async function withBudget(promise, ms) {
342
- let timer;
343
- try {
344
- return await Promise.race([
345
- promise,
346
- new Promise((resolve) => {
347
- timer = setTimeout(() => resolve(void 0), ms);
348
- })
349
- ]);
350
- } catch {
351
- return void 0;
352
- } finally {
353
- if (timer) clearTimeout(timer);
354
- }
355
- }
356
- async function emitBeacon(options, request, classification, budgetMs) {
357
- const clientIp = getHeader(request, "cloudfront-viewer-address")?.split(":")[0];
358
- await withBudget(
359
- reportUnregisteredAttempt(
360
- { apiBaseUrl: options.apiBaseUrl, counterpartyId: options.counterpartyId },
361
- {
362
- counterpartyUrl: options.counterpartyUrl,
363
- counterpartyType: "website",
364
- sourceIp: clientIp,
365
- userAgent: getHeader(request, "user-agent"),
366
- requestPath: request.uri,
367
- requestMethod: request.method,
368
- // 3.9.0 evidence fields (backend persists them into eventData).
369
- protocol: classification.protocol,
370
- evidence: classification.evidence,
371
- // Workstream D — full sanitised header + connection capture for the
372
- // unregistered caller (fire-and-forget, so free).
373
- observedMetadata: buildObservedMetadata(request)
374
- }
375
- ),
376
- budgetMs
377
- );
378
- }
379
- function sampled(rate, random = Math.random) {
380
- if (rate <= 0) return false;
381
- if (rate >= 1) return true;
382
- return random() < rate;
383
- }
384
-
385
- // src/pipeline.ts
386
- function baseOutcome(classification) {
387
- return {
388
- tier: classification.tier,
389
- decision: "allow",
390
- reasons: [],
391
- protocol: classification.protocol
392
- };
393
- }
394
- function buildVerificationRequest(options, request, classification, includeArtifacts) {
395
- const headers = flattenHeaders(request.headers);
396
- const clientIp = getHeader(request, "cloudfront-viewer-address")?.split(":")[0];
397
- const pdlss = resolveHttpPdlss({
398
- method: request.method,
399
- astraPurpose: getHeader(request, "x-astra-purpose"),
400
- astraAction: getHeader(request, "x-astra-action")
401
- });
402
- const attemptId = getHeader(request, "x-astra-attempt-id");
403
- return {
404
- ...attemptId && /^att_[0-9a-f]{32}$/.test(attemptId) && { attemptId },
405
- credentials: extractCredentials2(headers, {}),
406
- purpose: pdlss.purpose,
407
- action: pdlss.action,
408
- resource: request.uri,
409
- createSession: true,
410
- counterpartyType: "website",
411
- counterpartyUrl: options.counterpartyUrl,
412
- callerMetadata: {
413
- sourceIp: clientIp,
414
- userAgent: getHeader(request, "user-agent"),
415
- referer: getHeader(request, "referer"),
416
- host: getHeader(request, "host"),
417
- // Workstream D — the full sanitised header + connection capture. The
418
- // backend stores it fire-and-forget (zero decision latency) and uses the
419
- // key-format / platform headers for attribution.
420
- observedMetadata: buildObservedMetadata(request)
421
- },
422
- ...includeArtifacts && classification.artifacts && { commerceArtifacts: classification.artifacts }
423
- };
424
- }
425
- function outcomeFromVerifyResult(classification, result) {
426
- const outcome = baseOutcome(classification);
427
- outcome.sessionId = result.sessionId;
428
- outcome.correlationId = result.correlationId;
429
- outcome.guidance = result.guidance;
430
- if (result.requiresStepUp || result.stepUpApproval) {
431
- outcome.decision = "manual_review";
432
- outcome.reasons = ["step-up approval required"];
433
- outcome.stepUp = {
434
- pollUrl: result.stepUpApproval?.pollUrl,
435
- expiresAt: result.stepUpApproval?.expiresAt
436
- };
437
- return outcome;
438
- }
439
- if (!result.identityVerified || !result.policyAllowed) {
440
- outcome.decision = "deny";
441
- outcome.reasons = result.denialReasons?.length ? result.denialReasons : [!result.identityVerified ? "identity not verified" : "denied by access policy"];
442
- return outcome;
443
- }
444
- outcome.asat = {
445
- trustScore: result.agent?.trustScore,
446
- agentId: result.agent?.astraId,
447
- developerId: result.developer?.astradId,
448
- accessLevel: result.accessLevel
449
- };
450
- return outcome;
451
- }
452
- async function runTier(options, request, classification, policy, apiKey, sampling) {
453
- const budgets = options.budgets ?? {};
454
- const beaconMs = budgets.beaconMs ?? 300;
455
- const verifyMs = policy.mode === "enforce" ? budgets.verifyEnforceMs ?? 3e3 : budgets.verifyObserveMs ?? 1500;
456
- const gatewayConfig = {
457
- apiBaseUrl: options.apiBaseUrl,
458
- ...apiKey && { apiKey },
459
- counterpartyId: options.counterpartyId,
460
- // The shell handles its own error semantics; init self-probes don't
461
- // belong in a per-request edge function.
462
- disableInitChecks: true
463
- };
464
- try {
465
- switch (classification.tier) {
466
- case "verified": {
467
- if (policy.depth === "classify") {
468
- return baseOutcome(classification);
469
- }
470
- const result = await withBudget(
471
- verify(
472
- gatewayConfig,
473
- buildVerificationRequest(options, request, classification, policy.depth === "authorize")
474
- ),
475
- verifyMs
476
- );
477
- if (!result) {
478
- const outcome = baseOutcome(classification);
479
- outcome.reasons = ["verify-access unreachable within budget \u2014 fail-open"];
480
- return outcome;
481
- }
482
- return outcomeFromVerifyResult(classification, result);
483
- }
484
- case "identified": {
485
- if (policy.depth === "authorize" && classification.artifacts) {
486
- const result = await withBudget(
487
- verify(gatewayConfig, buildVerificationRequest(options, request, classification, true)),
488
- verifyMs
489
- );
490
- if (!result) {
491
- const outcome2 = baseOutcome(classification);
492
- outcome2.reasons = ["verify-access unreachable within budget \u2014 fail-open"];
493
- return outcome2;
494
- }
495
- return outcomeFromVerifyResult(classification, result);
496
- }
497
- await emitBeacon(options, request, classification, beaconMs);
498
- const outcome = baseOutcome(classification);
499
- if (policy.mode === "enforce" && policy.depth !== "classify") {
500
- outcome.decision = "deny";
501
- outcome.reasons = ["agent is not registered with AstraSync"];
502
- }
503
- return outcome;
504
- }
505
- case "anonymous-bot": {
506
- if (sampled(sampling.anonymousBeaconRate, options.random)) {
507
- await emitBeacon(
508
- options,
509
- request,
510
- { ...classification, protocol: classification.protocol ?? "ua-heuristic" },
511
- beaconMs
512
- );
513
- }
514
- return baseOutcome(classification);
515
- }
516
- default:
517
- return baseOutcome(classification);
518
- }
519
- } catch (err) {
520
- const outcome = baseOutcome(classification);
521
- outcome.reasons = [
522
- `edge pipeline error \u2014 fail-open: ${err instanceof Error ? err.message : String(err)}`
523
- ];
524
- return outcome;
525
- }
526
- }
527
-
528
- // src/messaging.ts
529
- var PROTOCOL_MESSAGES = {
530
- "vi-sd-jwt": "This request presented Visa Intelligent Commerce credentials, but the agent is not verified with AstraSync. Register the agent to pair your VI credentials with a verified identity and mandate.",
531
- "rfc9421-agent-pay": "This request carried a Mastercard Agent Pay signature, but the agent is not verified with AstraSync. Register the agent to pair Agent Pay credentials with a verified identity and mandate.",
532
- "rfc9421-tap": "This request carried a Visa TAP signature, but the agent is not verified with AstraSync. Register the agent to pair TAP credentials with a verified identity and mandate.",
533
- "rfc9421-web-bot-auth": "This request carried a Web Bot Auth signature, but the agent is not verified with AstraSync. Register the agent to link your signed-agent identity to a verified principal.",
534
- rfc9421: "This request carried an RFC 9421 HTTP message signature, but the agent is not verified with AstraSync. Register the agent to link the signing identity to a verified principal.",
535
- acp: "This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
536
- ucp: "This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
537
- ap2: "This request presented AP2 mandates, but the agent is not verified with AstraSync. Register the agent to pair your mandates with a verified identity.",
538
- mpp: "This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
539
- x402: "This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
540
- "platform-ua": "This traffic was identified as a platform AI agent without AstraSync credentials. Register the agent to access this property with a verified identity.",
541
- "x-astra": "The presented AstraSync credentials failed verification or were denied by this property\u2019s access policy."
542
- };
543
- function buildDenyBody(outcome, apiBaseUrl) {
544
- const origin = apiBaseUrl.replace(/\/api\/?$/, "");
545
- const protocolMessage = (outcome.protocol && PROTOCOL_MESSAGES[outcome.protocol]) ?? "This request could not be verified by AstraSync.";
546
- return {
547
- success: false,
548
- error: {
549
- // UNAUTHORIZED = identity failed (register/re-authenticate helps);
550
- // INSUFFICIENT_ACCESS = identity fine, policy denied (fix the mandate).
551
- code: outcome.tier === "verified" ? "INSUFFICIENT_ACCESS" : "UNAUTHORIZED",
552
- message: protocolMessage,
553
- ...outcome.protocol && { protocol: outcome.protocol },
554
- failures: outcome.reasons,
555
- ...outcome.correlationId && { correlationId: outcome.correlationId },
556
- guidance: {
557
- // `||` not `??`: verify() fills these with EMPTY STRINGS when the
558
- // well-known cache is cold — empty means "use the fallback".
559
- message: outcome.guidance?.message || "Register this agent with AstraSync to receive verifiable credentials.",
560
- registrationUrl: outcome.guidance?.registrationUrl || `${origin}/register`,
561
- documentationUrl: outcome.guidance?.documentationUrl || `${origin}/docs/edge-adapter`
562
- }
563
- }
564
- };
565
- }
566
- function buildManualReviewBody(outcome) {
567
- return {
568
- success: false,
569
- status: "manual_review",
570
- message: "This action requires human approval. Poll the step-up approval endpoint and retry once approved.",
571
- ...outcome.stepUp && { stepUpApproval: outcome.stepUp },
572
- ...outcome.correlationId && { correlationId: outcome.correlationId }
573
- };
574
- }
575
-
576
- // src/enforce.ts
577
- var ASAT_HEADERS = {
578
- trustScore: "X-AstraSync-Trust-Score",
579
- agentId: "X-AstraSync-Agent-Id",
580
- developerId: "X-AstraSync-Developer-Id",
581
- permissions: "X-AstraSync-Permissions",
582
- observedDecision: "X-AstraSync-Observed-Decision"
583
- };
584
- function applyOutcome(options, request, outcome, policy) {
585
- stripHeadersByPrefix(request, "x-astrasync-");
586
- if (policy.mode !== "enforce") {
587
- if (outcome.decision !== "allow") {
588
- setHeader(request, ASAT_HEADERS.observedDecision, outcome.decision);
589
- }
590
- injectAsat(request, outcome);
591
- return request;
592
- }
593
- switch (outcome.decision) {
594
- case "deny":
595
- return jsonResponse(403, buildDenyBody(outcome, options.apiBaseUrl));
596
- case "manual_review":
597
- return jsonResponse(202, buildManualReviewBody(outcome), {
598
- "Retry-After": "30"
599
- });
600
- default:
601
- injectAsat(request, outcome);
602
- return request;
603
- }
604
- }
605
- function injectAsat(request, outcome) {
606
- if (!outcome.asat) return;
607
- const { trustScore, agentId, developerId, accessLevel } = outcome.asat;
608
- if (trustScore !== void 0) {
609
- setHeader(request, ASAT_HEADERS.trustScore, String(trustScore));
610
- }
611
- if (agentId) setHeader(request, ASAT_HEADERS.agentId, agentId);
612
- if (developerId) setHeader(request, ASAT_HEADERS.developerId, developerId);
613
- if (accessLevel) setHeader(request, ASAT_HEADERS.permissions, accessLevel);
614
- }
615
-
616
171
  // src/handler.ts
617
172
  function createEdgeHandler(options) {
618
173
  const log = options.log ?? ((level, message, data) => {
@@ -624,27 +179,13 @@ function createEdgeHandler(options) {
624
179
  normalizeOriginHost(request);
625
180
  const apiKey = await resolveApiKey({ ...options, log });
626
181
  const config = await loadEdgeConfig(options, apiKey);
627
- const policy = resolvePolicy(config, request.uri);
628
- if (policy.skip) return request;
629
- const host = getHeader(request, "x-forwarded-host") ?? getHeader(request, "host") ?? new URL(options.counterpartyUrl).host;
630
- const classification = classify(request, host, policy.depth);
631
- if (classification.tier === "human") return request;
632
- const outcome = await runTier(
182
+ const { application } = await evaluateEdgeRequest(
633
183
  { ...options, log },
634
- request,
635
- classification,
636
- policy,
637
- apiKey,
638
- config.sampling
184
+ toNormalizedRequest(request),
185
+ config,
186
+ apiKey
639
187
  );
640
- if (outcome.decision !== "allow") {
641
- log(
642
- "info",
643
- policy.mode === "enforce" ? `${outcome.decision.toUpperCase()}: ${request.method} ${request.uri}` : `[OBSERVE] would have been ${outcome.decision.toUpperCase()}: ${request.method} ${request.uri}`,
644
- { tier: outcome.tier, protocol: outcome.protocol, reasons: outcome.reasons }
645
- );
646
- }
647
- return applyOutcome(options, request, outcome, policy);
188
+ return applyCoreOutcome(request, application);
648
189
  } catch (err) {
649
190
  log("error", "edge handler error \u2014 passing request through", {
650
191
  error: err instanceof Error ? err.message : String(err)
@@ -653,6 +194,70 @@ function createEdgeHandler(options) {
653
194
  }
654
195
  };
655
196
  }
197
+
198
+ // src/classify.ts
199
+ import {
200
+ classify as classifyCore,
201
+ resolvePolicy,
202
+ _patterns
203
+ } from "@astrasyncai/verification-gateway/edge-core";
204
+ function classify(request, host, depth) {
205
+ return classifyCore(toNormalizedRequest(request), host, depth);
206
+ }
207
+
208
+ // src/detect.ts
209
+ import {
210
+ detectCommerce as detectCommerceCore
211
+ } from "@astrasyncai/verification-gateway/edge-core";
212
+ function detectCommerce(request, host, body) {
213
+ const normalized = toNormalizedRequest(request);
214
+ return detectCommerceCore(
215
+ {
216
+ ...normalized,
217
+ bodyText: body.text,
218
+ bodyTruncated: body.truncated
219
+ },
220
+ host
221
+ );
222
+ }
223
+
224
+ // src/pipeline.ts
225
+ import { runTier as runTierCore } from "@astrasyncai/verification-gateway/edge-core";
226
+ async function runTier(options, request, classification, policy, apiKey, sampling) {
227
+ return runTierCore(
228
+ options,
229
+ toNormalizedRequest(request),
230
+ classification,
231
+ policy,
232
+ apiKey,
233
+ sampling
234
+ );
235
+ }
236
+
237
+ // src/enforce.ts
238
+ import {
239
+ applyOutcome as resolveOutcomeApplication,
240
+ ASAT_HEADERS
241
+ } from "@astrasyncai/verification-gateway/edge-core";
242
+ function applyOutcome(options, request, outcome, policy) {
243
+ return applyCoreOutcome(request, resolveOutcomeApplication(options, outcome, policy));
244
+ }
245
+
246
+ // src/messaging.ts
247
+ import {
248
+ buildDenyBody,
249
+ buildManualReviewBody
250
+ } from "@astrasyncai/verification-gateway/edge-core";
251
+
252
+ // src/events.ts
253
+ import {
254
+ emitBeacon as emitBeaconCore,
255
+ withBudget,
256
+ sampled
257
+ } from "@astrasyncai/verification-gateway/edge-core";
258
+ async function emitBeacon(options, request, classification, budgetMs) {
259
+ await emitBeaconCore(options, toNormalizedRequest(request), classification, budgetMs);
260
+ }
656
261
  export {
657
262
  ASAT_HEADERS,
658
263
  _resetConfigCaches,