The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: sign impersonation JWT with browser crypto (#20212)
Kevin Grünebergefda65478991
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsxindex 98e81352ae6..20b7df8106a 100644--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx@@ -1,4 +1,5 @@import { Dispatch, SetStateAction, useEffect } from 'react'+import toast from 'react-hot-toast'import { RoleImpersonationPopover } from 'components/interfaces/RoleImpersonationSelector'import { useProjectApiQuery } from 'data/config/project-api-query'@@ -42,7 +43,9 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokenssnap.role.type === 'postgrest') {token = anonRoleKey- bearer = getRoleImpersonationJWT(config.projectRef, jwtSecret, snap.role)+ getRoleImpersonationJWT(config.projectRef, jwtSecret, snap.role)+ .then((token) => (bearer = token))+ .catch((err) => toast.error(`Failed to get JWT for role: ${err.message}`))} else {token = serviceRoleKey}diff --git a/apps/studio/lib/role-impersonation.ts b/apps/studio/lib/role-impersonation.tsindex 7e14e921297..781aab9b7d8 100644--- a/apps/studio/lib/role-impersonation.ts+++ b/apps/studio/lib/role-impersonation.ts@@ -1,5 +1,3 @@-import jwt from 'jwt-simple'-import { User } from 'data/auth/users-query'import { uuidv4 } from './helpers'@@ -114,12 +112,58 @@ export function wrapWithRoleImpersonation(`}-export function getRoleImpersonationJWT(+export async function getRoleImpersonationJWT(projectRef: string,jwtSecret: string,role: PostgrestImpersonationRole-) {+): Promise<string> {const claims = getPostgrestClaims(projectRef, role)+ return createToken(claims, jwtSecret)+}++async function createToken(payload: object, key: string) {+ const header = { typ: 'JWT', alg: 'HS256' }++ const segments = []+ segments.push(btoa(JSON.stringify(header)).replace(/=/g, ''))+ segments.push(btoa(JSON.stringify(payload)).replace(/=/g, ''))++ const footer = await sign(segments.join('.'), btoa(key).replace(/=/g, ''))+ segments.push(footer.replace(/=/g, ''))+ return segments.join('.')+}- return jwt.encode(claims, jwtSecret, 'HS256')+async function sign(data: string, key: string) {+ return window.crypto.subtle+ .importKey(+ 'jwk',+ {+ //this is an example jwk key, "raw" would be an ArrayBuffer+ kty: 'oct',+ k: key,+ alg: 'HS256',+ },+ {+ name: 'HMAC',+ hash: { name: 'SHA-256' },+ },+ false,+ ['sign', 'verify']+ )+ .then((key) => {+ const jsonString = JSON.stringify(data)+ const encodedData = new TextEncoder().encode(jsonString)+ return window.crypto.subtle.sign(+ {+ name: 'HMAC',+ },+ key,+ encodedData+ )+ })+ .then((token) => {+ const u8 = new Uint8Array(token)+ const b64encoded = btoa(String.fromCharCode(...u8))+ return b64encoded+ })}diff --git a/apps/studio/next.config.js b/apps/studio/next.config.jsindex 40fbf3c42cb..d7e8324a6e2 100644--- a/apps/studio/next.config.js+++ b/apps/studio/next.config.js@@ -84,8 +84,7 @@ const nextConfig = {experimental: {// [Kevin] Next polyfills Node modules like Crypto by default, blowing up the bundle size. We use generate-password-browser (safe to use in browser) and the polyfills are not needed for us// Revisit on Next 14 upgrade (PR #19909)- // [Ivan] Temporarily enable until we find a fix for breaking anon-role in the Realtime inspector- // fallbackNodePolyfills: false,+ fallbackNodePolyfills: false,},async redirects() {return [diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex c7b8619dcd9..63b09ae3bba 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -56,7 +56,6 @@"ip-num": "^1.5.1","json-logic-js": "^2.0.2","jsonrepair": "^3.2.3",- "jwt-simple": "^0.5.6","lodash": "^4.17.21","lucide-react": "^0.167.0","markdown-table": "=2.0.0",diff --git a/apps/studio/pages/project/[ref]/api/graphiql.tsx b/apps/studio/pages/project/[ref]/api/graphiql.tsxindex bb04af8ba7a..52f62ccfcd9 100644--- a/apps/studio/pages/project/[ref]/api/graphiql.tsx+++ b/apps/studio/pages/project/[ref]/api/graphiql.tsx@@ -4,6 +4,7 @@ import { useParams } from 'common'import { observer } from 'mobx-react-lite'import { useTheme } from 'next-themes'import { useMemo } from 'react'+import toast from 'react-hot-toast'import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard'import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'@@ -49,7 +50,7 @@ const GraphiQLPage: NextPageWithLayout = () => {url: `${API_URL}/projects/${projectRef}/api/graphql`,fetch,})- const customFetcher: Fetcher = (graphqlParams, opts) => {+ const customFetcher: Fetcher = async (graphqlParams, opts) => {let userAuthorization: string | undefinedconst role = getImpersonatedRole()@@ -59,7 +60,12 @@ const GraphiQLPage: NextPageWithLayout = () => {role !== undefined &&role.type === 'postgrest') {- userAuthorization = `Bearer ${getRoleImpersonationJWT(projectRef, jwtSecret, role)}`+ try {+ const token = await getRoleImpersonationJWT(projectRef, jwtSecret, role)+ userAuthorization = 'Bearer ' + token+ } catch (err: any) {+ toast.error(`Failed to get JWT for role: ${err.message}`)+ }}return fetcherFn(graphqlParams, {diff --git a/package-lock.json b/package-lock.jsonindex e8d053c9c49..85a83f03705 100644--- a/package-lock.json+++ b/package-lock.json@@ -803,7 +803,6 @@"ip-num": "^1.5.1","json-logic-js": "^2.0.2","jsonrepair": "^3.2.3",- "jwt-simple": "^0.5.6","lodash": "^4.17.21","lucide-react": "^0.167.0","markdown-table": "=2.0.0",@@ -23732,14 +23731,6 @@"safe-buffer": "^5.0.1"}},- "node_modules/jwt-simple": {- "version": "0.5.6",- "resolved": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.5.6.tgz",- "integrity": "sha512-40aUybvhH9t2h71ncA1/1SbtTNCVZHgsTsTgqPUxGWDmUDrXyDf2wMNQKEbdBjbf4AI+fQhbECNTV6lWxQKUzg==",- "engines": {- "node": ">= 0.4.0"- }- },"node_modules/kasi": {"version": "1.1.0","resolved": "https://registry.npmjs.org/kasi/-/kasi-1.1.0.tgz",