@benchcutlogic/edge-kit 0.0.0-stage → 0.2.2

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/body.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import * as Effect from 'effect/Effect';
2
+ import * as Schema from 'effect/Schema';
3
+ import type * as SchemaAST from 'effect/SchemaAST';
4
+ declare const BodyTooLargeError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
5
+ readonly _tag: "BodyTooLargeError";
6
+ } & Readonly<A>;
7
+ export declare class BodyTooLargeError extends BodyTooLargeError_base<{
8
+ readonly maxBytes: number;
9
+ readonly actualBytes?: number;
10
+ readonly declaredBytes?: number;
11
+ }> {
12
+ get message(): string;
13
+ }
14
+ declare const BodyReadError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
15
+ readonly _tag: "BodyReadError";
16
+ } & Readonly<A>;
17
+ export declare class BodyReadError extends BodyReadError_base<{
18
+ readonly cause: unknown;
19
+ }> {
20
+ get message(): string;
21
+ }
22
+ declare const InvalidJsonError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
23
+ readonly _tag: "InvalidJsonError";
24
+ } & Readonly<A>;
25
+ export declare class InvalidJsonError extends InvalidJsonError_base<{
26
+ readonly cause: unknown;
27
+ }> {
28
+ get message(): string;
29
+ }
30
+ export type BodySource = Response | ReadableStream<Uint8Array> | null | undefined;
31
+ export interface ReadCappedJsonOptions {
32
+ readonly maxBytes: number;
33
+ readonly onExcessProperty?: SchemaAST.ParseOptions['onExcessProperty'];
34
+ readonly errors?: SchemaAST.ParseOptions['errors'];
35
+ readonly parseOptions?: SchemaAST.ParseOptions;
36
+ }
37
+ /**
38
+ * Reads bytes from a `Response` or `ReadableStream<Uint8Array>` while enforcing
39
+ * a hard streaming byte ceiling.
40
+ *
41
+ * Uses `Content-Length` only as a fast-fail optimization when it already exceeds
42
+ * `maxBytes`; always enforces the streaming byte cap via `ReadableStreamDefaultReader`
43
+ * and calls `reader.cancel()` immediately on overflow.
44
+ */
45
+ export declare function readCappedBytes(source: BodySource, maxBytes: number): Effect.Effect<Uint8Array, BodyTooLargeError | BodyReadError>;
46
+ /**
47
+ * Reads a UTF-8 string from a `Response` or `ReadableStream<Uint8Array>` with a
48
+ * strict streaming byte ceiling.
49
+ */
50
+ export declare function readCappedText(source: BodySource, maxBytes: number): Effect.Effect<string, BodyTooLargeError | BodyReadError>;
51
+ /**
52
+ * Reads a capped UTF-8 body, parses it as JSON, and decodes it with an Effect v4 Schema.
53
+ */
54
+ export declare function readCappedJson<S extends Schema.Constraint>(source: BodySource, schema: S, options: ReadCappedJsonOptions | number): Effect.Effect<S['Type'], BodyTooLargeError | BodyReadError | InvalidJsonError | Schema.SchemaError, S['DecodingServices']>;
55
+ export {};
package/dist/body.js ADDED
@@ -0,0 +1,177 @@
1
+ import * as Data from 'effect/Data';
2
+ import * as Effect from 'effect/Effect';
3
+ import * as Schema from 'effect/Schema';
4
+ export class BodyTooLargeError extends Data.TaggedError('BodyTooLargeError') {
5
+ get message() {
6
+ if (this.declaredBytes !== undefined) {
7
+ return `Response body Content-Length (${this.declaredBytes} bytes) exceeds limit of ${this.maxBytes} bytes`;
8
+ }
9
+ if (this.actualBytes !== undefined) {
10
+ return `Response body (${this.actualBytes} bytes) exceeds limit of ${this.maxBytes} bytes`;
11
+ }
12
+ return `Response body exceeds limit of ${this.maxBytes} bytes`;
13
+ }
14
+ }
15
+ export class BodyReadError extends Data.TaggedError('BodyReadError') {
16
+ get message() {
17
+ const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
18
+ return `Failed to read body stream: ${detail}`;
19
+ }
20
+ }
21
+ export class InvalidJsonError extends Data.TaggedError('InvalidJsonError') {
22
+ get message() {
23
+ const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
24
+ return `Failed to parse JSON body: ${detail}`;
25
+ }
26
+ }
27
+ function isResponse(source) {
28
+ return (typeof source === 'object' &&
29
+ source !== null &&
30
+ 'headers' in source &&
31
+ 'status' in source &&
32
+ 'body' in source);
33
+ }
34
+ function parseContentLength(headers) {
35
+ const raw = headers.get('content-length');
36
+ if (raw === null)
37
+ return undefined;
38
+ const trimmed = raw.trim();
39
+ if (!/^\d+$/.test(trimmed))
40
+ return undefined;
41
+ const parsed = Number(trimmed);
42
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
43
+ }
44
+ function assertValidMaxBytes(maxBytes) {
45
+ if (!Number.isFinite(maxBytes) || maxBytes < 0) {
46
+ throw new RangeError(`maxBytes must be a finite non-negative number, got ${maxBytes}`);
47
+ }
48
+ }
49
+ function concatChunks(chunks, totalLength) {
50
+ const result = new Uint8Array(totalLength);
51
+ let offset = 0;
52
+ for (const chunk of chunks) {
53
+ result.set(chunk, offset);
54
+ offset += chunk.byteLength;
55
+ }
56
+ return result;
57
+ }
58
+ /**
59
+ * Reads bytes from a `Response` or `ReadableStream<Uint8Array>` while enforcing
60
+ * a hard streaming byte ceiling.
61
+ *
62
+ * Uses `Content-Length` only as a fast-fail optimization when it already exceeds
63
+ * `maxBytes`; always enforces the streaming byte cap via `ReadableStreamDefaultReader`
64
+ * and calls `reader.cancel()` immediately on overflow.
65
+ */
66
+ export function readCappedBytes(source, maxBytes) {
67
+ return Effect.gen(function* () {
68
+ assertValidMaxBytes(maxBytes);
69
+ if (source === null || source === undefined) {
70
+ return new Uint8Array(0);
71
+ }
72
+ let stream;
73
+ if (isResponse(source)) {
74
+ stream = source.body;
75
+ if (stream === null) {
76
+ return new Uint8Array(0);
77
+ }
78
+ const declaredBytes = parseContentLength(source.headers);
79
+ if (declaredBytes !== undefined && declaredBytes > maxBytes) {
80
+ try {
81
+ void stream.cancel('Body exceeded maxBytes limit').catch(() => undefined);
82
+ }
83
+ catch {
84
+ // Best-effort cancellation on declared overflow
85
+ }
86
+ return yield* new BodyTooLargeError({ maxBytes, declaredBytes });
87
+ }
88
+ }
89
+ else {
90
+ stream = source;
91
+ if (stream === null) {
92
+ return new Uint8Array(0);
93
+ }
94
+ }
95
+ return yield* Effect.acquireUseRelease(Effect.try({
96
+ try: () => stream.getReader(),
97
+ catch: (cause) => new BodyReadError({ cause })
98
+ }), (reader) => Effect.gen(function* () {
99
+ const chunks = [];
100
+ let totalBytes = 0;
101
+ while (true) {
102
+ const step = yield* Effect.tryPromise({
103
+ try: () => reader.read(),
104
+ catch: (cause) => new BodyReadError({ cause })
105
+ });
106
+ if (step.done) {
107
+ break;
108
+ }
109
+ const chunk = step.value;
110
+ if (chunk === undefined || chunk.byteLength === 0) {
111
+ continue;
112
+ }
113
+ const nextTotal = totalBytes + chunk.byteLength;
114
+ if (nextTotal > maxBytes) {
115
+ try {
116
+ void reader.cancel('Body exceeded maxBytes limit').catch(() => undefined);
117
+ }
118
+ catch {
119
+ // Best-effort cancellation on overflow without awaiting cloned sibling branches
120
+ }
121
+ return yield* new BodyTooLargeError({
122
+ maxBytes,
123
+ actualBytes: nextTotal
124
+ });
125
+ }
126
+ chunks.push(chunk);
127
+ totalBytes = nextTotal;
128
+ }
129
+ return concatChunks(chunks, totalBytes);
130
+ }), (reader, exit) => Effect.sync(() => {
131
+ if (exit._tag === 'Failure') {
132
+ try {
133
+ void reader.cancel().catch(() => undefined);
134
+ }
135
+ catch {
136
+ // Best-effort cancellation on error or interruption
137
+ }
138
+ }
139
+ try {
140
+ reader.releaseLock();
141
+ }
142
+ catch {
143
+ // Lock may already be released after cancel
144
+ }
145
+ }));
146
+ });
147
+ }
148
+ /**
149
+ * Reads a UTF-8 string from a `Response` or `ReadableStream<Uint8Array>` with a
150
+ * strict streaming byte ceiling.
151
+ */
152
+ export function readCappedText(source, maxBytes) {
153
+ return Effect.map(readCappedBytes(source, maxBytes), (bytes) => new TextDecoder('utf-8').decode(bytes));
154
+ }
155
+ /**
156
+ * Reads a capped UTF-8 body, parses it as JSON, and decodes it with an Effect v4 Schema.
157
+ */
158
+ export function readCappedJson(source, schema, options) {
159
+ return Effect.gen(function* () {
160
+ const maxBytes = typeof options === 'number' ? options : options.maxBytes;
161
+ const parseOptions = typeof options === 'number'
162
+ ? undefined
163
+ : {
164
+ ...options.parseOptions,
165
+ ...(options.onExcessProperty !== undefined
166
+ ? { onExcessProperty: options.onExcessProperty }
167
+ : {}),
168
+ ...(options.errors !== undefined ? { errors: options.errors } : {})
169
+ };
170
+ const text = yield* readCappedText(source, maxBytes);
171
+ const parsed = yield* Effect.try({
172
+ try: () => JSON.parse(text),
173
+ catch: (cause) => new InvalidJsonError({ cause })
174
+ });
175
+ return yield* Schema.decodeUnknownEffect(schema, parseOptions)(parsed);
176
+ });
177
+ }
@@ -0,0 +1,6 @@
1
+ export * from './analytics.js';
2
+ export * from './body.js';
3
+ export * from './scrub.js';
4
+ export { assertPublicHttpUrl, createNodeDnsResolver, createPinnedNodeFetch, DeadlineExceededError, InvalidUrlError, isPrivateOrReservedIp, NetworkError, SsrfBlockedError, ssrfFetch, type AssertPublicHttpUrlOptions, type CappedResponse, type DnsResolver, type SsrfFetchOptions, type SsrfFetchRequestInit, type SsrfFetchTransport } from './ssrf.js';
5
+ export * from './sveltekit.js';
6
+ export * from './tenant.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './analytics.js';
2
+ export * from './body.js';
3
+ export * from './scrub.js';
4
+ export { assertPublicHttpUrl, createNodeDnsResolver, createPinnedNodeFetch, DeadlineExceededError, InvalidUrlError, isPrivateOrReservedIp, NetworkError, SsrfBlockedError, ssrfFetch } from './ssrf.js';
5
+ export * from './sveltekit.js';
6
+ export * from './tenant.js';
@@ -0,0 +1,128 @@
1
+ export declare const DEFAULT_SECRET_KEYS: ReadonlyArray<string>;
2
+ export interface ScrubConfig {
3
+ readonly secretKeys?: ReadonlyArray<string>;
4
+ readonly replacement?: string;
5
+ readonly maxDepth?: number;
6
+ readonly pathPatterns?: ReadonlyArray<{
7
+ readonly pattern: RegExp;
8
+ readonly replacement: string;
9
+ }>;
10
+ }
11
+ /**
12
+ * The structural subset of a Sentry event that the scrubber reads. It has no
13
+ * index signatures, so Sentry's own `ErrorEvent` interface (from `@sentry/core`,
14
+ * re-exported by `@sentry/node`, `@sentry/browser`, and the framework SDKs)
15
+ * satisfies it without a cast.
16
+ */
17
+ export interface SentryEventLike {
18
+ message?: string;
19
+ request?: {
20
+ url?: string;
21
+ query_string?: unknown;
22
+ headers?: unknown;
23
+ cookies?: unknown;
24
+ data?: unknown;
25
+ };
26
+ exception?: {
27
+ values?: ReadonlyArray<{
28
+ value?: string;
29
+ stacktrace?: {
30
+ frames?: ReadonlyArray<{
31
+ filename?: string;
32
+ }>;
33
+ };
34
+ }>;
35
+ };
36
+ breadcrumbs?: ReadonlyArray<{
37
+ message?: string;
38
+ data?: {
39
+ [key: string]: unknown;
40
+ };
41
+ }>;
42
+ }
43
+ /**
44
+ * The part of Sentry's `EventHint` that a `beforeSend` hook may read. Sentry
45
+ * always passes a hint object, so `assertScrubberInvariants` passes one too.
46
+ */
47
+ export interface SentryEventHintLike {
48
+ readonly originalException?: unknown;
49
+ readonly syntheticException?: Error | null;
50
+ }
51
+ /**
52
+ * A Sentry `beforeSend` hook. It is generic over the event, so it is assignable
53
+ * to `beforeSend` in `Sentry.init` and returns the same event type it receives.
54
+ */
55
+ export type SentryBeforeSend = <E extends SentryEventLike>(event: E, hint?: unknown) => E | null;
56
+ export interface SentryEvent {
57
+ message?: string;
58
+ request?: {
59
+ url?: string;
60
+ query_string?: string | Record<string, unknown> | ReadonlyArray<readonly [string, string]>;
61
+ headers?: Record<string, unknown>;
62
+ cookies?: Record<string, unknown> | string;
63
+ data?: unknown;
64
+ [key: string]: unknown;
65
+ };
66
+ exception?: {
67
+ values?: Array<{
68
+ type?: string;
69
+ value?: string;
70
+ stacktrace?: {
71
+ frames?: Array<{
72
+ filename?: string;
73
+ vars?: Record<string, unknown>;
74
+ [key: string]: unknown;
75
+ }>;
76
+ };
77
+ [key: string]: unknown;
78
+ }>;
79
+ };
80
+ breadcrumbs?: Array<{
81
+ message?: string;
82
+ category?: string;
83
+ data?: Record<string, unknown>;
84
+ [key: string]: unknown;
85
+ }>;
86
+ extra?: Record<string, unknown>;
87
+ contexts?: Record<string, unknown>;
88
+ tags?: Record<string, unknown>;
89
+ user?: Record<string, unknown>;
90
+ [key: string]: unknown;
91
+ }
92
+ /**
93
+ * Collapses dynamic path segments (UUIDs, numeric IDs, long tokens, emails)
94
+ * and strips query strings and hash fragments from a URL or pathname.
95
+ */
96
+ export declare function templatePath(input: string, config?: ScrubConfig): string;
97
+ /**
98
+ * Scrubs Bearer/Basic tokens, secret query parameters, secret header lines,
99
+ * and multiline JSON `SyntaxError` snippets from a string.
100
+ */
101
+ export declare function scrubString(value: string, config?: ScrubConfig): string;
102
+ /**
103
+ * Recursively clones and redacts secret keys, tokens, and multiline JSON
104
+ * syntax snippets from an arbitrary object graph without mutating the input.
105
+ */
106
+ export declare function scrubObject<T>(value: T, config?: ScrubConfig): T;
107
+ /**
108
+ * Produces a scrubbed `Error` copy with redacted message, stack trace, cause,
109
+ * and enumerable custom properties without mutating the input error.
110
+ */
111
+ export declare function scrubError(error: unknown, config?: ScrubConfig): Error;
112
+ /**
113
+ * Builds a Sentry `beforeSend` hook that scrubs secret headers, cookies,
114
+ * query strings, Bearer/Basic tokens, multiline `SyntaxError` JSON snippets,
115
+ * and dynamic URL segments.
116
+ */
117
+ export declare function createSentryBeforeSend(config?: ScrubConfig): SentryBeforeSend;
118
+ /**
119
+ * Verifies that a Sentry `beforeSend` scrubber upholds all core redaction invariants:
120
+ * - Bearer/Basic tokens in messages & exceptions
121
+ * - Secret query parameters (`?token=abc`, `?code=...`, `?state=...`)
122
+ * - Multiline JSON `SyntaxError` payload snippets
123
+ * - Secret HTTP headers (`Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`)
124
+ * - Query-string PII (`?email=...`) in request URLs, query strings, and breadcrumbs
125
+ *
126
+ * Throws a descriptive `AssertionError` if any invariant is violated.
127
+ */
128
+ export declare function assertScrubberInvariants<E extends SentryEventLike>(beforeSend: (event: E, hint: SentryEventHintLike) => E | null | undefined): void;