id,language,category,name,description,code,imports_or_contract,notes
1,javascript,signing,verify-signature,"Verify signed message","import { verifyMessageSignature } from '@stacks/encryption'; const isValid = verifyMessageSignature({ message: 'Verify ownership', signature: signatureData.signature, publicKey: publicKey }); console.log('Valid:', isValid)","import { verifyMessageSignature } from '@stacks/encryption'","Cryptographically verify message was signed by public key"
2,javascript,session,restore-session,"Restore auth session from cache","const cachedSession = localStorage.getItem('stacks_session'); if (cachedSession) { const session = JSON.parse(cachedSession); const hourAgo = Date.now() - 3600000; if (session.timestamp > hourAgo) { console.log('Cached session:', session.address) } else { localStorage.removeItem('stacks_session') }}","None","Validate timestamp to prevent stale sessions"
3,javascript,encryption,encrypt-data,"Encrypt data with user key","import { encryptContent } from '@stacks/encryption'; const encrypted = await encryptContent(JSON.stringify(sensitiveData), { publicKey: userPublicKey })","import { encryptContent } from '@stacks/encryption'","Only user with private key can decrypt; use wallet publicKey"
4,javascript,encryption,decrypt-data,"Decrypt encrypted data","import { decryptContent } from '@stacks/encryption'; const decrypted = await decryptContent(encryptedData, { privateKey: userPrivateKey })","import { decryptContent } from '@stacks/encryption'","Requires user private key; handle securely"
5,javascript,auth-guards,protected-route,"Protect routes with auth guard","function ProtectedRoute({ children }) { const { isAuthenticated } = useWallet(); const router = useRouter(); useEffect(() => { if (!isAuthenticated) { router.push('/login') }}, [isAuthenticated, router]); return isAuthenticated ? children : <div>Loading...</div> }","import { useWallet } from './hooks'; import { useRouter } from 'next/router'","Redirect to login if not authenticated; uses useWallet hook from stacks-js-core"
6,javascript,middleware,auth-middleware,"API route auth middleware","export function withAuth(handler) { return async (req, res) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).json({ error: 'Unauthorized' }); try { const verified = verifyJWT(token); req.user = verified; return handler(req, res) } catch { return res.status(401).json({ error: 'Invalid token' }) }}}","None","Protect API routes; verify JWT tokens"
7,javascript,jwt,create-auth-token,"Create JWT auth token","import jwt from 'jsonwebtoken'; const token = jwt.sign({ address: walletAddress, exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24)}, JWT_SECRET)","import jwt from 'jsonwebtoken'","Token expires in 24 hours; include wallet address"
8,javascript,jwt,verify-auth-token,"Verify JWT auth token","import jwt from 'jsonwebtoken'; try { const decoded = jwt.verify(token, JWT_SECRET); console.log('User:', decoded.address); return decoded } catch (error) { console.error('Invalid token:', error); return null }","import jwt from 'jsonwebtoken'","Throws error if token invalid or expired"
9,javascript,session-tokens,exchange-session-token,"Exchange auth token for session","async function exchangeAuthToken(authToken) { const response = await fetch('/api/auth/session', { method: 'POST', headers: { 'Authorization': `Bearer ${authToken}` } }); const { sessionToken } = await response.json(); localStorage.setItem('session_token', sessionToken); return sessionToken }","fetch","Backend validates auth token and issues session token"
10,javascript,backend-auth,wallet-to-jwt,"Connect wallet then get JWT from backend","import { connect } from '@stacks/connect'; const userData = await connect(); const address = userData.addresses.stx[0].address; const response = await fetch('/api/auth/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address }) }); const { token } = await response.json()","import { connect } from '@stacks/connect'","Connect wallet then verify with backend API to get JWT"
11,javascript,bns,lookup-bns-profile,"Resolve BNS to get profile data","import { lookupProfile } from '@stacks/auth'; const profile = await lookupProfile('username.btc'); console.log(profile.name, profile.description); const socialLinks = profile.account?.filter(a => a.service === 'twitter' || a.service === 'github')","import { lookupProfile } from '@stacks/auth'","BNS profiles can include social media links"
12,javascript,access-control,verify-nft-ownership,"Gate content by NFT ownership","async function hasAccessNFT(userAddress, nftContract, nftId) { const response = await fetch(`https://api.hiro.so/extended/v1/tokens/nft/holdings?principal=${nftContract}&token_id=${nftId}`); const data = await response.json(); return data.results[0]?.owner === userAddress }","fetch","Token-gated access pattern"
13,javascript,access-control,verify-token-balance,"Gate content by token balance","async function hasMinBalance(userAddress, tokenContract, minAmount) { const response = await fetch(`https://api.hiro.so/extended/v1/address/${userAddress}/balances`); const balances = await response.json(); const balance = balances.fungible_tokens[tokenContract]?.balance || '0'; return parseInt(balance) >= minAmount }","fetch","Require minimum token holdings for access"
14,javascript,webhooks,verify-webhook-signature,"Verify webhook signature","import crypto from 'crypto'; function verifyWebhook(payload, signature, secret) { const hmac = crypto.createHmac('sha256', secret); hmac.update(JSON.stringify(payload)); const digest = hmac.digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest)) }","import crypto from 'crypto'","Verify webhook came from trusted source"