New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

toucan-js

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

toucan-js

Cloudflare Workers client for Sentry

  • 2.5.0-beta.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
79K
increased by26.59%
Maintainers
1
Weekly downloads
 
Created
Source

Logo

npm version npm version npm version

toucan-js

Toucan is a reliable Sentry client for Cloudflare Workers. Follows Sentry unified API guidelines.

Motivation

In Cloudflare Workers isolate model, it is inadvisable to set or mutate global state within the event handler. The most of JavaScript SDKs use static methods that mutate global state with request metadata, breadcrumbs, tags, and other extra properties. This is reasonable, because they were implemented for environments where concurrency does not inherently exist. However, using these SDKs in Workers leads to race conditions, such as logging breadrumbs, request data, and other metadata of interleaved events.

Toucan was created with Workers concurrent model in mind. It is a class that is instantiated per-event rather than globally, meaning this kind of race-conditions do not exist, because all request metadata are scoped to a particular fetch event.

Usage

npm install --save toucan-js

worker.ts

import Toucan from "toucan-js";

addEventListener("fetch", (event) => {
  const sentry = new Toucan({
    dsn: "dsn...",
    event,
    allowedHeaders: ["user-agent"],
    allowedSearchParams: /(.*)/,
  });

  sentry.setUser({ id: "1234" });

  event.respondWith(doStuff(event, sentry));
});

async function doStuff(event: FetchEvent, sentry: Toucan) {
  try {
    sentry.addBreadcrumb({
      message: "About to do something",
      category: "log",
    });

    // ...code that may throw

    return new Response("OK", {
      status: 200,
      statusText: "OK",
    });
  } catch (err) {
    sentry.captureException(err);
    return new Response("Something went wrong", {
      status: 500,
      statusText: "Internal Server Error",
    });
  }
}

Features

  • addBreadcumb: Records a new breadcrumb which will be attached to future events.
  • captureException: Captures an exception event and sends it to Sentry.
  • captureMessage: Captures a message event and sends it to Sentry.
  • setRequestBody: Records incoming request's body which will be attached to future events.
  • setTag: Set key:value that will be sent as tags data with the event.
  • setTags: Set an object that will be merged sent as tags data with the event.
  • setExtra: Set key:value that will be sent as extra data with the event.
  • setExtras: Set an object that will be merged sent as extra data with the event.
  • setUser: Updates user context information for future events.
  • setFingerprint: Overrides the Sentry default grouping.
  • withScope: Creates a new scope and executes the given operation within. The scope is automatically removed once the operation finishes or throws.

Minimal options

OptionTypeDescription
context*ContextOnly available in 2.5.0-beta.1 and optional if event is set. This can be any object that contains waitUntil, and optionally request. It is the most universal way to instantiate Toucan in any kind of Cloudflare Worker. It can be FetchEvent, ScheduledEvent, DurableObjectState, or .mjs context. Note that DurableObjectState and .mjs ctx don't include request, you will need to set it as 'request' option.
event*FetchEvent | ScheduledEventWorkers event. Toucan needs this to be able to call waitUntil. Optional in 2.5.0-beta.1 if context is set.
dsnstringSentry Data Source Name. If an empty DSN is passed, we treat it as valid option which signifies disabling the SDK.

Other options

OptionTypeDescription
allowedCookiesstring[] | RegExpArray of allowed cookies, or a regular expression used to explicitly allow cookies of incoming request. If not provided, cookies will not be logged. No effect without request in context.
allowedHeadersstring[] | RegExpArray of allowed headers, or a regular expression used to explicitly allow headers of incoming request. If not provided, headers will not be logged. No effect without request in context.
allowedSearchParamsstring[] | RegExpArray of allowed search params, or a regular expression used to explicitly allow search params of incoming request. If not provided, search params will not be logged. No effect without request in context.
attachStacktracebooleanAttaches stacktraces to capture message. Default true.
beforeSend(event: Event) => EventThis function is applied to all events before sending to Sentry. If provided, all allowlists are ignored.
debugbooleanTurns debug mode on or off. If debug is enabled, toucan-js will attempt to print out useful debugging information.
environmentstringYour application's environment (production/staging/...).
maxBreadcrumbsnumberThis variable controls the total amount of breadcrumbs that should be captured. This defaults to 100.
pkgobjectEssentially your package.json. Toucan will use it to read project name, version, dependencies, and devDependencies.
releasestringRelease tag.
requestRequestOnly available in 2.5.0-beta.1. You will want to use this option in Durable Object or .mjs Worker, where request isn't included in context.
rewriteFrames{ root?: string, iteratee?: (frame: StackFrame) => StackFrame }Allows you to apply a transformation to each frame of the stack trace. root path will be appended to the basename of the current frame's url. iteratee is a function that takes the frame, applies any transformation on it and returns it back.
sampleRatenumberConfigures the sample rate as a percentage of events to be sent in the range of 0.0 to 1.0. The default is 1.0 which means that 100% of events are sent. If set to 0.1 only 10% of events will be sent. Events are picked randomly.
transportOptions{ headers?: Record<string, string> }Custom headers to be passed to Sentry.

Sensitive data

By default, Toucan does not send any Request property that could carry PII (Personally Identifiable Information) to Sentry.

This includes:

  • All request Headers
  • All request Cookies
  • All request search params
  • Request body

You will need to explicitly allow these data using:

  • allowedHeaders option (array of headers or Regex)
  • allowedCookies option (array of cookies or Regex)
  • allowedSearchParams option (array of search params or Regex)
  • toucan.setRequestBody function
  • beforeSend option (if you need more flexibility than allowedX functions)

Known issues

Source Maps

Make sure to use the absolute paths on the stack frames and Sentry's artifacts, the default ~/ will not match them properly. Any absolute path will work (i.e., /). You will need to use rewriteFrames option to add the prefix to the stack frames.

const toucan = new Toucan({
  dsn: ...
  event,
  rewriteFrames: {
    root: '/'
  }
}

Changing the Sentry's artifacts URL depends on plugin you use to upload your source maps.

Example configuration using @sentry/webpack-plugin:

const SentryWebpackPlugin = require("@sentry/webpack-plugin");
const pkg = require("./package.json");

module.exports = {
  entry: "./src/index.ts",
  target: "webworker",
  devtool: "source-map",
  plugins: [
    new SentryWebpackPlugin({
      release: `${pkg.name}-${pkg.version}`,
      include: "./dist",
      urlPrefix: "/",
    }),
  ],
};

For more information, see this issue.

Keywords

FAQs

Package last updated on 01 May 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc