Skip to content
Open
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,6 @@ no-hooks
dev-dist

credentials
credentials.*
credentials*

*.har
8 changes: 4 additions & 4 deletions apps/dialog/src/routes/dialog/wallet_connect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ function RouteComponent() {
)
const capabilities = params[0]?.capabilities
const grantAdmins = capabilities?.grantAdmins
const signInWithEthereumCapability = capabilities?.signInWithEthereum

// If any admins need to be authorized, we need to check the
// authority & validity of the request.
Expand Down Expand Up @@ -115,12 +116,11 @@ function RouteComponent() {
selectAccount,
...(capabilities?.signInWithEthereum && {
signInWithEthereum: {
...capabilities?.signInWithEthereum,
...signInWithEthereumCapability,
domain:
capabilities?.signInWithEthereum.domain ??
signInWithEthereumCapability?.domain ??
referrerURL?.hostname,
uri:
capabilities?.signInWithEthereum.uri ?? referrerURL?.href,
uri: signInWithEthereumCapability?.uri ?? referrerURL?.href,
},
}),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ function RouteComponent() {
},
})

useAuthSessionRedirect(respond)

const status = React.useMemo(() => {
if (capabilities?.grantPermissions && grantPermissionsQuery.isFetching)
return 'loading'
Expand All @@ -82,6 +80,8 @@ function RouteComponent() {
respond.isPending,
])

useAuthSessionRedirect(respond)

if (capabilities?.email ?? true)
return (
<Email
Expand Down
6 changes: 5 additions & 1 deletion apps/id/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
"~/*": ["./src/*"],
"porto/*": ["../../src/*"]
},
"types": ["unplugin-icons/types/react", "typed-query-selector/strict"]
"types": [
"vite-plugin-terminal/client",
"unplugin-icons/types/react",
"typed-query-selector/strict"
]
}
}
1 change: 1 addition & 0 deletions examples/authentication-rainbowkit/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default defineConfig((config) => {
cors: {
origin: config.mode === 'development' ? '*' : 'https://id.porto.sh',
},
port: 24312,
},
}
})
6 changes: 4 additions & 2 deletions examples/authentication-rainbowkit/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ const headers = new Headers({
'Access-Control-Allow-Headers':
'Content-Type, Authorization, X-Requested-With',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'https://id.porto.sh',
'Access-Control-Allow-Origin': '*',
'Access-Control-Max-Age': '86400',
})

