Skip to content

Commit

Permalink
chore: temporary commit (#358)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-app[bot] authored and stainless-bot committed Mar 27, 2024
1 parent 5837819 commit 14ae9bf
Show file tree
Hide file tree
Showing 16 changed files with 1 addition and 1,548 deletions.
161 changes: 0 additions & 161 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@

This library provides convenient access to the Mux REST API from server-side TypeScript or JavaScript.

> [!NOTE]
> In February 2024 this SDK was updated to Version 8.0. For upgrading to 8.x see [UPGRADE_8.x.md](https://github.com/muxinc/mux-node-sdk/blob/master/UPGRADE_8.x.md)
The REST API documentation can be found [on docs.mux.com](https://docs.mux.com). The full API of this library can be found in [api.md](api.md).

## Installation
Expand Down Expand Up @@ -66,164 +63,6 @@ main();

Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.

## JWT Helpers ([API Reference](https://github.com/muxinc/mux-node-sdk/blob/master/api.md#jwt))

You can use any JWT-compatible library, but we've included some light helpers in the SDK to make it easier to get up and running.

```js
// Assuming you have your signing key specified in your environment variables:
// Signing token ID: process.env.MUX_SIGNING_KEY
// Signing token secret: process.env.MUX_PRIVATE_KEY

// Most simple request, defaults to type video and is valid for 7 days.
const token = mux.jwt.signPlaybackId('some-playback-id');
// https://stream.mux.com/some-playback-id.m3u8?token=${token}

// If you wanted to sign a thumbnail
const thumbParams = { time: 14, width: 100 };
const thumbToken = mux.jwt.signPlaybackId('some-playback-id', {
type: 'thumbnail',
params: thumbParams,
});
// https://image.mux.com/some-playback-id/thumbnail.jpg?token=${token}

// If you wanted to sign a gif
const gifToken = mux.jwt.signPlaybackId('some-playback-id', { type: 'gif' });
// https://image.mux.com/some-playback-id/animated.gif?token=${token}

// Here's an example for a storyboard
const storyboardToken = mux.jwt.signPlaybackId('some-playback-id', {
type: 'storyboard',
});

// https://image.mux.com/some-playback-id/storyboard.jpg?token=${token}

// You can also use `signViewerCounts` to get a token
// used for requests to the Mux Engagement Counts API
// https://docs.mux.com/guides/see-how-many-people-are-watching
const statsToken = mux.jwt.signViewerCounts('some-live-stream-id', {
type: 'live_stream',
});

// https://stats.mux.com/counts?token={statsToken}
```

## Parsing Webhook payloads

To validate that the given payload was sent by Mux and parse the webhook payload for use in your application,
you can use the `mux.webhooks.unwrap` utility method.

This method accepts a raw `body` string and a list of headers. As long as you have set your `webhookSecret` in the
appropriate configuration property when instantiating the library, all webhooks will be verified for authenticity automatically.

The following example shows how you can handle a webhook using a Next.js app directory API route:

```js
// app/api/mux/webhooks/route.ts
import { revalidatePath } from 'next/cache';
import { headers } from 'next/headers';

import Mux from '@mux/mux-node';

const mux = new Mux({
webhookSecret: process.env.MUX_WEBHOOK_SECRET,
});

export async function POST(request: Request) {
const headersList = headers();
const body = await request.text();
const event = mux.webhooks.unwrap(body, headersList);

switch (event.type) {
case 'video.live_stream.active':
case 'video.live_stream.idle':
case 'video.live_stream.disabled':
/**
* `event` is now understood to be one of the following types:
*
* | Mux.Webhooks.VideoLiveStreamActiveWebhookEvent
* | Mux.Webhooks.VideoLiveStreamIdleWebhookEvent
* | Mux.Webhooks.VideoLiveStreamDisabledWebhookEvent
*/
if (event.data.id === 'MySpecialTVLiveStreamID') {
revalidatePath('/tv');
}
break;
default:
break;
}

return Response.json({ message: 'ok' });
}
```

## Verifying Webhook Signatures

Verifying Webhook Signatures is _optional but encouraged_. Learn more in our [Webhook Security Guide](https://docs.mux.com/docs/webhook-security)

```js
/*
If the header is valid, this function will not throw an error and will not return a value.
If the header is invalid, this function will throw one of the following errors:
- new Error(
"The webhook secret must either be set using the env var, MUX_WEBHOOK_SECRET, on the client class, Mux({ webhookSecret: '123' }), or passed to this function",
);
- new Error('Could not find a mux-signature header');
- new Error(
'Webhook body must be passed as the raw JSON string sent from the server (do not parse it first).',
);
- new Error('Unable to extract timestamp and signatures from header')
- new Error('No v1 signatures found');
- new Error('No signatures found matching the expected signature for payload.')
- new Error('Webhook timestamp is too old')
*/

/*
`body` is the raw request body. It should be a string representation of a JSON object.
`headers` is the value in request.headers
`secret` is the signing secret for this configured webhook. You can find that in your webhooks dashboard
(note that this secret is different than your API Secret Key)
*/

mux.webhooks.verifySignature(body, headers, secret);
```

Note that when passing in the payload (body) you want to pass in the raw un-parsed request body, not the parsed JSON. Here's an example if you are using express.

```js
const Mux = require('@mux/mux-node');
const mux = new Mux();
const express = require('express');
const bodyParser = require('body-parser');

/**
* You'll need to make sure this is externally accessible. ngrok (https://ngrok.com/)
* makes this really easy.
*/

const webhookSecret = process.env.WEBHOOK_SECRET;
const app = express();

app.post('/webhooks', bodyParser.raw({ type: 'application/json' }), async (req, res) => {
try {
// will raise an exception if the signature is invalid
const isValidSignature = mux.webhooks.verifySignature(req.body, req.headers, webhookSecret);
console.log('Success:', isValidSignature);
// convert the raw req.body to JSON, which is originally Buffer (raw)
const jsonFormattedBody = JSON.parse(req.body);
// await doSomething();
res.json({ received: true });
} catch (err) {
// On error, return the error message
return res.status(400).send(`Webhook Error: ${err.message}`);
}
});

app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
```

## Handling errors

When the library is unable to connect to the API,
Expand Down
11 changes: 0 additions & 11 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -387,14 +387,3 @@ Types:
- <code><a href="./src/resources/webhooks.ts">UnwrapWebhookEvent</a></code>

Methods:

- <code>client.webhooks.<a href="./src/resources/webhooks.ts">unwrap</a>(body, headers, secret) -> UnwrapWebhookEvent</code>
- <code>client.webhooks.<a href="./src/resources/webhooks.ts">verifySignature</a>(body, headers, secret) -> void</code>

# Jwt

Methods:

- <code>client.jwt.<a href="./src/resources/jwt.ts">signPlaybackId</a>(playbackId, config) -> Promise&lt;string&gt;</code>
- <code>client.jwt.<a href="./src/resources/jwt.ts">signSpaceId</a>(spaceId, config) -> Promise&lt;string&gt;</code>
- <code>client.jwt.<a href="./src/resources/jwt.ts">signViewerCounts</a>(id, config) -> Promise&lt;string&gt;</code>
180 changes: 0 additions & 180 deletions deno_tests/api-resources/jwt.test.ts

This file was deleted.

Loading

0 comments on commit 14ae9bf

Please sign in to comment.