autotel-backends 2.14.19 → 2.15.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 CHANGED
@@ -217,6 +217,37 @@ init(
217
217
 
218
218
  [View full Langfuse configuration options →](./src/langfuse.ts)
219
219
 
220
+ ## Browser export: `otlpRelay`
221
+
222
+ A backend that authenticates OTLP with a secret key (Datadog, Honeycomb,
223
+ Grafana) cannot take spans straight from a page: the key would ship to every
224
+ visitor, and most intakes refuse browser requests anyway. Point `autotel-web`
225
+ at your own origin and relay from the server, adding the key there. It takes
226
+ any preset in this package as-is:
227
+
228
+ ```typescript
229
+ import { otlpRelay } from 'autotel-backends/relay';
230
+ import { createDatadogConfig } from 'autotel-backends/datadog';
231
+
232
+ const relay = otlpRelay(
233
+ createDatadogConfig({ apiKey, site: 'datadoghq.eu', service: 'web' }),
234
+ );
235
+
236
+ // Hono, Next.js route handlers, Workers: anything with Request/Response
237
+ app.post('/otel/v1/*', (c) => relay(c.req.raw));
238
+ ```
239
+
240
+ ```typescript
241
+ // browser
242
+ initFull({ service: 'web', endpoint: '/otel' });
243
+ ```
244
+
245
+ It forwards `/v1/traces` and `/v1/logs` only, from the page's own origin only
246
+ (`allowedOrigins` adds others, with CORS), bodies up to `maxBodyBytes` (1 MiB),
247
+ and only `content-type` / `content-encoding` from the request: never cookies.
248
+ The backend's status comes back (so the exporter's retries work), its body
249
+ does not.
250
+
220
251
  ## Why Use Backend Configs?
221
252
 
222
253
  ### Without backend configs (manual):
package/dist/grafana.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_headers = require("./headers--QWNf7Su.cjs");
2
3
  let node_module = require("node:module");
3
4
  //#region src/grafana.ts
4
5
  /**
@@ -23,20 +24,6 @@ let node_module = require("node:module");
23
24
  * }));
24
25
  * ```
25
26
  */
26
- function normalizeHeaders(headers) {
27
- if (!headers) return void 0;
28
- if (typeof headers === "object") return headers;
29
- const out = {};
30
- for (const pair of headers.split(",")) {
31
- const [key, ...valueParts] = pair.split("=");
32
- if (key && valueParts.length > 0) {
33
- let value = valueParts.join("=").trim();
34
- value = value.replaceAll("%20", " ");
35
- out[key.trim()] = value;
36
- }
37
- }
38
- return Object.keys(out).length > 0 ? out : void 0;
39
- }
40
27
  /**
41
28
  * Create an autotel configuration for Grafana Cloud OTLP.
42
29
  *
@@ -50,7 +37,7 @@ function normalizeHeaders(headers) {
50
37
  function createGrafanaConfig(config) {
51
38
  const { endpoint, headers: headersInput, service, environment, version, enableLogs = true, logRecordProcessors } = config;
52
39
  if (!endpoint) throw new Error("Grafana Cloud endpoint is required. Get it from: Grafana Cloud → your stack → Connections → OpenTelemetry → Configure");
53
- const headers = normalizeHeaders(headersInput);
40
+ const headers = require_headers.normalizeHeaders(headersInput);
54
41
  const base = endpoint.replace(/\/v1\/(traces|metrics|logs)$/, "");
55
42
  const logsUrl = `${base}${base.endsWith("/") ? "" : "/"}v1/logs`;
56
43
  const result = {
package/dist/grafana.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { t as normalizeHeaders } from "./headers-B9KIbNlx.js";
1
2
  import { createRequire } from "node:module";
2
3
  //#region src/grafana.ts
3
4
  /**
@@ -22,20 +23,6 @@ import { createRequire } from "node:module";
22
23
  * }));
23
24
  * ```
24
25
  */