app.on(['GET', 'POST', 'OPTIONS'], '/siwe/nonce', async (c) => {
app.options('*', (c) => c.json({ success: true }, { headers }))

app.on(['POST', 'OPTIONS'], '/siwe/nonce', async (c) => {
// Generate a nonce to be used in the SIWE message.
// This is used to prevent replay attacks.
const nonce = generateSiweNonce()
Expand Down
9 changes: 8 additions & 1 deletion examples/authentication/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
JWT_SECRET=foobarbaz
JWT_SECRET=foobarbaz

# optional, see https://github.com/o-az/unplugin-cloudflare-tunnel
VITE_ENABLE_TUNNEL=
CLOUDFLARE_API_KEY=""
CLOUDFLARE_ACCOUNT_ID=""
CLOUDFLARE_TUNNEL_HOSTNAME=""
CLOUDFLARE_TUNNEL_SSL=""
3 changes: 2 additions & 1 deletion examples/authentication/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"build": "vite build",
"build:types": "wrangler types --include-runtime=false",
"deploy": "pnpm run build && wrangler deploy",
"dev": "vite",
"dev": "vite dev",
"prepreview": "pnpm build:types",
"preview": "pnpm run build && vite preview"
},
Expand All @@ -29,6 +29,7 @@
"@vitejs/plugin-react": "^5.0.4",
"globals": "^16.4.0",
"typescript": "~5.9.3",
"unplugin-cloudflare-tunnel": "0.0.0-alpha-1",
"vite": "^6.3.6",
"vite-plugin-mkcert": "^1.17.9",
"vite-plugin-pwa": "^1.1.0",
Expand Down
6 changes: 3 additions & 3 deletions examples/authentication/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ export function App() {
style={{
bottom: 10,
fontFamily: 'monospace',
fontSize: 24,
left: 10,
fontSize: 18,
position: 'absolute',
right: 10,
}}
>
<PWABadge />
Expand Down Expand Up @@ -98,7 +98,7 @@ function Me() {
>
Fetch /me (authenticated endpoint)
</button>
<div>{me}</div>
<pre>{me}</pre>
</div>
)
}
55 changes: 44 additions & 11 deletions examples/authentication/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { cloudflare } from '@cloudflare/vite-plugin'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import mkcert from 'vite-plugin-mkcert'
import CloudflareTunnel from 'unplugin-cloudflare-tunnel/vite'
import { defineConfig, loadEnv, type PluginOption } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'

import packageJson from './package.json' with { type: 'json' }

export default defineConfig((config) => ({
plugins: [
export default defineConfig((config) => {
const env = loadEnv(config.mode, process.cwd(), '')

const plugins: Array<PluginOption> = [
react(),
mkcert(),
cloudflare(),
VitePWA({
devOptions: {
Expand Down Expand Up @@ -37,10 +38,42 @@ export default defineConfig((config) => ({
globPatterns: ['**/*.{js,css,html,svg,png,ico}'],
},
}),
],
server: {
cors: {
origin: config.mode === 'development' ? '*' : 'https://id.porto.sh',
]

const enableTunnel =
env.VITE_ENABLE_TUNNEL === 'true' && config.mode === 'development'

if (enableTunnel)
plugins.push(
CloudflareTunnel({
accountId: env.CLOUDFLARE_ACCOUNT_ID,
apiToken: env.CLOUDFLARE_API_TOKEN,
enabled: true,
hostname: env.CLOUDFLARE_TUNNEL_HOSTNAME,
logFile: `logs/${packageJson.name}.log`,
ssl: env.CLOUDFLARE_TUNNEL_SSL,
tunnelName: packageJson.name,
}),
)

return {
plugins,
server: {
cors:
config.mode === 'development'
? {
allowedHeaders: [
'Content-Type',
'Authorization',
'X-Requested-With',
],
credentials: true,
methods: ['GET', 'POST', 'OPTIONS'],
origin: (origin, callback) =>
callback(null as never, origin ?? true),
preflightContinue: true,
}
: { origin: 'https://id.porto.sh' },
},
},
}))
}
})
14 changes: 11 additions & 3 deletions examples/authentication/worker-configuration.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/* eslint-disable */
// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 48a0b5401b67a79eebaa402adec9538b)
// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 1d34b249aada6580464f0661df2a5822)
declare namespace Cloudflare {
interface GlobalProps {
mainModule: typeof import('./worker/index')
}
interface Env {
NONCE_STORE: KVNamespace
JWT_SECRET: string
VITE_SIWE_URL: string
VITE_ENABLE_TUNNEL: string
CLOUDFLARE_TUNNEL_HOSTNAME: string
CLOUDFLARE_TUNNEL_SSL: string
}
}
interface Env extends Cloudflare.Env {}
Expand All @@ -19,6 +21,12 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
declare namespace NodeJS {
interface ProcessEnv
extends StringifyValues<
Pick<Cloudflare.Env, 'JWT_SECRET' | 'VITE_SIWE_URL'>
Pick<
Cloudflare.Env,
| 'JWT_SECRET'
| 'VITE_ENABLE_TUNNEL'
| 'CLOUDFLARE_TUNNEL_HOSTNAME'
| 'CLOUDFLARE_TUNNEL_SSL'
>
> {}
}
92 changes: 75 additions & 17 deletions examples/authentication/worker/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { env } from 'cloudflare:workers'
import { Hono } from 'hono'
import { deleteCookie, setCookie } from 'hono/cookie'
import { deleteCookie, getCookie, setCookie } from 'hono/cookie'
import * as jwt from 'hono/jwt'
import { Porto } from 'porto'
import { RelayClient } from 'porto/viem'
Expand All @@ -12,16 +12,30 @@ import {

const app = new Hono<{ Bindings: Cloudflare.Env }>().basePath('/api')

const headers = new Headers({
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers':
'Content-Type, Authorization, X-Requested-With',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'https://id.porto.sh',
'Access-Control-Max-Age': '86400',
})
function createCorsHeaders(request: Request) {
const origin = request.headers.get('Origin') ?? 'https://id.porto.sh'
const headers = new Headers({
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers':
'Content-Type, Authorization, X-Requested-With',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Private-Network': 'true',
'Access-Control-Max-Age': '86400',
Vary: 'Origin',
})
return headers
}

app.options('*', (c) =>
c.json({ success: true }, { headers: createCorsHeaders(c.req.raw) }),
)

app.on(['GET', 'POST', 'OPTIONS'], '/siwe/nonce', async (c) => {
app.options('/siwe/nonce', (c) =>
c.json({ success: true }, { headers: createCorsHeaders(c.req.raw) }),
)
app.on(['GET', 'POST'], '/siwe/nonce', async (c) => {
const headers = createCorsHeaders(c.req.raw)
// Generate a nonce to be used in the SIWE message.
// This is used to prevent replay attacks.
const nonce = generateSiweNonce()
Expand All @@ -32,7 +46,20 @@ app.on(['GET', 'POST', 'OPTIONS'], '/siwe/nonce', async (c) => {
return c.json({ nonce }, { headers })
})

app.on(['POST', 'OPTIONS'], '/siwe/verify', async (c) => {
app.options('/siwe/verify', (c) =>
c.json({ success: true }, { headers: createCorsHeaders(c.req.raw) }),
)
app.post('/siwe/verify', async (c) => {
const headers = createCorsHeaders(c.req.raw)
const existingToken = getCookie(c, 'auth')
if (existingToken) {
try {
await jwt.verify(existingToken, c.env.JWT_SECRET)
return c.json({ success: true }, { headers })
} catch {
// ignore and continue with verification flow
}
}
// Extract properties from the request body and SIWE message.
const { message, signature } = await c.req.json()
const siweMessage = parseSiweMessage(message)
Expand All @@ -43,14 +70,36 @@ app.on(['POST', 'OPTIONS'], '/siwe/verify', async (c) => {
return c.json({ error: 'Nonce is required' }, { headers, status: 400 })

// Check if the nonce is valid for this session.
const nonce_session = await c.env.NONCE_STORE.get(nonce)
const nonce_session = await c.env.NONCE_STORE.get<string | null>(nonce)
if (!nonce_session)
return c.json(
{ error: 'Invalid or expired nonce' },
{ headers, status: 401 },
)

await c.env.NONCE_STORE.delete(nonce)
if (nonce_session.startsWith('used:')) {
const usedSignature = nonce_session.slice('used:'.length)
if (usedSignature === signature) {
const maxAge = 60 * 60 * 24 * 7 // 7 days
const exp = Math.floor(Date.now() / 1000) + maxAge
const token = await jwt.sign({ exp, sub: address }, c.env.JWT_SECRET)
await c.env.NONCE_STORE.put(nonce, `used:${signature}`, {
expirationTtl: 60,
})
setCookie(c, 'auth', token, {
httpOnly: true,
maxAge,
path: '/',
sameSite: 'none',
secure: true,
})
return c.json({ success: true }, { headers })
}
return c.json(
{ error: 'Invalid or expired nonce' },
{ headers, status: 401 },
)
}

const porto = Porto.create()

Expand All @@ -71,31 +120,40 @@ app.on(['POST', 'OPTIONS'], '/siwe/verify', async (c) => {

// Issue a JWT token for the user in a HTTP-only cookie.
const token = await jwt.sign({ exp, sub: address }, c.env.JWT_SECRET)
await c.env.NONCE_STORE.put(nonce, `used:${signature}`, {
expirationTtl: 60,
})
setCookie(c, 'auth', token, {
httpOnly: true,
maxAge,
path: '/',
sameSite: 'lax',
sameSite: 'none',
secure: true,
})

return c.json({ success: true }, { headers })
})

app.options('/siwe/logout', (c) =>
c.json({ success: true }, { headers: createCorsHeaders(c.req.raw) }),
)
app.post(
'/siwe/logout',
jwt.jwt({ cookie: 'auth', secret: env.JWT_SECRET }),
async (c) => {
const headers = createCorsHeaders(c.req.raw)
deleteCookie(c, 'auth')
return c.json({ success: true }, { headers })
},
)

app.on(
['GET', 'OPTIONS'],
app.options('/me', (c) =>
c.json({ success: true }, { headers: createCorsHeaders(c.req.raw) }),
)
app.get(
'/me',
jwt.jwt({ cookie: 'auth', secret: env.JWT_SECRET }),
async (c) => {
const headers = createCorsHeaders(c.req.raw)
return c.json(c.get('jwtPayload'), { headers })
},
)
Expand Down
Loading
Loading