') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat: support generating JWT auth token by sweatybridge · Pull Request #4159 · supabase/cli · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions cmd/gen.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,8 +7,10 @@ import (

env "github.com/Netflix/go-env"
"github.com/go-errors/errors"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/supabase/cli/internal/gen/bearerjwt"
"github.com/supabase/cli/internal/gen/keys"
"github.com/supabase/cli/internal/gen/signingkeys"
"github.com/supabase/cli/internal/gen/types"
Expand DownExpand Up@@ -118,6 +120,23 @@ Supported algorithms:
return signingkeys.Run(cmd.Context(), algorithm.Value, appendKeys, afero.NewOsFs())
},
}

claims config.CustomClaims
expiry time.Time
validFor time.Duration

genJWTCmd = &cobra.Command{
Use: "bearer-jwt",
Short: "Generate a Bearer Auth JWT for accessing Data API",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if expiry.IsZero() {
expiry = time.Now().Add(validFor)
}
claims.ExpiresAt = jwt.NewNumericDate(expiry)
return bearerjwt.Run(cmd.Context(), claims, os.Stdout, afero.NewOsFs())
},
}
)

func init() {
Expand DownExpand Up@@ -145,5 +164,14 @@ func init() {
signingKeyFlags.Var(&algorithm, "algorithm", "Algorithm for signing key generation.")
signingKeyFlags.BoolVar(&appendKeys, "append", false, "Append new key to existing keys file instead of overwriting.")
genCmd.AddCommand(genSigningKeyCmd)
tokenFlags := genJWTCmd.Flags()
tokenFlags.StringVar(&claims.Role, "role", "", "Postgres role to use.")
tokenFlags.StringVar(&claims.Subject, "sub", "", "User ID to impersonate.")
genJWTCmd.Flag("sub").DefValue = "anonymous"
tokenFlags.TimeVar(&expiry, "exp", time.Time{}, []string{time.RFC3339}, "Expiry timestamp for this token.")
tokenFlags.DurationVar(&validFor, "valid-for", time.Minute*30, "Validity duration for this token.")
genJWTCmd.MarkFlagsMutuallyExclusive("exp", "valid-for")
cobra.CheckErr(genJWTCmd.MarkFlagRequired("role"))
genCmd.AddCommand(genJWTCmd)
rootCmd.AddCommand(genCmd)
}
42 changes: 42 additions & 0 deletions internal/gen/bearerjwt/bearerjwt.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
package bearerjwt

import (
"context"
"fmt"
"io"
"os"
"strings"

"github.com/go-errors/errors"
"github.com/spf13/afero"
"github.com/supabase/cli/internal/utils"
"github.com/supabase/cli/internal/utils/flags"
"github.com/supabase/cli/pkg/config"
)

func Run(ctx context.Context, claims config.CustomClaims, w io.Writer, fsys afero.Fs) error {
if err := flags.LoadConfig(fsys); err != nil {
return err
}
// Set is_anonymous = true for authenticated role without explicit user ID
if strings.EqualFold(claims.Role, "authenticated") && len(claims.Subject) == 0 {
claims.IsAnon = true
}
// Use the first signing key that passes validation
for _, k := range utils.Config.Auth.SigningKeys {
fmt.Fprintln(os.Stderr, "Using signing key ID:", k.KeyID.String())
if token, err := config.GenerateAsymmetricJWT(k, claims); err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
fmt.Fprintln(w, token)
return nil
}
}
fmt.Fprintln(os.Stderr, "Using legacy JWT secret...")
token, err := claims.NewToken().SignedString([]byte(utils.Config.Auth.JwtSecret.Value))
if err != nil {
return errors.Errorf("failed to generate auth token: %w", err)
}
fmt.Fprintln(w, token)
return nil
}
98 changes: 98 additions & 0 deletions internal/gen/bearerjwt/bearerjwt_test.go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
package bearerjwt

import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
_ "embed"
"encoding/json"
"testing"

"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/supabase/cli/internal/gen/signingkeys"
"github.com/supabase/cli/internal/utils"
"github.com/supabase/cli/pkg/config"
)

