workers-start 0.9.0 → 0.12.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/CHANGELOG.md +18 -0
- package/README.md +101 -13
- package/dist/google.d.ts +4 -2
- package/dist/google.d.ts.map +1 -1
- package/dist/google.js +6 -3
- package/dist/google.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/mail.d.ts +71 -0
- package/dist/mail.d.ts.map +1 -0
- package/dist/mail.js +163 -0
- package/dist/mail.js.map +1 -0
- package/dist/rate-limit.d.ts +71 -0
- package/dist/rate-limit.d.ts.map +1 -0
- package/dist/rate-limit.js +102 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/sentry.d.ts +102 -0
- package/dist/sentry.d.ts.map +1 -0
- package/dist/sentry.js +137 -0
- package/dist/sentry.js.map +1 -0
- package/package.json +21 -2
- package/src/google.ts +5 -2
- package/src/index.ts +46 -0
- package/src/mail.ts +234 -0
- package/src/rate-limit.ts +158 -0
- package/src/sentry.ts +193 -0
package/src/mail.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One way to send mail from a Worker, over Cloudflare Email Sending (the
|
|
3
|
+
* `send_email` binding) or Resend, with a recording fake for tests. Every
|
|
4
|
+
* message carries both a plain text and an HTML body: some clients show only
|
|
5
|
+
* one, and a message with only HTML scores worse with spam filters.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type MailAddress = string | { email: string; name?: string };
|
|
9
|
+
|
|
10
|
+
export interface MailAttachment {
|
|
11
|
+
filename: string;
|
|
12
|
+
/** Base64. */
|
|
13
|
+
content: string;
|
|
14
|
+
contentType?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface MailMessage {
|
|
18
|
+
from: MailAddress;
|
|
19
|
+
to: string | string[];
|
|
20
|
+
subject: string;
|
|
21
|
+
text: string;
|
|
22
|
+
html: string;
|
|
23
|
+
replyTo?: MailAddress;
|
|
24
|
+
/** Extra headers, such as `In-Reply-To`. */
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
/** Adds `List-Unsubscribe` and one-click `List-Unsubscribe-Post`, for bulk and marketing mail. */
|
|
27
|
+
listUnsubscribeUrl?: string;
|
|
28
|
+
/** Resend only: repeating a send with the same key within 24 hours sends once. */
|
|
29
|
+
idempotencyKey?: string;
|
|
30
|
+
attachments?: MailAttachment[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface MailResult {
|
|
34
|
+
/** The provider's message id. */
|
|
35
|
+
id?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Mailer {
|
|
39
|
+
send(message: MailMessage): Promise<MailResult>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A send that failed. `permanent` is true when repeating it cannot help (a 4xx other than 409 and 429). */
|
|
43
|
+
export class MailError extends Error {
|
|
44
|
+
override readonly name = "MailError";
|
|
45
|
+
constructor(
|
|
46
|
+
message: string,
|
|
47
|
+
readonly status?: number,
|
|
48
|
+
readonly body?: unknown,
|
|
49
|
+
) {
|
|
50
|
+
super(message);
|
|
51
|
+
}
|
|
52
|
+
get permanent(): boolean {
|
|
53
|
+
return (
|
|
54
|
+
this.status !== undefined &&
|
|
55
|
+
this.status >= 400 &&
|
|
56
|
+
this.status < 500 &&
|
|
57
|
+
this.status !== 409 &&
|
|
58
|
+
this.status !== 429
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Throws unless the message has recipients, a subject and both bodies. */
|
|
64
|
+
export function checkMessage(message: MailMessage): void {
|
|
65
|
+
const to = Array.isArray(message.to) ? message.to : [message.to];
|
|
66
|
+
if (to.length === 0 || to.some((t) => !t.trim()))
|
|
67
|
+
throw new MailError("A message needs at least one recipient.");
|
|
68
|
+
if (!message.subject.trim())
|
|
69
|
+
throw new MailError("A message needs a subject.");
|
|
70
|
+
if (!message.text.trim() || !message.html.trim())
|
|
71
|
+
throw new MailError("A message needs both a text and an HTML body.");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function headersFor(message: MailMessage): Record<string, string> {
|
|
75
|
+
const headers = { ...message.headers };
|
|
76
|
+
if (message.listUnsubscribeUrl) {
|
|
77
|
+
headers["List-Unsubscribe"] = `<${message.listUnsubscribeUrl}>`;
|
|
78
|
+
headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
|
|
79
|
+
}
|
|
80
|
+
return headers;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const formatAddress = (a: MailAddress) =>
|
|
84
|
+
typeof a === "string"
|
|
85
|
+
? a
|
|
86
|
+
: a.name
|
|
87
|
+
? `${a.name.replace(/["\\]/g, "")} <${a.email}>`
|
|
88
|
+
: a.email;
|
|
89
|
+
|
|
90
|
+
/** The `send_email` binding, structurally, so this module needs no Workers types. */
|
|
91
|
+
export interface SendEmailBinding {
|
|
92
|
+
// biome-ignore lint/suspicious/noExplicitAny: the binding's builder type lives in @cloudflare/workers-types.
|
|
93
|
+
send(message: any): Promise<{ messageId?: string } | undefined | void>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Sends through Cloudflare Email Sending. Senders and recipients must be allowed in the binding's wrangler config. */
|
|
97
|
+
export function cloudflareMailer(binding: SendEmailBinding): Mailer {
|
|
98
|
+
return {
|
|
99
|
+
async send(message) {
|
|
100
|
+
checkMessage(message);
|
|
101
|
+
const headers = headersFor(message);
|
|
102
|
+
const from =
|
|
103
|
+
typeof message.from === "string"
|
|
104
|
+
? message.from
|
|
105
|
+
: { email: message.from.email, name: message.from.name ?? "" };
|
|
106
|
+
try {
|
|
107
|
+
const result = await binding.send({
|
|
108
|
+
from,
|
|
109
|
+
to: message.to,
|
|
110
|
+
subject: message.subject,
|
|
111
|
+
text: message.text,
|
|
112
|
+
html: message.html,
|
|
113
|
+
...(message.replyTo
|
|
114
|
+
? {
|
|
115
|
+
replyTo:
|
|
116
|
+
typeof message.replyTo === "string"
|
|
117
|
+
? message.replyTo
|
|
118
|
+
: {
|
|
119
|
+
email: message.replyTo.email,
|
|
120
|
+
name: message.replyTo.name ?? "",
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
: {}),
|
|
124
|
+
...(Object.keys(headers).length ? { headers } : {}),
|
|
125
|
+
...(message.attachments?.length
|
|
126
|
+
? {
|
|
127
|
+
attachments: message.attachments.map((a) => ({
|
|
128
|
+
disposition: "attachment",
|
|
129
|
+
filename: a.filename,
|
|
130
|
+
type: a.contentType ?? "application/octet-stream",
|
|
131
|
+
content: a.content,
|
|
132
|
+
})),
|
|
133
|
+
}
|
|
134
|
+
: {}),
|
|
135
|
+
});
|
|
136
|
+
return result?.messageId ? { id: result.messageId } : {};
|
|
137
|
+
} catch (err) {
|
|
138
|
+
throw new MailError(
|
|
139
|
+
`Email Sending failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface ResendOptions {
|
|
147
|
+
apiKey: string | undefined;
|
|
148
|
+
fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
|
149
|
+
/** Default 10 seconds. */
|
|
150
|
+
timeoutMs?: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Sends through the Resend API with `fetch`, no SDK. */
|
|
154
|
+
export function resendMailer(options: ResendOptions): Mailer {
|
|
155
|
+
const fetcher = options.fetch ?? ((url, init) => fetch(url, init));
|
|
156
|
+
return {
|
|
157
|
+
async send(message) {
|
|
158
|
+
checkMessage(message);
|
|
159
|
+
if (!options.apiKey) throw new MailError("RESEND_API_KEY is not set.");
|
|
160
|
+
const headers = headersFor(message);
|
|
161
|
+
const body: Record<string, unknown> = {
|
|
162
|
+
from: formatAddress(message.from),
|
|
163
|
+
to: message.to,
|
|
164
|
+
subject: message.subject,
|
|
165
|
+
text: message.text,
|
|
166
|
+
html: message.html,
|
|
167
|
+
};
|
|
168
|
+
if (message.replyTo) body.reply_to = formatAddress(message.replyTo);
|
|
169
|
+
if (Object.keys(headers).length) body.headers = headers;
|
|
170
|
+
if (message.attachments?.length) {
|
|
171
|
+
body.attachments = message.attachments.map((a) => ({
|
|
172
|
+
filename: a.filename,
|
|
173
|
+
content: a.content,
|
|
174
|
+
...(a.contentType ? { content_type: a.contentType } : {}),
|
|
175
|
+
}));
|
|
176
|
+
}
|
|
177
|
+
let res: Response;
|
|
178
|
+
try {
|
|
179
|
+
res = await fetcher("https://api.resend.com/emails", {
|
|
180
|
+
method: "POST",
|
|
181
|
+
headers: {
|
|
182
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
183
|
+
"content-type": "application/json",
|
|
184
|
+
...(message.idempotencyKey
|
|
185
|
+
? { "idempotency-key": message.idempotencyKey }
|
|
186
|
+
: {}),
|
|
187
|
+
},
|
|
188
|
+
body: JSON.stringify(body),
|
|
189
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
|
|
190
|
+
});
|
|
191
|
+
} catch (err) {
|
|
192
|
+
throw new MailError(
|
|
193
|
+
`Resend did not answer: ${err instanceof Error ? err.message : String(err)}`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
const json = (await res.json().catch(() => null)) as {
|
|
197
|
+
id?: string;
|
|
198
|
+
message?: string;
|
|
199
|
+
} | null;
|
|
200
|
+
if (!res.ok) {
|
|
201
|
+
throw new MailError(
|
|
202
|
+
`Resend failed (${res.status}): ${json?.message ?? res.statusText}`,
|
|
203
|
+
res.status,
|
|
204
|
+
json,
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
return json?.id ? { id: json.id } : {};
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** A mailer that records what it would send, for tests. It applies the same checks as the real ones. */
|
|
213
|
+
export function recordingMailer(): Mailer & { sent: MailMessage[] } {
|
|
214
|
+
const sent: MailMessage[] = [];
|
|
215
|
+
return {
|
|
216
|
+
sent,
|
|
217
|
+
async send(message) {
|
|
218
|
+
checkMessage(message);
|
|
219
|
+
sent.push(message);
|
|
220
|
+
return { id: `test-${sent.length}` };
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Escapes text for an HTML body. */
|
|
226
|
+
export function escapeHtml(text: string): string {
|
|
227
|
+
return text.replace(
|
|
228
|
+
/[&<>"']/g,
|
|
229
|
+
(c) =>
|
|
230
|
+
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
|
|
231
|
+
c
|
|
232
|
+
] ?? c,
|
|
233
|
+
);
|
|
234
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate limiting on the Workers rate limiting binding, with one answer for
|
|
3
|
+
* every app: the client is keyed by a salted hash of its IP (never the raw
|
|
4
|
+
* address) or by an API key the app names, a missing binding fails open and
|
|
5
|
+
* says so once per isolate, and a limited request gets a 429 problem
|
|
6
|
+
* (RFC 9457) with `Retry-After`, the IETF `RateLimit-Policy` and `RateLimit`
|
|
7
|
+
* headers, and `cache-control: no-store`.
|
|
8
|
+
*
|
|
9
|
+
* The binding counts per Cloudflare location over 10 or 60 seconds. Quotas
|
|
10
|
+
* over hours or days (a plan's daily allowance) are product rules, not abuse
|
|
11
|
+
* limits; keep those in the app's database.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The `ratelimits` binding, structurally. */
|
|
15
|
+
export interface RateLimitBinding {
|
|
16
|
+
limit(options: { key: string }): Promise<{ success: boolean }>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RateLimitPolicy {
|
|
20
|
+
/** Names the limit in the headers, such as `api` or `join`. */
|
|
21
|
+
name: string;
|
|
22
|
+
/** Requests allowed per period. Must match the binding's wrangler config. */
|
|
23
|
+
limit: number;
|
|
24
|
+
/** The binding's period: 10 or 60 seconds. */
|
|
25
|
+
periodSeconds: 10 | 60;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const encoder = new TextEncoder();
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A stable, anonymous key for the client: the SHA-256 of `salt` and the
|
|
32
|
+
* client IP (`cf-connecting-ip`), hex, 32 characters. Without an IP (a
|
|
33
|
+
* request from a test or a service binding) the key is `anon`.
|
|
34
|
+
*/
|
|
35
|
+
export async function clientKey(
|
|
36
|
+
request: Request,
|
|
37
|
+
{ salt = "" }: { salt?: string } = {},
|
|
38
|
+
): Promise<string> {
|
|
39
|
+
const ip = request.headers.get("cf-connecting-ip")?.trim();
|
|
40
|
+
if (!ip) return "anon";
|
|
41
|
+
const digest = await crypto.subtle.digest(
|
|
42
|
+
"SHA-256",
|
|
43
|
+
encoder.encode(`${salt}\n${ip}`),
|
|
44
|
+
);
|
|
45
|
+
return [...new Uint8Array(digest).slice(0, 16)]
|
|
46
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
47
|
+
.join("");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const reported = new WeakSet<object>();
|
|
51
|
+
let reportedUnbound = false;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Whether the request may go ahead. A missing binding allows it (failing
|
|
55
|
+
* closed would take the site down over a config slip) and calls `onUnbound`
|
|
56
|
+
* once per isolate so the slip is seen. So does a binding that throws.
|
|
57
|
+
*/
|
|
58
|
+
export async function checkRateLimit(
|
|
59
|
+
binding: RateLimitBinding | undefined | null,
|
|
60
|
+
key: string,
|
|
61
|
+
{ onUnbound }: { onUnbound?: (error?: unknown) => void } = {},
|
|
62
|
+
): Promise<boolean> {
|
|
63
|
+
if (!binding) {
|
|
64
|
+
if (!reportedUnbound) {
|
|
65
|
+
reportedUnbound = true;
|
|
66
|
+
onUnbound?.();
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
return (await binding.limit({ key })).success;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (!reported.has(binding)) {
|
|
74
|
+
reported.add(binding);
|
|
75
|
+
onUnbound?.(error);
|
|
76
|
+
}
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The IETF rate limit headers for a limited response, with `Retry-After`. */
|
|
82
|
+
export function rateLimitHeaders(
|
|
83
|
+
policy: RateLimitPolicy,
|
|
84
|
+
): Record<string, string> {
|
|
85
|
+
const name = JSON.stringify(policy.name);
|
|
86
|
+
return {
|
|
87
|
+
"retry-after": String(policy.periodSeconds),
|
|
88
|
+
"ratelimit-policy": `${name};q=${policy.limit};w=${policy.periodSeconds}`,
|
|
89
|
+
ratelimit: `${name};r=0;t=${policy.periodSeconds}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The 429 problem for `policy`. `detail` replaces the default sentence. */
|
|
94
|
+
export function tooManyRequests(
|
|
95
|
+
policy: RateLimitPolicy,
|
|
96
|
+
{ detail }: { detail?: string } = {},
|
|
97
|
+
): Response {
|
|
98
|
+
const body = {
|
|
99
|
+
type: "about:blank",
|
|
100
|
+
title: "Too Many Requests",
|
|
101
|
+
status: 429,
|
|
102
|
+
code: "rate_limited",
|
|
103
|
+
detail:
|
|
104
|
+
detail ??
|
|
105
|
+
`Too many requests. Try again in ${policy.periodSeconds} seconds.`,
|
|
106
|
+
};
|
|
107
|
+
return new Response(JSON.stringify(body), {
|
|
108
|
+
status: 429,
|
|
109
|
+
headers: {
|
|
110
|
+
"content-type": "application/problem+json",
|
|
111
|
+
"cache-control": "no-store",
|
|
112
|
+
...rateLimitHeaders(policy),
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface RateLimitOptions {
|
|
118
|
+
/** The key to count by. Defaults to `clientKey(request, { salt })`. */
|
|
119
|
+
key?: string;
|
|
120
|
+
/** Salt for the default IP key, such as a secret from the env. */
|
|
121
|
+
salt?: string;
|
|
122
|
+
/** Let verified bots (`request.cf.verifiedBotCategory`) through uncounted. */
|
|
123
|
+
allowVerifiedBots?: boolean;
|
|
124
|
+
/** Called once per isolate when the binding is missing or fails. */
|
|
125
|
+
onUnbound?: (error?: unknown) => void;
|
|
126
|
+
/** Detail for the 429. */
|
|
127
|
+
detail?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Counts the request against `policy` and returns the 429 to send, or null
|
|
132
|
+
* to go ahead.
|
|
133
|
+
*
|
|
134
|
+
* const limited = await rateLimit(request, env.API_LIMIT, API_POLICY);
|
|
135
|
+
* if (limited) return limited;
|
|
136
|
+
*/
|
|
137
|
+
export async function rateLimit(
|
|
138
|
+
request: Request,
|
|
139
|
+
binding: RateLimitBinding | undefined | null,
|
|
140
|
+
policy: RateLimitPolicy,
|
|
141
|
+
options: RateLimitOptions = {},
|
|
142
|
+
): Promise<Response | null> {
|
|
143
|
+
if (options.allowVerifiedBots) {
|
|
144
|
+
const cf = (request as { cf?: { verifiedBotCategory?: string } }).cf;
|
|
145
|
+
if (cf?.verifiedBotCategory) return null;
|
|
146
|
+
}
|
|
147
|
+
const key =
|
|
148
|
+
options.key ??
|
|
149
|
+
(await clientKey(request, options.salt ? { salt: options.salt } : {}));
|
|
150
|
+
const allowed = await checkRateLimit(
|
|
151
|
+
binding,
|
|
152
|
+
`${policy.name}:${key}`,
|
|
153
|
+
options.onUnbound ? { onUnbound: options.onUnbound } : {},
|
|
154
|
+
);
|
|
155
|
+
return allowed
|
|
156
|
+
? null
|
|
157
|
+
: tooManyRequests(policy, options.detail ? { detail: options.detail } : {});
|
|
158
|
+
}
|
package/src/sentry.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sentry options for a Worker and its pages, without importing an SDK: the
|
|
3
|
+
* objects here go straight into `withSentry` from `@sentry/cloudflare` and
|
|
4
|
+
* `Sentry.init` from a browser SDK.
|
|
5
|
+
*
|
|
6
|
+
* What every app had written for itself: no DSN means no SDK traffic, events
|
|
7
|
+
* from a local server (`wrangler dev`, `vite preview`) never reach the
|
|
8
|
+
* production project, and in the browser the noise that is not the app's to
|
|
9
|
+
* fix (requests that never left the device, extension and injected wallet
|
|
10
|
+
* scripts, users declining a wallet prompt) is dropped. The Worker side gets
|
|
11
|
+
* no message filters: browser wording describes nothing workerd says, so a
|
|
12
|
+
* filter there could only hide a real failure.
|
|
13
|
+
*
|
|
14
|
+
* Release and environment are left unset unless given, so
|
|
15
|
+
* `@sentry/cloudflare` reads `SENTRY_RELEASE` (or `CF_VERSION_METADATA`) and
|
|
16
|
+
* `SENTRY_ENVIRONMENT` from the Worker's env itself.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The part of a Sentry event the filters read. */
|
|
20
|
+
export interface SentryEventLike {
|
|
21
|
+
request?: { url?: string };
|
|
22
|
+
message?: string;
|
|
23
|
+
logentry?: { message?: string };
|
|
24
|
+
exception?: { values?: { value?: string; type?: string }[] };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// biome-ignore lint/suspicious/noExplicitAny: each SDK types its events differently; these options must be assignable to all of them.
|
|
28
|
+
type AnyEvent = any;
|
|
29
|
+
type BeforeSend = (event: AnyEvent, hint: AnyEvent) => AnyEvent;
|
|
30
|
+
|
|
31
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
32
|
+
|
|
33
|
+
/** Whether the event's request was served from this machine. An event with no request (a cron run, a workflow step) is not local. */
|
|
34
|
+
export function isLocalEvent(event: SentryEventLike): boolean {
|
|
35
|
+
const url = event.request?.url;
|
|
36
|
+
if (!url) return false;
|
|
37
|
+
try {
|
|
38
|
+
const host = new URL(url).hostname;
|
|
39
|
+
return LOCAL_HOSTS.has(host) || host.endsWith(".localhost");
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A `beforeSend` that drops local events and keeps the rest. */
|
|
46
|
+
export function dropLocalEvents<T extends SentryEventLike>(event: T): T | null {
|
|
47
|
+
return isLocalEvent(event) ? null : event;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Browser wording for a request that never left the device: Chrome, Safari, Firefox. */
|
|
51
|
+
export const NETWORK_ERROR = /failed to fetch|load failed|network ?error/i;
|
|
52
|
+
/** Errors thrown by extension content scripts and injected wallets. */
|
|
53
|
+
export const EXTENSION_ERROR =
|
|
54
|
+
/func \w+ not found|tronlink|trap returned falsish|origin not allowed|object captured as promise rejection with keys: (?=[^\n]*\bcode\b)(?=[^\n]*\bmessage\b)/i;
|
|
55
|
+
/** A person declining a wallet prompt. */
|
|
56
|
+
export const USER_REJECTION = /user rejected|user denied|rejected the request/i;
|
|
57
|
+
|
|
58
|
+
/** Scripts other people inject into the page: extensions, wallets and Google Translate's proxy. */
|
|
59
|
+
export const BROWSER_DENY_URLS: readonly RegExp[] = [
|
|
60
|
+
/\/_\/translate_http\//i,
|
|
61
|
+
/injected\.js/i,
|
|
62
|
+
/inpage\.js/i,
|
|
63
|
+
/contentscript/i,
|
|
64
|
+
/chrome-extension:\/\//i,
|
|
65
|
+
/moz-extension:\/\//i,
|
|
66
|
+
/safari-(web-)?extension:\/\//i,
|
|
67
|
+
/ms-browser-extension:\/\//i,
|
|
68
|
+
/webkit-masked-url:/i,
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
/** The texts the noise check reads: the exception value, the message and the log entry. */
|
|
72
|
+
function messagesOf(event: SentryEventLike): string[] {
|
|
73
|
+
return [
|
|
74
|
+
event.exception?.values?.[0]?.value,
|
|
75
|
+
event.message,
|
|
76
|
+
event.logentry?.message,
|
|
77
|
+
].filter((m): m is string => typeof m === "string" && m !== "");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Whether a browser event is noise that is not the app's to fix. `extra` adds patterns matched against its messages. */
|
|
81
|
+
export function isBrowserNoise(
|
|
82
|
+
event: SentryEventLike,
|
|
83
|
+
extra: readonly RegExp[] = [],
|
|
84
|
+
): boolean {
|
|
85
|
+
const patterns = [NETWORK_ERROR, EXTENSION_ERROR, USER_REJECTION, ...extra];
|
|
86
|
+
return messagesOf(event).some((m) => patterns.some((re) => re.test(m)));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A DSN worth using: an `https://` URL. Anything else (empty, `off`, a placeholder) turns Sentry off. */
|
|
90
|
+
export function validDsn(dsn: string | null | undefined): string | undefined {
|
|
91
|
+
const value = dsn?.trim();
|
|
92
|
+
return value?.startsWith("https://") ? value : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function chain(...steps: (BeforeSend | undefined)[]): BeforeSend {
|
|
96
|
+
return (event, hint) => {
|
|
97
|
+
let current = event;
|
|
98
|
+
for (const step of steps) {
|
|
99
|
+
if (!step || current === null) continue;
|
|
100
|
+
current = step(current, hint);
|
|
101
|
+
}
|
|
102
|
+
return current;
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface CommonOptions {
|
|
107
|
+
/** Overrides the DSN read from the env. */
|
|
108
|
+
dsn?: string | undefined;
|
|
109
|
+
/** Left unset by default: an unset rate means no tracing at all, where 0 still creates unsampled spans. */
|
|
110
|
+
tracesSampleRate?: number;
|
|
111
|
+
/** Runs after the built-in filters. */
|
|
112
|
+
beforeSend?: BeforeSend;
|
|
113
|
+
/** Tags set on every event, such as `{ runtime: "worker", worker: "api" }`. */
|
|
114
|
+
tags?: Record<string, string>;
|
|
115
|
+
release?: string;
|
|
116
|
+
environment?: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface WorkerSentryOptions {
|
|
120
|
+
dsn: string | undefined;
|
|
121
|
+
enabled: boolean;
|
|
122
|
+
tracesSampleRate?: number;
|
|
123
|
+
beforeSend: BeforeSend;
|
|
124
|
+
beforeSendTransaction: BeforeSend;
|
|
125
|
+
initialScope?: { tags: Record<string, string> };
|
|
126
|
+
release?: string;
|
|
127
|
+
environment?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Options for `withSentry`, `instrumentWorkflowWithSentry` and
|
|
132
|
+
* `instrumentDurableObjectWithSentry`. Reads `SENTRY_DSN` from the env;
|
|
133
|
+
* spread the result and add anything app-specific (integrations, samplers).
|
|
134
|
+
*/
|
|
135
|
+
export function workerSentryOptions(
|
|
136
|
+
env: { SENTRY_DSN?: string | undefined },
|
|
137
|
+
options: CommonOptions = {},
|
|
138
|
+
): WorkerSentryOptions {
|
|
139
|
+
const dsn = validDsn(options.dsn ?? env.SENTRY_DSN);
|
|
140
|
+
const out: WorkerSentryOptions = {
|
|
141
|
+
dsn,
|
|
142
|
+
enabled: dsn !== undefined,
|
|
143
|
+
beforeSend: chain(dropLocalEvents, options.beforeSend),
|
|
144
|
+
beforeSendTransaction: dropLocalEvents,
|
|
145
|
+
};
|
|
146
|
+
if (options.tracesSampleRate !== undefined)
|
|
147
|
+
out.tracesSampleRate = options.tracesSampleRate;
|
|
148
|
+
if (options.tags) out.initialScope = { tags: options.tags };
|
|
149
|
+
if (options.release) out.release = options.release;
|
|
150
|
+
if (options.environment) out.environment = options.environment;
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface BrowserSentryOptions extends WorkerSentryOptions {
|
|
155
|
+
denyUrls: RegExp[];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Options for a browser SDK's `Sentry.init`. Pass the DSN (from the build),
|
|
160
|
+
* and `enabled: false` for dev builds, which the browser cannot tell from
|
|
161
|
+
* the env.
|
|
162
|
+
*/
|
|
163
|
+
export function browserSentryOptions(
|
|
164
|
+
options: CommonOptions & {
|
|
165
|
+
enabled?: boolean;
|
|
166
|
+
/** More script URLs to ignore. */
|
|
167
|
+
denyUrls?: readonly RegExp[];
|
|
168
|
+
/** More messages that are noise. */
|
|
169
|
+
noise?: readonly RegExp[];
|
|
170
|
+
/** Events to keep even when they read like noise, such as handled captures from a wallet flow. */
|
|
171
|
+
keep?: (event: AnyEvent) => boolean;
|
|
172
|
+
} = {},
|
|
173
|
+
): BrowserSentryOptions {
|
|
174
|
+
const dsn = validDsn(options.dsn);
|
|
175
|
+
const noise = options.noise ?? [];
|
|
176
|
+
const out: BrowserSentryOptions = {
|
|
177
|
+
dsn,
|
|
178
|
+
enabled: dsn !== undefined && options.enabled !== false,
|
|
179
|
+
denyUrls: [...BROWSER_DENY_URLS, ...(options.denyUrls ?? [])],
|
|
180
|
+
beforeSend: chain((event) => {
|
|
181
|
+
if (isLocalEvent(event)) return null;
|
|
182
|
+
if (options.keep?.(event)) return event;
|
|
183
|
+
return isBrowserNoise(event, noise) ? null : event;
|
|
184
|
+
}, options.beforeSend),
|
|
185
|
+
beforeSendTransaction: dropLocalEvents,
|
|
186
|
+
};
|
|
187
|
+
if (options.tracesSampleRate !== undefined)
|
|
188
|
+
out.tracesSampleRate = options.tracesSampleRate;
|
|
189
|
+
if (options.tags) out.initialScope = { tags: options.tags };
|
|
190
|
+
if (options.release) out.release = options.release;
|
|
191
|
+
if (options.environment) out.environment = options.environment;
|
|
192
|
+
return out;
|
|
193
|
+
}
|