25
- function normalizeHeaders(headers) {
26
- if (!headers) return void 0;
27
- if (typeof headers === "object") return headers;
28
- const out = {};
29
- for (const pair of headers.split(",")) {
30
- const [key, ...valueParts] = pair.split("=");
31
- if (key && valueParts.length > 0) {
32
- let value = valueParts.join("=").trim();
33
- value = value.replaceAll("%20", " ");
34
- out[key.trim()] = value;
35
- }
36
- }
37
- return Object.keys(out).length > 0 ? out : void 0;
38
- }
39
26
  /**
40
27
  * Create an autotel configuration for Grafana Cloud OTLP.
41
28
  *
@@ -0,0 +1,28 @@
1
+ //#region src/headers.ts
2
+ /**
3
+ * OTLP headers in either form the presets and users have: the
4
+ * `key=value,key=value` string of `OTEL_EXPORTER_OTLP_HEADERS` (values
5
+ * percent-encoded, as the specification has them) or an already-parsed
6
+ * record. Undefined when there are none.
7
+ */
8
+ function normalizeHeaders(headers) {
9
+ if (!headers) return void 0;
10
+ if (typeof headers === "object") return headers;
11
+ const out = {};
12
+ for (const pair of headers.split(",")) {
13
+ const [key, ...valueParts] = pair.split("=");
14
+ if (key && valueParts.length > 0) {
15
+ let value = valueParts.join("=").trim();
16
+ value = value.replaceAll("%20", " ");
17
+ out[key.trim()] = value;
18
+ }
19
+ }
20
+ return Object.keys(out).length > 0 ? out : void 0;
21
+ }
22
+ //#endregion
23
+ Object.defineProperty(exports, "normalizeHeaders", {
24
+ enumerable: true,
25
+ get: function() {
26
+ return normalizeHeaders;
27
+ }
28
+ });
@@ -0,0 +1,23 @@
1
+ //#region src/headers.ts
2
+ /**
3
+ * OTLP headers in either form the presets and users have: the
4
+ * `key=value,key=value` string of `OTEL_EXPORTER_OTLP_HEADERS` (values
5
+ * percent-encoded, as the specification has them) or an already-parsed
6
+ * record. Undefined when there are none.
7
+ */
8
+ function normalizeHeaders(headers) {
9
+ if (!headers) return void 0;
10
+ if (typeof headers === "object") return headers;
11
+ const out = {};
12
+ for (const pair of headers.split(",")) {
13
+ const [key, ...valueParts] = pair.split("=");
14
+ if (key && valueParts.length > 0) {
15
+ let value = valueParts.join("=").trim();
16
+ value = value.replaceAll("%20", " ");
17
+ out[key.trim()] = value;
18
+ }
19
+ }
20
+ return Object.keys(out).length > 0 ? out : void 0;
21
+ }
22
+ //#endregion
23
+ export { normalizeHeaders as t };
package/dist/relay.cjs ADDED
@@ -0,0 +1,174 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_headers = require("./headers--QWNf7Su.cjs");
3
+ //#region src/relay.ts
4
+ /**
5
+ * The server half of exporting from a browser to a backend that needs a
6
+ * secret.
7
+ *
8
+ * Datadog, Honeycomb and Grafana authenticate OTLP with an API key, and a key
9
+ * shipped to a page is a key anyone can use. So the page exports to its own
10
+ * origin and this forwards the request with the key added on the server:
11
+ *
12
+ * ```ts
13
+ * // server: any framework that speaks Request/Response (Hono, Next, Workers)
14
+ * import { otlpRelay } from 'autotel-backends/relay';
15
+ * import { createDatadogConfig } from 'autotel-backends/datadog';
16
+ *
17
+ * const relay = otlpRelay(createDatadogConfig({ apiKey, site: 'datadoghq.eu' }));
18
+ * app.post('/otel/v1/*', (c) => relay(c.req.raw));
19
+ *
20
+ * // browser
21
+ * initFull({ service: 'web', endpoint: '/otel' });
22
+ * ```
23
+ *
24
+ * It takes the same `{ endpoint, headers }` every backend preset returns, so
25
+ * one relay works for any of them. Uses only the Fetch API.
26
+ */
27
+ /** OTLP signals a page exports. Metrics stay server-side. */
28
+ const SIGNALS = ["traces", "logs"];
29
+ /** The only request headers forwarded: what the payload needs to be read. */
30
+ const FORWARDED = ["content-type", "content-encoding"];
31
+ /**
32
+ * The request body, or undefined once it passes `limit` bytes. Stops reading
33
+ * at that point and cancels the rest of the stream.
34
+ */
35
+ async function readAtMost(request, limit) {
36
+ if (!request.body) return /* @__PURE__ */ new Uint8Array(0);
37
+ const reader = request.body.getReader();
38
+ const chunks = [];
39
+ let total = 0;
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done) break;
43
+ total += value.byteLength;
44
+ if (total > limit) {
45
+ await reader.cancel();
46
+ return;
47
+ }
48
+ chunks.push(value);
49
+ }
50
+ const body = new Uint8Array(total);
51
+ let offset = 0;
52
+ for (const chunk of chunks) {
53
+ body.set(chunk, offset);
54
+ offset += chunk.byteLength;
55
+ }
56
+ return body;
57
+ }
58
+ function upstreamUrl(endpoint, signal) {
59
+ const [base, query = ""] = endpoint.split("?");
60
+ return `${base.replace(/\/+$/, "").replace(/\/v1\/(traces|logs)$/, "")}/v1/${signal}${query ? `?${query}` : ""}`;
61
+ }
62
+ /**
63
+ * The hosts this request was addressed to: its own, and the public one a
64
+ * reverse proxy (nginx, a load balancer, Vite with `xfwd`) passes in
65
+ * X-Forwarded-Host when it rewrites Host. Host only, not scheme: TLS usually
66
+ * ends at the proxy, so the page is https and the relay sees http. A page on
67
+ * another site cannot set X-Forwarded-Host without a preflight, which this
68
+ * relay refuses.
69
+ */
70
+ function publicHosts(request, url) {
71
+ const forwarded = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
72
+ return forwarded ? [url.host, forwarded] : [url.host];
73
+ }
74
+ function hostOf(origin) {
75
+ try {
76
+ return new URL(origin).host;
77
+ } catch {
78
+ return;
79
+ }
80
+ }
81
+ /** A client-supplied value, quoted and capped before it reaches a log. */
82
+ function quoted(value) {
83
+ return JSON.stringify(value.length > 200 ? `${value.slice(0, 200)}…` : value);
84
+ }
85
+ const refuse = (status, reason, extra) => new Response(reason, {
86
+ status,
87
+ headers: {
88
+ "content-type": "text/plain",
89
+ ...extra
90
+ }
91
+ });
92
+ /**
93
+ * A `(request) => Response` handler that forwards OTLP traces and logs from a
94
+ * page to `endpoint`, with `headers` added. The signal is taken from the
95
+ * request path (`…/v1/traces` or `…/v1/logs`); anything else is refused.
96
+ */
97
+ function otlpRelay(options) {
98
+ const { endpoint } = options;
99
+ if (!endpoint) throw new Error("otlpRelay needs the backend endpoint. A preset created with useAgent: true has none to relay to.");
100
+ const auth = require_headers.normalizeHeaders(options.headers) ?? {};
101
+ const allowed = new Set(options.allowedOrigins);
102
+ const maxBodyBytes = options.maxBodyBytes ?? 1048576;
103
+ const send = options.fetch ?? globalThis.fetch;
104
+ /**
105
+ * Said once per kind of refusal, on the server. The page's exporter only
106
+ * sees a status, so a relay refusing every export is otherwise silent.
107
+ * Keyed by the fixed kind, never by request content: the set holds at most
108
+ * one entry per kind, however many origins a client invents.
109
+ */
110
+ const warned = /* @__PURE__ */ new Set();
111
+ const refuseLoudly = (kind, status, reason, extra) => {
112
+ if (!warned.has(kind)) {
113
+ warned.add(kind);
114
+ console.warn(`[autotel-backends/relay] ${status}: ${reason}`);
115
+ }
116
+ return refuse(status, reason, extra);
117
+ };
118
+ return async (request) => {
119
+ const url = new URL(request.url);
120
+ const origin = request.headers.get("origin");
121
+ const host = origin === null ? void 0 : hostOf(origin);
122
+ const sameOrigin = origin === null || host !== void 0 && publicHosts(request, url).includes(host);
123
+ const crossOrigin = origin !== null && !sameOrigin && allowed.has(origin);
124
+ if (!sameOrigin && !crossOrigin) return refuseLoudly("origin", 403, `Origin ${quoted(origin)} may not post to this relay. Add it to otlpRelay({ allowedOrigins }). If it is this site, the relay sees the host ${publicHosts(request, url).join(" / ")}: a proxy in front rewrote Host without setting X-Forwarded-Host.`);
125
+ const cors = crossOrigin && origin ? {
126
+ "access-control-allow-origin": origin,
127
+ vary: "origin"
128
+ } : {};
129
+ if (request.method === "OPTIONS") return new Response(null, {
130
+ status: 204,
131
+ headers: {
132
+ ...cors,
133
+ "access-control-allow-methods": "POST",
134
+ "access-control-allow-headers": FORWARDED.join(", "),
135
+ "access-control-max-age": "86400"
136
+ }
137
+ });
138
+ if (request.method !== "POST") return refuse(405, "POST only.", {
139
+ ...cors,
140
+ allow: "POST"
141
+ });
142
+ const signal = SIGNALS.find((name) => url.pathname.replace(/\/+$/, "").endsWith(`/v1/${name}`));
143
+ if (!signal) return refuseLoudly("path", 404, "Expected a path ending in /v1/traces or /v1/logs.", cors);
144
+ if (Number(request.headers.get("content-length") ?? 0) > maxBodyBytes) return refuseLoudly("size", 413, `Body over ${maxBodyBytes} bytes.`, cors);
145
+ const body = await readAtMost(request, maxBodyBytes);
146
+ if (body === void 0) return refuseLoudly("size", 413, `Body over ${maxBodyBytes} bytes.`, cors);
147
+ const headers = new Headers(auth);
148
+ for (const name of FORWARDED) {
149
+ const value = request.headers.get(name);
150
+ if (value) headers.set(name, value);
151
+ }
152
+ let upstream;
153
+ try {
154
+ upstream = await send(upstreamUrl(endpoint, signal), {
155
+ method: "POST",
156
+ headers,
157
+ body
158
+ });
159
+ } catch {
160
+ return refuseLoudly("upstream", 502, "The backend could not be reached.", cors);
161
+ }
162
+ await upstream.body?.cancel();
163
+ const retryAfter = upstream.headers.get("retry-after");
164
+ return new Response(null, {
165
+ status: upstream.status,
166
+ headers: retryAfter ? {
167
+ ...cors,
168
+ "retry-after": retryAfter
169
+ } : cors
170
+ });
171
+ };
172
+ }
173
+ //#endregion
174
+ exports.otlpRelay = otlpRelay;
@@ -0,0 +1,54 @@
1
+ //#region src/relay.d.ts
2
+ /**
3
+ * The server half of exporting from a browser to a backend that needs a
4
+ * secret.
5
+ *
6
+ * Datadog, Honeycomb and Grafana authenticate OTLP with an API key, and a key
7
+ * shipped to a page is a key anyone can use. So the page exports to its own
8
+ * origin and this forwards the request with the key added on the server:
9
+ *
10
+ * ```ts
11
+ * // server: any framework that speaks Request/Response (Hono, Next, Workers)
12
+ * import { otlpRelay } from 'autotel-backends/relay';
13
+ * import { createDatadogConfig } from 'autotel-backends/datadog';
14
+ *
15
+ * const relay = otlpRelay(createDatadogConfig({ apiKey, site: 'datadoghq.eu' }));
16
+ * app.post('/otel/v1/*', (c) => relay(c.req.raw));
17
+ *
18
+ * // browser
19
+ * initFull({ service: 'web', endpoint: '/otel' });
20
+ * ```
21
+ *
22
+ * It takes the same `{ endpoint, headers }` every backend preset returns, so
23
+ * one relay works for any of them. Uses only the Fetch API.
24
+ */
25
+ export interface OtlpRelayOptions {
26
+ /** The backend's OTLP base URL, as `init()` takes it. */
27
+ endpoint?: string;
28
+ /**
29
+ * Headers to add on the server: the backend's auth. Either a record or the
30
+ * `key=value,key=value` string the backend presets return.
31
+ */
32
+ headers?: Record<string, string> | string;
33
+ /**
34
+ * Origins allowed to post, besides the relay's own. Cross-origin callers
35
+ * also get CORS headers. Without this, only same-origin pages may post.
36
+ */
37
+ allowedOrigins?: string[];
38
+ /**
39
+ * Largest request body forwarded, in bytes. The relay spends your API key,
40
+ * so it refuses what a page would never send.
41
+ *
42
+ * @default 1_048_576 (1 MiB)
43
+ */
44
+ maxBodyBytes?: number;
45
+ /** Replaces `globalThis.fetch` for the upstream call. For tests. */
46
+ fetch?: typeof fetch;
47
+ }
48
+ /**
49
+ * A `(request) => Response` handler that forwards OTLP traces and logs from a
50
+ * page to `endpoint`, with `headers` added. The signal is taken from the
51
+ * request path (`…/v1/traces` or `…/v1/logs`); anything else is refused.
52
+ */
53
+ export declare function otlpRelay(options: OtlpRelayOptions): (request: Request) => Promise<Response>;
54
+ //#endregion
@@ -0,0 +1,54 @@
1
+ //#region src/relay.d.ts
2
+ /**
3
+ * The server half of exporting from a browser to a backend that needs a
4
+ * secret.
5
+ *
6
+ * Datadog, Honeycomb and Grafana authenticate OTLP with an API key, and a key
7
+ * shipped to a page is a key anyone can use. So the page exports to its own
8
+ * origin and this forwards the request with the key added on the server:
9
+ *
10
+ * ```ts
11
+ * // server: any framework that speaks Request/Response (Hono, Next, Workers)
12
+ * import { otlpRelay } from 'autotel-backends/relay';
13
+ * import { createDatadogConfig } from 'autotel-backends/datadog';
14
+ *
15
+ * const relay = otlpRelay(createDatadogConfig({ apiKey, site: 'datadoghq.eu' }));
16
+ * app.post('/otel/v1/*', (c) => relay(c.req.raw));
17
+ *
18
+ * // browser
19
+ * initFull({ service: 'web', endpoint: '/otel' });
20
+ * ```
21
+ *
22
+ * It takes the same `{ endpoint, headers }` every backend preset returns, so
23
+ * one relay works for any of them. Uses only the Fetch API.
24
+ */
25
+ export interface OtlpRelayOptions {
26
+ /** The backend's OTLP base URL, as `init()` takes it. */
27
+ endpoint?: string;
28
+ /**
29
+ * Headers to add on the server: the backend's auth. Either a record or the
30
+ * `key=value,key=value` string the backend presets return.
31
+ */
32
+ headers?: Record<string, string> | string;
33
+ /**
34
+ * Origins allowed to post, besides the relay's own. Cross-origin callers
35
+ * also get CORS headers. Without this, only same-origin pages may post.
36
+ */
37
+ allowedOrigins?: string[];
38
+ /**
39
+ * Largest request body forwarded, in bytes. The relay spends your API key,
40
+ * so it refuses what a page would never send.
41
+ *
42
+ * @default 1_048_576 (1 MiB)
43
+ */
44
+ maxBodyBytes?: number;
45
+ /** Replaces `globalThis.fetch` for the upstream call. For tests. */
46
+ fetch?: typeof fetch;
47
+ }
48
+ /**
49
+ * A `(request) => Response` handler that forwards OTLP traces and logs from a
50
+ * page to `endpoint`, with `headers` added. The signal is taken from the
51
+ * request path (`…/v1/traces` or `…/v1/logs`); anything else is refused.
52
+ */
53
+ export declare function otlpRelay(options: OtlpRelayOptions): (request: Request) => Promise<Response>;
54
+ //#endregion
package/dist/relay.js ADDED
@@ -0,0 +1,173 @@
1
+ import { t as normalizeHeaders } from "./headers-B9KIbNlx.js";
2
+ //#region src/relay.ts
3
+ /**
4
+ * The server half of exporting from a browser to a backend that needs a
5
+ * secret.
6
+ *
7
+ * Datadog, Honeycomb and Grafana authenticate OTLP with an API key, and a key
8
+ * shipped to a page is a key anyone can use. So the page exports to its own
9
+ * origin and this forwards the request with the key added on the server:
10
+ *
11
+ * ```ts
12
+ * // server: any framework that speaks Request/Response (Hono, Next, Workers)
13
+ * import { otlpRelay } from 'autotel-backends/relay';
14
+ * import { createDatadogConfig } from 'autotel-backends/datadog';
15
+ *
16
+ * const relay = otlpRelay(createDatadogConfig({ apiKey, site: 'datadoghq.eu' }));
17
+ * app.post('/otel/v1/*', (c) => relay(c.req.raw));
18
+ *
19
+ * // browser
20
+ * initFull({ service: 'web', endpoint: '/otel' });
21
+ * ```
22
+ *
23
+ * It takes the same `{ endpoint, headers }` every backend preset returns, so
24
+ * one relay works for any of them. Uses only the Fetch API.
25
+ */
26
+ /** OTLP signals a page exports. Metrics stay server-side. */
27
+ const SIGNALS = ["traces", "logs"];
28
+ /** The only request headers forwarded: what the payload needs to be read. */
29
+ const FORWARDED = ["content-type", "content-encoding"];
30
+ /**
31
+ * The request body, or undefined once it passes `limit` bytes. Stops reading
32
+ * at that point and cancels the rest of the stream.
33
+ */
34
+ async function readAtMost(request, limit) {
35
+ if (!request.body) return /* @__PURE__ */ new Uint8Array(0);
36
+ const reader = request.body.getReader();
37
+ const chunks = [];
38
+ let total = 0;
39
+ for (;;) {
40
+ const { done, value } = await reader.read();
41
+ if (done) break;
42
+ total += value.byteLength;
43
+ if (total > limit) {
44
+ await reader.cancel();
45
+ return;
46
+ }
47
+ chunks.push(value);
48
+ }
49
+ const body = new Uint8Array(total);
50
+ let offset = 0;
51
+ for (const chunk of chunks) {
52
+ body.set(chunk, offset);
53
+ offset += chunk.byteLength;
54
+ }
55
+ return body;
56
+ }
57
+ function upstreamUrl(endpoint, signal) {
58
+ const [base, query = ""] = endpoint.split("?");
59
+ return `${base.replace(/\/+$/, "").replace(/\/v1\/(traces|logs)$/, "")}/v1/${signal}${query ? `?${query}` : ""}`;
60
+ }
61
+ /**
62
+ * The hosts this request was addressed to: its own, and the public one a
63
+ * reverse proxy (nginx, a load balancer, Vite with `xfwd`) passes in
64
+ * X-Forwarded-Host when it rewrites Host. Host only, not scheme: TLS usually
65
+ * ends at the proxy, so the page is https and the relay sees http. A page on
66
+ * another site cannot set X-Forwarded-Host without a preflight, which this
67
+ * relay refuses.
68
+ */
69
+ function publicHosts(request, url) {
70
+ const forwarded = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
71
+ return forwarded ? [url.host, forwarded] : [url.host];
72
+ }
73
+ function hostOf(origin) {
74
+ try {
75
+ return new URL(origin).host;
76
+ } catch {
77
+ return;
78
+ }
79
+ }
80
+ /** A client-supplied value, quoted and capped before it reaches a log. */
81
+ function quoted(value) {
82
+ return JSON.stringify(value.length > 200 ? `${value.slice(0, 200)}…` : value);
83
+ }
84
+ const refuse = (status, reason, extra) => new Response(reason, {
85
+ status,
86
+ headers: {
87
+ "content-type": "text/plain",
88
+ ...extra
89
+ }
90
+ });
91
+ /**
92
+ * A `(request) => Response` handler that forwards OTLP traces and logs from a
93
+ * page to `endpoint`, with `headers` added. The signal is taken from the
94
+ * request path (`…/v1/traces` or `…/v1/logs`); anything else is refused.
95
+ */
96
+ function otlpRelay(options) {
97
+ const { endpoint } = options;
98
+ if (!endpoint) throw new Error("otlpRelay needs the backend endpoint. A preset created with useAgent: true has none to relay to.");
99
+ const auth = normalizeHeaders(options.headers) ?? {};
100
+ const allowed = new Set(options.allowedOrigins);
101
+ const maxBodyBytes = options.maxBodyBytes ?? 1048576;
102
+ const send = options.fetch ?? globalThis.fetch;
103
+ /**
104
+ * Said once per kind of refusal, on the server. The page's exporter only
105
+ * sees a status, so a relay refusing every export is otherwise silent.
106
+ * Keyed by the fixed kind, never by request content: the set holds at most
107
+ * one entry per kind, however many origins a client invents.
108
+ */
109
+ const warned = /* @__PURE__ */ new Set();
110
+ const refuseLoudly = (kind, status, reason, extra) => {
111
+ if (!warned.has(kind)) {
112
+ warned.add(kind);
113
+ console.warn(`[autotel-backends/relay] ${status}: ${reason}`);
114
+ }
115
+ return refuse(status, reason, extra);
116
+ };
117
+ return async (request) => {
118
+ const url = new URL(request.url);
119
+ const origin = request.headers.get("origin");
120
+ const host = origin === null ? void 0 : hostOf(origin);
121
+ const sameOrigin = origin === null || host !== void 0 && publicHosts(request, url).includes(host);
122
+ const crossOrigin = origin !== null && !sameOrigin && allowed.has(origin);
123
+ if (!sameOrigin && !crossOrigin) return refuseLoudly("origin", 403, `Origin ${quoted(origin)} may not post to this relay. Add it to otlpRelay({ allowedOrigins }). If it is this site, the relay sees the host ${publicHosts(request, url).join(" / ")}: a proxy in front rewrote Host without setting X-Forwarded-Host.`);
124
+ const cors = crossOrigin && origin ? {
125
+ "access-control-allow-origin": origin,
126
+ vary: "origin"
127
+ } : {};
128
+ if (request.method === "OPTIONS") return new Response(null, {
129
+ status: 204,
130
+ headers: {
131
+ ...cors,
132
+ "access-control-allow-methods": "POST",
133
+ "access-control-allow-headers": FORWARDED.join(", "),
134
+ "access-control-max-age": "86400"
135
+ }
136
+ });
137
+ if (request.method !== "POST") return refuse(405, "POST only.", {
138
+ ...cors,
139
+ allow: "POST"
140
+ });
141
+ const signal = SIGNALS.find((name) => url.pathname.replace(/\/+$/, "").endsWith(`/v1/${name}`));
142
+ if (!signal) return refuseLoudly("path", 404, "Expected a path ending in /v1/traces or /v1/logs.", cors);
143
+ if (Number(request.headers.get("content-length") ?? 0) > maxBodyBytes) return refuseLoudly("size", 413, `Body over ${maxBodyBytes} bytes.`, cors);
144
+ const body = await readAtMost(request, maxBodyBytes);
145
+ if (body === void 0) return refuseLoudly("size", 413, `Body over ${maxBodyBytes} bytes.`, cors);
146
+ const headers = new Headers(auth);
147
+ for (const name of FORWARDED) {
148
+ const value = request.headers.get(name);
149
+ if (value) headers.set(name, value);
150
+ }
151
+ let upstream;
152
+ try {
153
+ upstream = await send(upstreamUrl(endpoint, signal), {
154
+ method: "POST",
155
+ headers,
156
+ body
157
+ });
158
+ } catch {
159
+ return refuseLoudly("upstream", 502, "The backend could not be reached.", cors);
160
+ }
161
+ await upstream.body?.cancel();
162
+ const retryAfter = upstream.headers.get("retry-after");
163
+ return new Response(null, {
164
+ status: upstream.status,
165
+ headers: retryAfter ? {
166
+ ...cors,
167
+ "retry-after": retryAfter
168
+ } : cors
169
+ });
170
+ };
171
+ }
172
+ //#endregion
173
+ export { otlpRelay };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autotel-backends",
3
- "version": "2.14.19",
3
+ "version": "2.15.0",
4
4
  "description": "Vendor backend configurations for Autotel (Honeycomb, Datadog, etc.)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -46,6 +46,11 @@
46
46
  "types": "./dist/posthog.d.ts",
47
47
  "import": "./dist/posthog.js",
48
48
  "require": "./dist/posthog.cjs"
49
+ },
50
+ "./relay": {
51
+ "types": "./dist/relay.d.ts",
52
+ "import": "./dist/relay.js",
53
+ "require": "./dist/relay.cjs"
49
54
  }
50
55
  },
51
56
  "files": [
@@ -72,7 +77,7 @@
72
77
  "author": "Jag Reehal <jag@jagreehal.com> (https://jagreehal.com)",
73
78
  "license": "Apache-2.0",
74
79
  "dependencies": {
75
- "autotel": "8.6.2",
80
+ "autotel": "8.7.0",
76
81
  "@opentelemetry/exporter-logs-otlp-http": ">=0.223.0",
77
82
  "@opentelemetry/sdk-logs": ">=0.223.0"
78
83
  },