func TestGenerateToken(t *testing.T) {
t.Run("mints custom JWT", func(t *testing.T) {
claims := config.CustomClaims{
Role: "authenticated",
}
// Setup private key
privateKey, err := signingkeys.GeneratePrivateKey(config.AlgES256)
require.NoError(t, err)
// Setup public key for validation
publicKey := ecdsa.PublicKey{Curve: elliptic.P256()}
publicKey.X, err = config.NewBigIntFromBase64(privateKey.X)
require.NoError(t, err)
publicKey.Y, err = config.NewBigIntFromBase64(privateKey.Y)
require.NoError(t, err)
// Setup in-memory fs
fsys := afero.NewMemMapFs()
require.NoError(t, utils.WriteFile("supabase/config.toml", []byte(`
[auth]
signing_keys_path = "./keys.json"
`), fsys))
testKey, err := json.Marshal([]config.JWK{*privateKey})
require.NoError(t, err)
require.NoError(t, utils.WriteFile("supabase/keys.json", testKey, fsys))
// Run test
var buf bytes.Buffer
err = Run(context.Background(), claims, &buf, fsys)
// Check error
assert.NoError(t, err)
token, err := jwt.NewParser().Parse(buf.String(), func(t *jwt.Token) (any, error) {
return &publicKey, nil
})
assert.NoError(t, err)
assert.True(t, token.Valid)
assert.Equal(t, map[string]any{
"alg": "ES256",
"kid": privateKey.KeyID.String(),
"typ": "JWT",
}, token.Header)
assert.Equal(t, jwt.MapClaims{
"is_anonymous": true,
"role": "authenticated",
}, token.Claims)
})

t.Run("mints legacy JWT", func(t *testing.T) {
utils.Config.Auth.SigningKeysPath = ""
utils.Config.Auth.SigningKeys = nil
claims := config.CustomClaims{
RegisteredClaims: jwt.RegisteredClaims{
Subject: uuid.New().String(),
},
Role: "authenticated",
}
// Setup in-memory fs
fsys := afero.NewMemMapFs()
// Run test
var buf bytes.Buffer
err := Run(context.Background(), claims, &buf, fsys)
// Check error
assert.NoError(t, err)
token, err := jwt.NewParser().Parse(buf.String(), func(t *jwt.Token) (any, error) {
return []byte(utils.Config.Auth.JwtSecret.Value), nil
})
assert.NoError(t, err)
assert.True(t, token.Valid)
assert.Equal(t, map[string]any{
"alg": "HS256",
"typ": "JWT",
}, token.Header)
assert.Equal(t, jwt.MapClaims{
"exp": float64(1983812996),
"iss": "supabase-demo",
"role": "authenticated",
"sub": claims.Subject,
}, token.Claims)
})
}
14 changes: 11 additions & 3 deletions pkg/config/apikeys.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,7 +39,7 @@ func (a auth) generateJWT(role string) (string, error) {
claims := CustomClaims{Issuer: "supabase-demo", Role: role}
if len(a.SigningKeys) > 0 {
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 365 * 10)) // 10 years
return generateAsymmetricJWT(a.SigningKeys[0], claims)
return GenerateAsymmetricJWT(a.SigningKeys[0], claims)
}
// Fallback to generating symmetric keys
if len(a.JwtSecret.Value) < 16 {
Expand All@@ -52,8 +52,8 @@ func (a auth) generateJWT(role string) (string, error) {
return signed, nil
}

// generateAsymmetricJWT generates a JWT token signed with the provided JWK private key
func generateAsymmetricJWT(jwk JWK, claims CustomClaims) (string, error) {
// GenerateAsymmetricJWT generates a JWT token signed with the provided JWK private key
func GenerateAsymmetricJWT(jwk JWK, claims CustomClaims) (string, error) {
privateKey, err := jwkToPrivateKey(jwk)
if err != nil {
return "", errors.Errorf("failed to convert JWK to private key: %w", err)
Expand DownExpand Up@@ -167,3 +167,11 @@ func jwkToECDSAPrivateKey(jwk JWK) (*ecdsa.PrivateKey, error) {
D: d,
}, nil
}

func NewBigIntFromBase64(n string) (*big.Int, error) {
nBytes, err := base64.RawURLEncoding.DecodeString(n)
if err != nil {
return nil, errors.Errorf("failed to decode base64: %w", err)
}
return new(big.Int).SetBytes(nBytes), nil
}
2 changes: 1 addition & 1 deletion pkg/config/auth.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -363,7 +363,7 @@ type (
}

web3 struct {
Solana solana `toml:"solana"`
Solana solana `toml:"solana"`
Ethereum ethereum `toml:"ethereum"`
}
)
Expand Down
2 changes: 1 addition & 1 deletion pkg/config/config.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -130,6 +130,7 @@ type CustomClaims struct {
Issuer string `json:"iss,omitempty"`
Ref string `json:"ref,omitempty"`
Role string `json:"role"`
IsAnon bool `json:"is_anonymous,omitempty"`
jwt.RegisteredClaims
}

Expand DownExpand Up@@ -876,7 +877,6 @@ func (c *config) Validate(fsys fs.FS) error {
return errors.New("Missing required field in config: edge_runtime.deno_version")
case 1:
c.EdgeRuntime.Image = deno1
break
case 2:
break
default:
Expand Down