Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Fix #26802: Implement client-side only JWT secret generation (#26831)

O-Aditya1775dd17dead
diff --git a/apps/docs/components/JwtGenerator/JwtGenerator.tsx b/apps/docs/components/JwtGenerator/JwtGenerator.tsx
index 7191bbc3817..fceaab1c44d 100644
--- a/apps/docs/components/JwtGenerator/JwtGenerator.tsx
+++ b/apps/docs/components/JwtGenerator/JwtGenerator.tsx
@@ -1,5 +1,5 @@
import { KJUR } from 'jsrsasign'
-import { ChangeEvent, useState } from 'react'
+import { useState, ChangeEvent } from 'react'
import { Button, CodeBlock, Input, Select } from 'ui'
const JWT_HEADER = { alg: 'HS256', typ: 'JWT' }
@@ -24,8 +24,41 @@ const serviceToken = `
}
`.trim()
+const generateRandomString = (length: number) => {
+ const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+ let result = ''
+
+ /**
+ * The number of possible Uint8 integers is 256. Since the length of `CHARS`
+ * doesn't fit exactly into 256, simply taking the modulus would create an
+ * uneven distribution that favors the earlier characters. To make a truly
+ * uniform distribution, we have to discard everything above the last full
+ * cycle, and pick again.
+ *
+ * The minus 1 is to account for 0-indexing.
+ */
+ const MAX = Math.floor(256 / CHARS.length) * CHARS.length - 1
+
+ const randomUInt8Array = new Uint8Array(1)
+
+ for (let i = 0; i < length; i++) {
+ let randomNumber: number
+ do {
+ crypto.getRandomValues(randomUInt8Array)
+ randomNumber = randomUInt8Array[0]
+ /**
+ * Keep picking until we get a number in the valid range.
+ */
+ } while (randomNumber > MAX)
+
+ result += CHARS[randomNumber % CHARS.length]
+ }
+
+ return result
+}
+
export default function JwtGenerator({}) {
- const secret = [...Array(40)].map(() => Math.random().toString(36)[2]).join('')
+ const secret = generateRandomString(40)
const [jwtSecret, setJwtSecret] = useState(secret)
const [token, setToken] = useState(anonToken)
diff --git a/apps/docs/components/JwtGenerator/index.tsx b/apps/docs/components/JwtGenerator/index.tsx
index be4fff11c1a..0896688868a 100644
--- a/apps/docs/components/JwtGenerator/index.tsx
+++ b/apps/docs/components/JwtGenerator/index.tsx
@@ -1,11 +1,14 @@
-import { lazy, Suspense } from 'react'
+import dynamic from 'next/dynamic'
+import { Suspense } from 'react'
-const Generator = lazy(() => import('./JwtGenerator'))
+const DynamicJwtGenerator = dynamic(() => import('./JwtGenerator'), { ssr: false })
-export function JwtGenerator() {
+const JwtGenerator = () => {
return (
- <Suspense>
- <Generator />
+ <Suspense fallback={<div>Loading...</div>}>
+ <DynamicJwtGenerator />
</Suspense>
)
}
+
+export { JwtGenerator }