next-sanity 2.0.2 → 2.1.0-webhook.1

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
@@ -28,6 +28,7 @@
28
28
  - [Opt-in to using `StudioProvider` and `StudioLayout`](#opt-in-to-using-studioprovider-and-studiolayout)
29
29
  - [Customize `<ServerStyleSheetDocument />`](#customize-serverstylesheetdocument-)
30
30
  - [Full-control mode](#full-control-mode)
31
+ - [`next-sanity/webhook`](#next-sanitywebhook)
31
32
  - [Migrate](#migrate)
32
33
  - [From `v1`](#from-v1)
33
34
  - [`createPreviewSubscriptionHook` is replaced with `definePreview`](#createpreviewsubscriptionhook-is-replaced-with-definepreview)
@@ -596,6 +597,42 @@ function Studiopage() {
596
597
  }
597
598
  ```
598
599
 
600
+ ## `next-sanity/webhook`
601
+
602
+ Implements [`@sanity/webhook`](https://github.com/sanity-io/webhook-toolkit) to parse and verify that a [Webhook](https://www.sanity.io/docs/webhooks) is indeed coming from Sanity infrastructure.
603
+
604
+ `pages/api/revalidate`:
605
+
606
+ ```ts
607
+ import type {NextApiRequest, NextApiResponse} from 'next'
608
+ import {parseBody} from 'next-sanity/webhook'
609
+
610
+ // Export the config from next-sanity to enable validating the request body signature properly
611
+ export {config} from 'next-sanity/webhook'
612
+
613
+ export default async function revalidate(req: NextApiRequest, res: NextApiResponse) {
614
+ try {
615
+ const {isValidSignature, body} = await parseBody(req, process.env.SANITY_REVALIDATE_SECRET)
616
+
617
+ if (!isValidSignature) {
618
+ const message = 'Invalid signature'
619
+ console.warn(message)
620
+ res.status(401).json({message})
621
+ return
622
+ }
623
+
624
+ const staleRoute = `/${body.slug.current}`
625
+ await res.revalidate(staleRoute)
626
+ const message = `Updated route: ${staleRoute}`
627
+ console.log(message)
628
+ return res.status(200).json({message})
629
+ } catch (err) {
630
+ console.error(err)
631
+ return res.status(500).json({message: err.message})
632
+ }
633
+ }
634
+ ```
635
+
599
636
  ## Migrate
600
637
 
601
638
  ### From `v1`
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', {
4
+ value: true
5
+ });
6
+ var sanityWebhook = require('@sanity/webhook');
7
+ function _interopDefaultLegacy(e) {
8
+ return e && typeof e === 'object' && 'default' in e ? e : {
9
+ 'default': e
10
+ };
11
+ }
12
+ var sanityWebhook__default = /*#__PURE__*/_interopDefaultLegacy(sanityWebhook);
13
+ const config = {
14
+ api: {
15
+ bodyParser: false
16
+ }
17
+ };
18
+ async function _readBody(readable) {
19
+ const chunks = [];
20
+ for await (const chunk of readable) {
21
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
22
+ }
23
+ return Buffer.concat(chunks).toString("utf8");
24
+ }
25
+ const {
26
+ isValidSignature,
27
+ SIGNATURE_HEADER_NAME
28
+ } = sanityWebhook__default["default"];
29
+ async function parseBody(req, secret, waitForContentLakeEventualConsistency) {
30
+ let signature = req.headers[SIGNATURE_HEADER_NAME];
31
+ if (Array.isArray(signature)) {
32
+ signature = signature[0];
33
+ }
34
+ const body = await _readBody(req);
35
+ const validSignature = secret ? isValidSignature(body, signature, secret.trim()) : null;
36
+ if (validSignature !== false && waitForContentLakeEventualConsistency) {
37
+ await new Promise(resolve => setTimeout(resolve, 1e3));
38
+ }
39
+ return {
40
+ body: JSON.parse(body),
41
+ isValidSignature: validSignature
42
+ };
43
+ }
44
+ exports.config = config;
45
+ exports.parseBody = parseBody;
46
+ //# sourceMappingURL=webhook.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.cjs","sources":["../src/webhook/config.ts","../src/webhook/readBody.ts","../src/webhook/parseBody.ts"],"sourcesContent":["/**\n * Next.js will by default parse the body, which can lead to invalid signatures\n * @public\n */\nexport const config = {api: {bodyParser: false}}\n","import type {NextApiRequest} from 'next'\n\n/** @internal */\nexport async function _readBody(readable: NextApiRequest): Promise<string> {\n const chunks = []\n for await (const chunk of readable) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n","import type {SanityDocument} from '@sanity/types'\nimport sanityWebhook from '@sanity/webhook'\nimport type {NextApiRequest} from 'next'\n\n// As `@sanity/webhook` isn't shipping ESM, extracting from the default export have the best ecosystem support\nconst {isValidSignature, SIGNATURE_HEADER_NAME} = sanityWebhook\n\nimport {_readBody as readBody} from './readBody'\n\n/** @public */\nexport type ParseBody = {\n /**\n * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`\n */\n isValidSignature: boolean | null\n body: SanityDocument\n}\n/**\n * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries\n * without worrying about getting stale data.\n * @public\n */\nexport async function parseBody(\n req: NextApiRequest,\n secret?: string,\n waitForContentLakeEventualConsistency?: boolean\n): Promise<ParseBody> {\n let signature = req.headers[SIGNATURE_HEADER_NAME]!\n if (Array.isArray(signature)) {\n signature = signature[0]\n }\n\n // Read the body into a string\n const body = await readBody(req)\n // Then we're able to verify the checksum signature\n const validSignature = secret ? isValidSignature(body, signature, secret.trim()) : null\n\n if (validSignature !== false && waitForContentLakeEventualConsistency) {\n // Wait a second to give Elastic Search time to reach eventual consistency\n await new Promise((resolve) => setTimeout(resolve, 1000))\n }\n\n return {\n body: JSON.parse(body),\n isValidSignature: validSignature,\n }\n}\n"],"names":["config","api","bodyParser","_readBody","readable","chunks","chunk","push","Buffer","from","concat","toString","isValidSignature","SIGNATURE_HEADER_NAME","sanityWebhook","parseBody","req","secret","waitForContentLakeEventualConsistency","signature","headers","Array","isArray","body","readBody","validSignature","trim","Promise","resolve","setTimeout","JSON","parse"],"mappings":";;;;;;;;;;;;AAIO,MAAMA,SAAS;EAACC,GAAA,EAAK;IAACC,UAAA,EAAY;EAAM;AAAA,CAAA;ACD/C,eAAsBC,UAAUC,QAA2C,EAAA;EACzE,MAAMC,SAAS,EAAC;EAChB,WAAA,MAAiBC,SAASF,QAAU,EAAA;IAC3BC,MAAA,CAAAE,IAAA,CAAK,OAAOD,KAAU,KAAA,QAAA,GAAWE,OAAOC,IAAK,CAAAH,KAAK,IAAIA,KAAK,CAAA;EACpE;EACA,OAAOE,MAAO,CAAAE,MAAA,CAAOL,MAAM,CAAA,CAAEM,SAAS,MAAM,CAAA;AAC9C;ACJA,MAAM;EAACC,gBAAkB;EAAAC;AAAyB,CAAA,GAAAC,iCAAA;AAiB5B,eAAAC,SAAA,CACpBC,GACA,EAAAC,MAAA,EACAC,qCACoB,EAAA;EAChB,IAAAC,SAAA,GAAYH,IAAII,OAAQ,CAAAP,qBAAA,CAAA;EACxB,IAAAQ,KAAA,CAAMC,OAAQ,CAAAH,SAAS,CAAG,EAAA;IAC5BA,SAAA,GAAYA,SAAU,CAAA,CAAA,CAAA;EACxB;EAGM,MAAAI,IAAA,GAAO,MAAMC,SAAA,CAASR,GAAG,CAAA;EAEzB,MAAAS,cAAA,GAAiBR,SAASL,gBAAiB,CAAAW,IAAA,EAAMJ,WAAWF,MAAO,CAAAS,IAAA,EAAM,CAAI,GAAA,IAAA;EAE/E,IAAAD,cAAA,KAAmB,SAASP,qCAAuC,EAAA;IAErE,MAAM,IAAIS,OAAQ,CAACC,WAAYC,UAAW,CAAAD,OAAA,EAAS,GAAI,CAAC,CAAA;EAC1D;EAEO,OAAA;IACLL,IAAA,EAAMO,IAAK,CAAAC,KAAA,CAAMR,IAAI,CAAA;IACrBX,gBAAkB,EAAAa;EAAA,CACpB;AACF;;"}
@@ -0,0 +1,34 @@
1
+ import type {NextApiRequest} from 'next'
2
+ import type {SanityDocument} from '@sanity/types'
3
+
4
+ /**
5
+ * Next.js will by default parse the body, which can lead to invalid signatures
6
+ * @public
7
+ */
8
+ export declare const config: {
9
+ api: {
10
+ bodyParser: boolean
11
+ }
12
+ }
13
+
14
+ /** @public */
15
+ export declare type ParseBody = {
16
+ /**
17
+ * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`
18
+ */
19
+ isValidSignature: boolean | null
20
+ body: SanityDocument
21
+ }
22
+
23
+ /**
24
+ * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries
25
+ * without worrying about getting stale data.
26
+ * @public
27
+ */
28
+ export declare function parseBody(
29
+ req: NextApiRequest,
30
+ secret?: string,
31
+ waitForContentLakeEventualConsistency?: boolean
32
+ ): Promise<ParseBody>
33
+
34
+ export {}
@@ -0,0 +1,34 @@
1
+ import sanityWebhook from '@sanity/webhook';
2
+ const config = {
3
+ api: {
4
+ bodyParser: false
5
+ }
6
+ };
7
+ async function _readBody(readable) {
8
+ const chunks = [];
9
+ for await (const chunk of readable) {
10
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
11
+ }
12
+ return Buffer.concat(chunks).toString("utf8");
13
+ }
14
+ const {
15
+ isValidSignature,
16
+ SIGNATURE_HEADER_NAME
17
+ } = sanityWebhook;
18
+ async function parseBody(req, secret, waitForContentLakeEventualConsistency) {
19
+ let signature = req.headers[SIGNATURE_HEADER_NAME];
20
+ if (Array.isArray(signature)) {
21
+ signature = signature[0];
22
+ }
23
+ const body = await _readBody(req);
24
+ const validSignature = secret ? isValidSignature(body, signature, secret.trim()) : null;
25
+ if (validSignature !== false && waitForContentLakeEventualConsistency) {
26
+ await new Promise(resolve => setTimeout(resolve, 1e3));
27
+ }
28
+ return {
29
+ body: JSON.parse(body),
30
+ isValidSignature: validSignature
31
+ };
32
+ }
33
+ export { config, parseBody };
34
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","sources":["../src/webhook/config.ts","../src/webhook/readBody.ts","../src/webhook/parseBody.ts"],"sourcesContent":["/**\n * Next.js will by default parse the body, which can lead to invalid signatures\n * @public\n */\nexport const config = {api: {bodyParser: false}}\n","import type {NextApiRequest} from 'next'\n\n/** @internal */\nexport async function _readBody(readable: NextApiRequest): Promise<string> {\n const chunks = []\n for await (const chunk of readable) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n","import type {SanityDocument} from '@sanity/types'\nimport sanityWebhook from '@sanity/webhook'\nimport type {NextApiRequest} from 'next'\n\n// As `@sanity/webhook` isn't shipping ESM, extracting from the default export have the best ecosystem support\nconst {isValidSignature, SIGNATURE_HEADER_NAME} = sanityWebhook\n\nimport {_readBody as readBody} from './readBody'\n\n/** @public */\nexport type ParseBody = {\n /**\n * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`\n */\n isValidSignature: boolean | null\n body: SanityDocument\n}\n/**\n * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries\n * without worrying about getting stale data.\n * @public\n */\nexport async function parseBody(\n req: NextApiRequest,\n secret?: string,\n waitForContentLakeEventualConsistency?: boolean\n): Promise<ParseBody> {\n let signature = req.headers[SIGNATURE_HEADER_NAME]!\n if (Array.isArray(signature)) {\n signature = signature[0]\n }\n\n // Read the body into a string\n const body = await readBody(req)\n // Then we're able to verify the checksum signature\n const validSignature = secret ? isValidSignature(body, signature, secret.trim()) : null\n\n if (validSignature !== false && waitForContentLakeEventualConsistency) {\n // Wait a second to give Elastic Search time to reach eventual consistency\n await new Promise((resolve) => setTimeout(resolve, 1000))\n }\n\n return {\n body: JSON.parse(body),\n isValidSignature: validSignature,\n }\n}\n"],"names":["config","api","bodyParser","_readBody","readable","chunks","chunk","push","Buffer","from","concat","toString","isValidSignature","SIGNATURE_HEADER_NAME","sanityWebhook","parseBody","req","secret","waitForContentLakeEventualConsistency","signature","headers","Array","isArray","body","readBody","validSignature","trim","Promise","resolve","setTimeout","JSON","parse"],"mappings":";AAIO,MAAMA,SAAS;EAACC,GAAA,EAAK;IAACC,UAAA,EAAY;EAAM;AAAA,CAAA;ACD/C,eAAsBC,UAAUC,QAA2C,EAAA;EACzE,MAAMC,SAAS,EAAC;EAChB,WAAA,MAAiBC,SAASF,QAAU,EAAA;IAC3BC,MAAA,CAAAE,IAAA,CAAK,OAAOD,KAAU,KAAA,QAAA,GAAWE,OAAOC,IAAK,CAAAH,KAAK,IAAIA,KAAK,CAAA;EACpE;EACA,OAAOE,MAAO,CAAAE,MAAA,CAAOL,MAAM,CAAA,CAAEM,SAAS,MAAM,CAAA;AAC9C;ACJA,MAAM;EAACC,gBAAkB;EAAAC;AAAyB,CAAA,GAAAC,aAAA;AAiB5B,eAAAC,SAAA,CACpBC,GACA,EAAAC,MAAA,EACAC,qCACoB,EAAA;EAChB,IAAAC,SAAA,GAAYH,IAAII,OAAQ,CAAAP,qBAAA,CAAA;EACxB,IAAAQ,KAAA,CAAMC,OAAQ,CAAAH,SAAS,CAAG,EAAA;IAC5BA,SAAA,GAAYA,SAAU,CAAA,CAAA,CAAA;EACxB;EAGM,MAAAI,IAAA,GAAO,MAAMC,SAAA,CAASR,GAAG,CAAA;EAEzB,MAAAS,cAAA,GAAiBR,SAASL,gBAAiB,CAAAW,IAAA,EAAMJ,WAAWF,MAAO,CAAAS,IAAA,EAAM,CAAI,GAAA,IAAA;EAE/E,IAAAD,cAAA,KAAmB,SAASP,qCAAuC,EAAA;IAErE,MAAM,IAAIS,OAAQ,CAACC,WAAYC,UAAW,CAAAD,OAAA,EAAS,GAAI,CAAC,CAAA;EAC1D;EAEO,OAAA;IACLL,IAAA,EAAMO,IAAK,CAAAC,KAAA,CAAMR,IAAI,CAAA;IACrBX,gBAAkB,EAAAa;EAAA,CACpB;AACF;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "2.0.2",
3
+ "version": "2.1.0-webhook.1",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "sanity",
@@ -50,6 +50,13 @@
50
50
  "require": "./dist/studio.cjs",
51
51
  "default": "./dist/studio.js"
52
52
  },
53
+ "./webhook": {
54
+ "types": "./dist/webhook.d.ts",
55
+ "source": "./src/webhook/index.ts",
56
+ "import": "./dist/webhook.js",
57
+ "require": "./dist/webhook.cjs",
58
+ "default": "./dist/webhook.js"
59
+ },
53
60
  "./package.json": "./package.json"
54
61
  },
55
62
  "main": "./dist/index.cjs",
@@ -63,6 +70,9 @@
63
70
  ],
64
71
  "studio": [
65
72
  "./dist/studio.d.ts"
73
+ ],
74
+ "webhook": [
75
+ "./dist/webhook.d.ts"
66
76
  ]
67
77
  }
68
78
  },
@@ -101,6 +111,7 @@
101
111
  "dependencies": {
102
112
  "@sanity/client": "^3.4.1",
103
113
  "@sanity/preview-kit": "^1.2.8",
114
+ "@sanity/webhook": "^2.0.0",
104
115
  "groq": "^2.33.2"
105
116
  },
106
117
  "devDependencies": {
@@ -119,7 +130,7 @@
119
130
  "@types/styled-components": "^5.1.26",
120
131
  "@typescript-eslint/eslint-plugin": "^5.43.0",
121
132
  "autoprefixer": "^10.4.13",
122
- "eslint": "^8.27.0",
133
+ "eslint": "^8.28.0",
123
134
  "eslint-config-next": "13.0.4",
124
135
  "eslint-config-prettier": "^8.5.0",
125
136
  "eslint-config-sanity": "^6.0.0",
@@ -144,12 +155,16 @@
144
155
  "typescript": "^4.9.3"
145
156
  },
146
157
  "peerDependencies": {
158
+ "@sanity/types": "*",
147
159
  "next": "^12 || ^13",
148
160
  "react": "^16.3 || ^17 || ^18",
149
161
  "sanity": "dev-preview",
150
162
  "styled-components": "^5.2"
151
163
  },
152
164
  "peerDependenciesMeta": {
165
+ "@sanity/types": {
166
+ "optional": true
167
+ },
153
168
  "sanity": {
154
169
  "optional": true
155
170
  },
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Next.js will by default parse the body, which can lead to invalid signatures
3
+ * @public
4
+ */
5
+ export const config = {api: {bodyParser: false}}
@@ -0,0 +1,2 @@
1
+ export * from './config'
2
+ export * from './parseBody'
@@ -0,0 +1,47 @@
1
+ import type {SanityDocument} from '@sanity/types'
2
+ import sanityWebhook from '@sanity/webhook'
3
+ import type {NextApiRequest} from 'next'
4
+
5
+ // As `@sanity/webhook` isn't shipping ESM, extracting from the default export have the best ecosystem support
6
+ const {isValidSignature, SIGNATURE_HEADER_NAME} = sanityWebhook
7
+
8
+ import {_readBody as readBody} from './readBody'
9
+
10
+ /** @public */
11
+ export type ParseBody = {
12
+ /**
13
+ * If a secret is given then it returns a boolean. If no secret is provided then no validation is done on the signature, and it'll return `null`
14
+ */
15
+ isValidSignature: boolean | null
16
+ body: SanityDocument
17
+ }
18
+ /**
19
+ * Handles parsing the body JSON, and validating its signature. Also waits for Content Lake eventual consistency so you can run your queries
20
+ * without worrying about getting stale data.
21
+ * @public
22
+ */
23
+ export async function parseBody(
24
+ req: NextApiRequest,
25
+ secret?: string,
26
+ waitForContentLakeEventualConsistency?: boolean
27
+ ): Promise<ParseBody> {
28
+ let signature = req.headers[SIGNATURE_HEADER_NAME]!
29
+ if (Array.isArray(signature)) {
30
+ signature = signature[0]
31
+ }
32
+
33
+ // Read the body into a string
34
+ const body = await readBody(req)
35
+ // Then we're able to verify the checksum signature
36
+ const validSignature = secret ? isValidSignature(body, signature, secret.trim()) : null
37
+
38
+ if (validSignature !== false && waitForContentLakeEventualConsistency) {
39
+ // Wait a second to give Elastic Search time to reach eventual consistency
40
+ await new Promise((resolve) => setTimeout(resolve, 1000))
41
+ }
42
+
43
+ return {
44
+ body: JSON.parse(body),
45
+ isValidSignature: validSignature,
46
+ }
47
+ }
@@ -0,0 +1,10 @@
1
+ import type {NextApiRequest} from 'next'
2
+
3
+ /** @internal */
4
+ export async function _readBody(readable: NextApiRequest): Promise<string> {
5
+ const chunks = []
6
+ for await (const chunk of readable) {
7
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
8
+ }
9
+ return Buffer.concat(chunks).toString('utf8')
10
+ }