@astrasyncai/adapter-lambda 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/dist/index.js ADDED
@@ -0,0 +1,671 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ ASAT_HEADERS: () => ASAT_HEADERS,
34
+ _resetConfigCaches: () => _resetConfigCaches,
35
+ applyOutcome: () => applyOutcome,
36
+ buildDenyBody: () => buildDenyBody,
37
+ buildManualReviewBody: () => buildManualReviewBody,
38
+ classify: () => classify,
39
+ createEdgeHandler: () => createEdgeHandler,
40
+ decodeBody: () => decodeBody,
41
+ detectCommerce: () => detectCommerce,
42
+ emitBeacon: () => emitBeacon,
43
+ flattenHeaders: () => flattenHeaders,
44
+ getHeader: () => getHeader,
45
+ getRequest: () => getRequest,
46
+ jsonResponse: () => jsonResponse,
47
+ loadEdgeConfig: () => loadEdgeConfig,
48
+ requestUrl: () => requestUrl,
49
+ resolveApiKey: () => resolveApiKey,
50
+ resolvePolicy: () => resolvePolicy,
51
+ runTier: () => runTier,
52
+ sampled: () => sampled,
53
+ setHeader: () => setHeader,
54
+ stripHeadersByPrefix: () => stripHeadersByPrefix,
55
+ withBudget: () => withBudget
56
+ });
57
+ module.exports = __toCommonJS(src_exports);
58
+
59
+ // src/cf.ts
60
+ function getRequest(event) {
61
+ return event.Records[0].cf.request;
62
+ }
63
+ function getHeader(request, name) {
64
+ return request.headers[name.toLowerCase()]?.[0]?.value;
65
+ }
66
+ function flattenHeaders(headers) {
67
+ const out = {};
68
+ for (const [name, entries] of Object.entries(headers)) {
69
+ if (!entries?.length) continue;
70
+ out[name] = entries.length === 1 ? entries[0].value : entries.map((e) => e.value);
71
+ }
72
+ return out;
73
+ }
74
+ function decodeBody(request) {
75
+ const body = request.body;
76
+ if (!body?.data) return { truncated: false };
77
+ const text = body.encoding === "base64" ? Buffer.from(body.data, "base64").toString("utf8") : body.data;
78
+ return { text, truncated: body.inputTruncated === true };
79
+ }
80
+ function requestUrl(request, host) {
81
+ const qs = request.querystring ? `?${request.querystring}` : "";
82
+ return `https://${host}${request.uri}${qs}`;
83
+ }
84
+ function setHeader(request, name, value) {
85
+ request.headers[name.toLowerCase()] = [{ key: name, value }];
86
+ }
87
+ function stripHeadersByPrefix(request, prefix) {
88
+ const p = prefix.toLowerCase();
89
+ for (const name of Object.keys(request.headers)) {
90
+ if (name.startsWith(p)) delete request.headers[name];
91
+ }
92
+ }
93
+ function jsonResponse(status, body, extraHeaders) {
94
+ const headers = {
95
+ "content-type": [{ key: "Content-Type", value: "application/json" }]
96
+ };
97
+ for (const [name, value] of Object.entries(extraHeaders ?? {})) {
98
+ headers[name.toLowerCase()] = [{ key: name, value }];
99
+ }
100
+ return {
101
+ status: String(status),
102
+ statusDescription: status === 403 ? "Forbidden" : status === 202 ? "Accepted" : "OK",
103
+ headers,
104
+ body: JSON.stringify(body)
105
+ };
106
+ }
107
+
108
+ // src/config.ts
109
+ var import_edge_config = require("@astrasyncai/verification-gateway/edge-config");
110
+ var SECRET_TTL_MS = 15 * 60 * 1e3;
111
+ var secretCache = /* @__PURE__ */ new Map();
112
+ async function defaultFetchSecret(secretName) {
113
+ const { SecretsManagerClient, GetSecretValueCommand } = await import("@aws-sdk/client-secrets-manager");
114
+ const client = new SecretsManagerClient({ region: "us-east-1" });
115
+ const result = await client.send(new GetSecretValueCommand({ SecretId: secretName }));
116
+ return result.SecretString ?? void 0;
117
+ }
118
+ async function resolveApiKey(options) {
119
+ if (options.apiKey) return options.apiKey;
120
+ const secretName = options.apiKeySecretName;
121
+ if (!secretName) return void 0;
122
+ const cached = secretCache.get(secretName);
123
+ if (cached && Date.now() - cached.fetchedAt < SECRET_TTL_MS) return cached.value;
124
+ try {
125
+ const fetcher = options.fetchSecret ?? defaultFetchSecret;
126
+ const value = await fetcher(secretName);
127
+ secretCache.set(secretName, { value, fetchedAt: Date.now() });
128
+ return value;
129
+ } catch (err) {
130
+ options.log?.("warn", "Secrets Manager fetch failed \u2014 continuing keyless", {
131
+ secretName,
132
+ error: err instanceof Error ? err.message : String(err)
133
+ });
134
+ return cached?.value;
135
+ }
136
+ }
137
+ async function loadEdgeConfig(options, apiKey) {
138
+ try {
139
+ return await (0, import_edge_config.getEdgeConfig)({ apiBaseUrl: options.apiBaseUrl, apiKey }, options.counterpartyId, {
140
+ ttlMs: options.configTtlMs
141
+ });
142
+ } catch {
143
+ return options.fallbackConfig ?? import_edge_config.DEFAULT_EDGE_CONFIG;
144
+ }
145
+ }
146
+ function _resetConfigCaches() {
147
+ secretCache.clear();
148
+ }
149
+
150
+ // src/classify.ts
151
+ var import_verify = require("@astrasyncai/verification-gateway/verify");
152
+ var import_platform_signatures = require("@astrasyncai/verification-gateway/platform-signatures");
153
+ var import_edge_config2 = require("@astrasyncai/verification-gateway/edge-config");
154
+
155
+ // src/detect.ts
156
+ var SD_JWT_PATTERN = /^eyJ[\w-]+\.[\w-]*\.[\w-]+~/;
157
+ function sniffJwtHeader(compact) {
158
+ try {
159
+ const seg = compact.split(".")[0];
160
+ return JSON.parse(Buffer.from(seg, "base64url").toString("utf8"));
161
+ } catch {
162
+ return void 0;
163
+ }
164
+ }
165
+ function parseJsonBody(body) {
166
+ if (!body.text) return void 0;
167
+ try {
168
+ const parsed = JSON.parse(body.text);
169
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
170
+ } catch {
171
+ return void 0;
172
+ }
173
+ }
174
+ function detectCommerce(request, host, body) {
175
+ const url = requestUrl(request, host);
176
+ const method = request.method;
177
+ const headers = flattenHeaders(request.headers);
178
+ const jsonBody = parseJsonBody(body);
179
+ const truncated = body.truncated ? { bodyTruncated: true } : {};
180
+ const authHeader = getHeader(request, "authorization");
181
+ const bearer = authHeader?.replace(/^Bearer\s+/i, "");
182
+ const mandateHeader = getHeader(request, "x-payment-mandate") ?? getHeader(request, "payment-mandate");
183
+ const sdJwtCandidate = [mandateHeader, bearer].find((v) => v && SD_JWT_PATTERN.test(v));
184
+ if (sdJwtCandidate) {
185
+ const typ = sniffJwtHeader(sdJwtCandidate)?.typ;
186
+ return {
187
+ protocol: "vi-sd-jwt",
188
+ artifacts: { viSdJwt: sdJwtCandidate },
189
+ evidence: { typ, ...truncated }
190
+ };
191
+ }
192
+ const signature = getHeader(request, "signature");
193
+ const signatureInput = getHeader(request, "signature-input");
194
+ if (signature && signatureInput) {
195
+ const signatureAgent = getHeader(request, "signature-agent");
196
+ const registryHint = getHeader(request, "x-agent-registry");
197
+ const lowerInput = signatureInput.toLowerCase();
198
+ 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";
199
+ return {
200
+ protocol,
201
+ artifacts: {
202
+ rfc9421: { headers, method, url, ...body.text && { body: body.text } }
203
+ },
204
+ evidence: {
205
+ ...signatureAgent && { signatureAgent },
206
+ ...registryHint && { registryHint },
207
+ keyid: signatureInput.match(/keyid="([^"]+)"/)?.[1],
208
+ ...truncated
209
+ }
210
+ };
211
+ }
212
+ const acpTimestamp = getHeader(request, "timestamp");
213
+ if (signature && !signatureInput && (acpTimestamp || getHeader(request, "idempotency-key"))) {
214
+ return {
215
+ protocol: "acp",
216
+ artifacts: {
217
+ acpRequest: {
218
+ method,
219
+ url,
220
+ headers,
221
+ ...body.text && { rawBody: body.text },
222
+ ...jsonBody && { body: jsonBody }
223
+ }
224
+ },
225
+ evidence: { hasTimestamp: Boolean(acpTimestamp), ...truncated }
226
+ };
227
+ }
228
+ if (/\/checkout[-_]sessions(\/|$)/.test(request.uri)) {
229
+ return {
230
+ protocol: "ucp",
231
+ artifacts: { ucpRequest: { method, url, ...jsonBody && { body: jsonBody } } },
232
+ evidence: { path: request.uri, ...truncated }
233
+ };
234
+ }
235
+ if (jsonBody) {
236
+ const intent = jsonBody.intent_mandate ?? jsonBody.intentMandate;
237
+ const cart = jsonBody.cart_mandate ?? jsonBody.cartMandate;
238
+ const payment = jsonBody.payment_mandate ?? jsonBody.paymentMandate;
239
+ if (typeof intent === "string" || typeof cart === "string" || typeof payment === "string") {
240
+ return {
241
+ protocol: "ap2",
242
+ artifacts: {
243
+ ap2Mandates: {
244
+ ...typeof intent === "string" && { intent },
245
+ ...typeof cart === "string" && { cart },
246
+ ...typeof payment === "string" && { payment }
247
+ }
248
+ },
249
+ evidence: {
250
+ mandatesPresent: [
251
+ typeof intent === "string" && "intent",
252
+ typeof cart === "string" && "cart",
253
+ typeof payment === "string" && "payment"
254
+ ].filter(Boolean),
255
+ ...truncated
256
+ }
257
+ };
258
+ }
259
+ }
260
+ if (authHeader && /^Payment\s+/i.test(authHeader)) {
261
+ return {
262
+ protocol: "mpp",
263
+ artifacts: {
264
+ mppRequest: {
265
+ method,
266
+ url,
267
+ headers,
268
+ ...body.text && { rawBody: body.text },
269
+ ...jsonBody && { body: jsonBody }
270
+ }
271
+ },
272
+ evidence: truncated
273
+ };
274
+ }
275
+ if (getHeader(request, "x-payment")) {
276
+ return {
277
+ protocol: "x402",
278
+ artifacts: {
279
+ x402Request: { method, url, headers, ...jsonBody && { body: jsonBody } }
280
+ },
281
+ evidence: truncated
282
+ };
283
+ }
284
+ return void 0;
285
+ }
286
+
287
+ // src/classify.ts
288
+ 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;
289
+ 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;
290
+ var BROWSER_UA_PATTERN = /mozilla\/\d/i;
291
+ function resolvePolicy(config, path) {
292
+ if (STATIC_EXTENSIONS.test(path)) {
293
+ return { mode: config.mode, depth: config.depth, skip: true };
294
+ }
295
+ const rule = (0, import_edge_config2.matchEdgePathRule)(config.pathRules, path);
296
+ if (!rule) return { mode: config.mode, depth: config.depth, skip: false };
297
+ return {
298
+ mode: rule.mode ?? config.mode,
299
+ depth: rule.depth ?? config.depth,
300
+ skip: rule.skip === true
301
+ };
302
+ }
303
+ function classify(request, host, depth) {
304
+ const userAgent = getHeader(request, "user-agent") ?? "";
305
+ const credentials = (0, import_verify.extractCredentials)(flattenHeaders(request.headers), {});
306
+ if (credentials.astraId || credentials.apiKey || credentials.jwt) {
307
+ return { tier: "verified", protocol: "x-astra" };
308
+ }
309
+ if (depth !== "classify") {
310
+ const commerce = detectCommerce(request, host, decodeBody(request));
311
+ if (commerce) {
312
+ return {
313
+ tier: "identified",
314
+ protocol: commerce.protocol,
315
+ artifacts: commerce.artifacts,
316
+ evidence: commerce.evidence,
317
+ fingerprint: (0, import_platform_signatures.detectPlatformFingerprint)({ userAgent })
318
+ };
319
+ }
320
+ }
321
+ const fingerprint = (0, import_platform_signatures.detectPlatformFingerprint)({ userAgent });
322
+ if (fingerprint) {
323
+ return { tier: "identified", protocol: "platform-ua", fingerprint };
324
+ }
325
+ if (!userAgent || BOT_UA_PATTERN.test(userAgent) || !BROWSER_UA_PATTERN.test(userAgent)) {
326
+ return { tier: "anonymous-bot", evidence: { userAgent: userAgent || "(none)" } };
327
+ }
328
+ if (!getHeader(request, "sec-fetch-mode") && !getHeader(request, "accept-language")) {
329
+ return { tier: "anonymous-bot", evidence: { userAgent, spoofedBrowser: true } };
330
+ }
331
+ return { tier: "human" };
332
+ }
333
+
334
+ // src/pipeline.ts
335
+ var import_verify3 = require("@astrasyncai/verification-gateway/verify");
336
+ var import_http_pdlss = require("@astrasyncai/verification-gateway/http-pdlss");
337
+
338
+ // src/events.ts
339
+ var import_verify2 = require("@astrasyncai/verification-gateway/verify");
340
+ async function withBudget(promise, ms) {
341
+ let timer;
342
+ try {
343
+ return await Promise.race([
344
+ promise,
345
+ new Promise((resolve) => {
346
+ timer = setTimeout(() => resolve(void 0), ms);
347
+ })
348
+ ]);
349
+ } catch {
350
+ return void 0;
351
+ } finally {
352
+ if (timer) clearTimeout(timer);
353
+ }
354
+ }
355
+ async function emitBeacon(options, request, classification, budgetMs) {
356
+ const clientIp = getHeader(request, "cloudfront-viewer-address")?.split(":")[0];
357
+ await withBudget(
358
+ (0, import_verify2.reportUnregisteredAttempt)(
359
+ { apiBaseUrl: options.apiBaseUrl, counterpartyId: options.counterpartyId },
360
+ {
361
+ counterpartyUrl: options.counterpartyUrl,
362
+ counterpartyType: "website",
363
+ sourceIp: clientIp,
364
+ userAgent: getHeader(request, "user-agent"),
365
+ requestPath: request.uri,
366
+ requestMethod: request.method,
367
+ // 3.9.0 evidence fields (backend persists them into eventData).
368
+ protocol: classification.protocol,
369
+ evidence: classification.evidence
370
+ }
371
+ ),
372
+ budgetMs
373
+ );
374
+ }
375
+ function sampled(rate, random = Math.random) {
376
+ if (rate <= 0) return false;
377
+ if (rate >= 1) return true;
378
+ return random() < rate;
379
+ }
380
+
381
+ // src/pipeline.ts
382
+ function baseOutcome(classification) {
383
+ return {
384
+ tier: classification.tier,
385
+ decision: "allow",
386
+ reasons: [],
387
+ protocol: classification.protocol
388
+ };
389
+ }
390
+ function buildVerificationRequest(options, request, classification, includeArtifacts) {
391
+ const headers = flattenHeaders(request.headers);
392
+ const clientIp = getHeader(request, "cloudfront-viewer-address")?.split(":")[0];
393
+ const pdlss = (0, import_http_pdlss.resolveHttpPdlss)({
394
+ method: request.method,
395
+ astraPurpose: getHeader(request, "x-astra-purpose"),
396
+ astraAction: getHeader(request, "x-astra-action")
397
+ });
398
+ return {
399
+ credentials: (0, import_verify3.extractCredentials)(headers, {}),
400
+ purpose: pdlss.purpose,
401
+ action: pdlss.action,
402
+ resource: request.uri,
403
+ createSession: true,
404
+ counterpartyType: "website",
405
+ counterpartyUrl: options.counterpartyUrl,
406
+ callerMetadata: {
407
+ sourceIp: clientIp,
408
+ userAgent: getHeader(request, "user-agent"),
409
+ referer: getHeader(request, "referer"),
410
+ host: getHeader(request, "host")
411
+ },
412
+ ...includeArtifacts && classification.artifacts && { commerceArtifacts: classification.artifacts }
413
+ };
414
+ }
415
+ function outcomeFromVerifyResult(classification, result) {
416
+ const outcome = baseOutcome(classification);
417
+ outcome.sessionId = result.sessionId;
418
+ outcome.correlationId = result.correlationId;
419
+ outcome.guidance = result.guidance;
420
+ if (result.requiresStepUp || result.stepUpApproval) {
421
+ outcome.decision = "manual_review";
422
+ outcome.reasons = ["step-up approval required"];
423
+ outcome.stepUp = {
424
+ pollUrl: result.stepUpApproval?.pollUrl,
425
+ expiresAt: result.stepUpApproval?.expiresAt
426
+ };
427
+ return outcome;
428
+ }
429
+ if (!result.identityVerified || !result.policyAllowed) {
430
+ outcome.decision = "deny";
431
+ outcome.reasons = result.denialReasons?.length ? result.denialReasons : [!result.identityVerified ? "identity not verified" : "denied by access policy"];
432
+ return outcome;
433
+ }
434
+ outcome.asat = {
435
+ trustScore: result.agent?.trustScore,
436
+ agentId: result.agent?.astraId,
437
+ developerId: result.developer?.astradId,
438
+ accessLevel: result.accessLevel
439
+ };
440
+ return outcome;
441
+ }
442
+ async function runTier(options, request, classification, policy, apiKey, sampling) {
443
+ const budgets = options.budgets ?? {};
444
+ const beaconMs = budgets.beaconMs ?? 300;
445
+ const verifyMs = policy.mode === "enforce" ? budgets.verifyEnforceMs ?? 3e3 : budgets.verifyObserveMs ?? 1500;
446
+ const gatewayConfig = {
447
+ apiBaseUrl: options.apiBaseUrl,
448
+ ...apiKey && { apiKey },
449
+ counterpartyId: options.counterpartyId,
450
+ // The shell handles its own error semantics; init self-probes don't
451
+ // belong in a per-request edge function.
452
+ disableInitChecks: true
453
+ };
454
+ try {
455
+ switch (classification.tier) {
456
+ case "verified": {
457
+ if (policy.depth === "classify") {
458
+ return baseOutcome(classification);
459
+ }
460
+ const result = await withBudget(
461
+ (0, import_verify3.verify)(
462
+ gatewayConfig,
463
+ buildVerificationRequest(options, request, classification, policy.depth === "authorize")
464
+ ),
465
+ verifyMs
466
+ );
467
+ if (!result) {
468
+ const outcome = baseOutcome(classification);
469
+ outcome.reasons = ["verify-access unreachable within budget \u2014 fail-open"];
470
+ return outcome;
471
+ }
472
+ return outcomeFromVerifyResult(classification, result);
473
+ }
474
+ case "identified": {
475
+ if (policy.depth === "authorize" && classification.artifacts) {
476
+ const result = await withBudget(
477
+ (0, import_verify3.verify)(gatewayConfig, buildVerificationRequest(options, request, classification, true)),
478
+ verifyMs
479
+ );
480
+ if (!result) {
481
+ const outcome2 = baseOutcome(classification);
482
+ outcome2.reasons = ["verify-access unreachable within budget \u2014 fail-open"];
483
+ return outcome2;
484
+ }
485
+ return outcomeFromVerifyResult(classification, result);
486
+ }
487
+ await emitBeacon(options, request, classification, beaconMs);
488
+ const outcome = baseOutcome(classification);
489
+ if (policy.mode === "enforce" && policy.depth !== "classify") {
490
+ outcome.decision = "deny";
491
+ outcome.reasons = ["agent is not registered with AstraSync"];
492
+ }
493
+ return outcome;
494
+ }
495
+ case "anonymous-bot": {
496
+ if (sampled(sampling.anonymousBeaconRate, options.random)) {
497
+ await emitBeacon(
498
+ options,
499
+ request,
500
+ { ...classification, protocol: classification.protocol ?? "ua-heuristic" },
501
+ beaconMs
502
+ );
503
+ }
504
+ return baseOutcome(classification);
505
+ }
506
+ default:
507
+ return baseOutcome(classification);
508
+ }
509
+ } catch (err) {
510
+ const outcome = baseOutcome(classification);
511
+ outcome.reasons = [
512
+ `edge pipeline error \u2014 fail-open: ${err instanceof Error ? err.message : String(err)}`
513
+ ];
514
+ return outcome;
515
+ }
516
+ }
517
+
518
+ // src/messaging.ts
519
+ var PROTOCOL_MESSAGES = {
520
+ "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.",
521
+ "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.",
522
+ "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.",
523
+ "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.",
524
+ 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.",
525
+ acp: "This request used the Agentic Commerce Protocol, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
526
+ ucp: "This request used a UCP checkout session, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
527
+ 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.",
528
+ mpp: "This request presented MPP payment credentials, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
529
+ x402: "This request used x402 payment headers, but the agent is not verified with AstraSync. Register the agent to transact on this property.",
530
+ "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.",
531
+ "x-astra": "The presented AstraSync credentials failed verification or were denied by this property\u2019s access policy."
532
+ };
533
+ function buildDenyBody(outcome, apiBaseUrl) {
534
+ const origin = apiBaseUrl.replace(/\/api\/?$/, "");
535
+ const protocolMessage = (outcome.protocol && PROTOCOL_MESSAGES[outcome.protocol]) ?? "This request could not be verified by AstraSync.";
536
+ return {
537
+ success: false,
538
+ error: {
539
+ // UNAUTHORIZED = identity failed (register/re-authenticate helps);
540
+ // INSUFFICIENT_ACCESS = identity fine, policy denied (fix the mandate).
541
+ code: outcome.tier === "verified" ? "INSUFFICIENT_ACCESS" : "UNAUTHORIZED",
542
+ message: protocolMessage,
543
+ ...outcome.protocol && { protocol: outcome.protocol },
544
+ failures: outcome.reasons,
545
+ ...outcome.correlationId && { correlationId: outcome.correlationId },
546
+ guidance: {
547
+ // `||` not `??`: verify() fills these with EMPTY STRINGS when the
548
+ // well-known cache is cold — empty means "use the fallback".
549
+ message: outcome.guidance?.message || "Register this agent with AstraSync to receive verifiable credentials.",
550
+ registrationUrl: outcome.guidance?.registrationUrl || `${origin}/register`,
551
+ documentationUrl: outcome.guidance?.documentationUrl || `${origin}/docs/edge-adapter`
552
+ }
553
+ }
554
+ };
555
+ }
556
+ function buildManualReviewBody(outcome) {
557
+ return {
558
+ success: false,
559
+ status: "manual_review",
560
+ message: "This action requires human approval. Poll the step-up approval endpoint and retry once approved.",
561
+ ...outcome.stepUp && { stepUpApproval: outcome.stepUp },
562
+ ...outcome.correlationId && { correlationId: outcome.correlationId }
563
+ };
564
+ }
565
+
566
+ // src/enforce.ts
567
+ var ASAT_HEADERS = {
568
+ trustScore: "X-AstraSync-Trust-Score",
569
+ agentId: "X-AstraSync-Agent-Id",
570
+ developerId: "X-AstraSync-Developer-Id",
571
+ permissions: "X-AstraSync-Permissions",
572
+ observedDecision: "X-AstraSync-Observed-Decision"
573
+ };
574
+ function applyOutcome(options, request, outcome, policy) {
575
+ stripHeadersByPrefix(request, "x-astrasync-");
576
+ if (policy.mode !== "enforce") {
577
+ if (outcome.decision !== "allow") {
578
+ setHeader(request, ASAT_HEADERS.observedDecision, outcome.decision);
579
+ }
580
+ injectAsat(request, outcome);
581
+ return request;
582
+ }
583
+ switch (outcome.decision) {
584
+ case "deny":
585
+ return jsonResponse(403, buildDenyBody(outcome, options.apiBaseUrl));
586
+ case "manual_review":
587
+ return jsonResponse(202, buildManualReviewBody(outcome), {
588
+ "Retry-After": "30"
589
+ });
590
+ default:
591
+ injectAsat(request, outcome);
592
+ return request;
593
+ }
594
+ }
595
+ function injectAsat(request, outcome) {
596
+ if (!outcome.asat) return;
597
+ const { trustScore, agentId, developerId, accessLevel } = outcome.asat;
598
+ if (trustScore !== void 0) {
599
+ setHeader(request, ASAT_HEADERS.trustScore, String(trustScore));
600
+ }
601
+ if (agentId) setHeader(request, ASAT_HEADERS.agentId, agentId);
602
+ if (developerId) setHeader(request, ASAT_HEADERS.developerId, developerId);
603
+ if (accessLevel) setHeader(request, ASAT_HEADERS.permissions, accessLevel);
604
+ }
605
+
606
+ // src/handler.ts
607
+ function createEdgeHandler(options) {
608
+ const log = options.log ?? ((level, message, data) => {
609
+ console[level === "info" ? "log" : level](`[astrasync-edge] ${message}`, data ?? "");
610
+ });
611
+ return async function handler(event) {
612
+ const request = getRequest(event);
613
+ try {
614
+ const apiKey = await resolveApiKey({ ...options, log });
615
+ const config = await loadEdgeConfig(options, apiKey);
616
+ const policy = resolvePolicy(config, request.uri);
617
+ if (policy.skip) return request;
618
+ const host = getHeader(request, "x-forwarded-host") ?? getHeader(request, "host") ?? new URL(options.counterpartyUrl).host;
619
+ const classification = classify(request, host, policy.depth);
620
+ if (classification.tier === "human") return request;
621
+ const outcome = await runTier(
622
+ { ...options, log },
623
+ request,
624
+ classification,
625
+ policy,
626
+ apiKey,
627
+ config.sampling
628
+ );
629
+ if (outcome.decision !== "allow") {
630
+ log(
631
+ "info",
632
+ policy.mode === "enforce" ? `${outcome.decision.toUpperCase()}: ${request.method} ${request.uri}` : `[OBSERVE] would have been ${outcome.decision.toUpperCase()}: ${request.method} ${request.uri}`,
633
+ { tier: outcome.tier, protocol: outcome.protocol, reasons: outcome.reasons }
634
+ );
635
+ }
636
+ return applyOutcome(options, request, outcome, policy);
637
+ } catch (err) {
638
+ log("error", "edge handler error \u2014 passing request through", {
639
+ error: err instanceof Error ? err.message : String(err)
640
+ });
641
+ return request;
642
+ }
643
+ };
644
+ }
645
+ // Annotate the CommonJS export names for ESM import in node:
646
+ 0 && (module.exports = {
647
+ ASAT_HEADERS,
648
+ _resetConfigCaches,
649
+ applyOutcome,
650
+ buildDenyBody,
651
+ buildManualReviewBody,
652
+ classify,
653
+ createEdgeHandler,
654
+ decodeBody,
655
+ detectCommerce,
656
+ emitBeacon,
657
+ flattenHeaders,
658
+ getHeader,
659
+ getRequest,
660
+ jsonResponse,
661
+ loadEdgeConfig,
662
+ requestUrl,
663
+ resolveApiKey,
664
+ resolvePolicy,
665
+ runTier,
666
+ sampled,
667
+ setHeader,
668
+ stripHeadersByPrefix,
669
+ withBudget
670
+ });
671
+ //# sourceMappingURL=index.js.map