Skip to content
Draft
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
63 changes: 63 additions & 0 deletions .github/scripts/inject-basic-auth.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/usr/bin/env node
// Injects a basic-auth edge middleware into a Vercel Build Output API v3
// bundle (.vercel/output) after the build, so the demo deployment is gated
// without touching any app code. The gate only engages when the Vercel
// project defines BASIC_AUTH_CREDENTIALS ("user:pass"); without it the
// middleware passes every request through.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'

const outputDir = process.argv[2]
if (!outputDir) {
console.error('Usage: inject-basic-auth.mjs <path to .vercel/output>')
process.exit(1)
}

const configPath = resolve(outputDir, 'config.json')
const config = JSON.parse(readFileSync(configPath, 'utf8'))

// The middleware route must come first so it runs before the static
// filesystem handler and the serverless function routes.
if (!config.routes?.some((route) => route.middlewarePath === '_middleware')) {
config.routes = [
{ src: '/(.*)', middlewarePath: '_middleware', continue: true },
...(config.routes ?? []),
]
}
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`)

const middlewareSource = `export default function middleware(request) {
const credentials = process.env.BASIC_AUTH_CREDENTIALS
if (!credentials) {
return new Response(null, { headers: { 'x-middleware-next': '1' } })
}
const header = request.headers.get('authorization') ?? ''
const [scheme, token, ...rest] = header.split(' ')
const authorized =
Boolean(scheme && token) &&
rest.length === 0 &&
scheme.toLowerCase() === 'basic' &&
token === btoa(credentials)
if (authorized) {
return new Response(null, { headers: { 'x-middleware-next': '1' } })
}
return new Response('Authentication required', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="uniswap-zkpassport-demo"' },
})
}
`

const funcDir = resolve(outputDir, 'functions/_middleware.func')
mkdirSync(funcDir, { recursive: true })
writeFileSync(
resolve(funcDir, '.vc-config.json'),
`${JSON.stringify(
{ runtime: 'edge', entrypoint: 'index.js', envVarsInUse: ['BASIC_AUTH_CREDENTIALS'] },
null,
2,
)}\n`,
)
writeFileSync(resolve(funcDir, 'index.js'), middlewareSource)

console.log(`[inject-basic-auth] Edge middleware injected into ${outputDir}`)
91 changes: 91 additions & 0 deletions .github/workflows/deploy-demo.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Builds the web app and ships it to Vercel as a prebuilt deployment.
# Lives only on the ZKPassport demo branch; requires repo secrets
# VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID and repo variables
# ZKPASSPORT_POPUP_URL, ZKPASSPORT_CREATE_POLICY_URL. Optional repo
# variables ZKPASSPORT_ATTEST_REGISTRY_SEPOLIA and
# ZKPASSPORT_ATTEST_DEPLOY_BLOCK_SEPOLIA override the registry baked
# into apps/web ZkPassport/config.ts without a commit (set both, then
# re-run this workflow).
name: Deploy demo to Vercel

on:
push:
branches: [martin/zkpassport-demo]
workflow_dispatch:

concurrency:
group: deploy-demo
cancel-in-progress: true

jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 45
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc

- uses: oven-sh/setup-bun@v2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. Github, foundry, and uniswap made github actions are exempt.

To resolve this comment:

✨ Commit fix suggestion

Suggested change
- uses: oven-sh/setup-bun@v2
- uses: oven-sh/setup-bun@<VERIFIED_VALUE_REQUIRED> # v2
with:
bun-version: 1.3.14
View step-by-step instructions
  1. Identify the trusted commit SHA for the v2 release of oven-sh/setup-bun from its official repository or release tag.
  2. Replace the mutable tag with the full 40-character commit SHA and keep the release as a comment for readability:
    - uses: oven-sh/setup-bun@<40-character-commit-sha> # v2
  3. Keep bun-version: 1.3.14 unchanged so the workflow continues to install the intended Bun version.
💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by third-party-action-not-pinned-to-commit-sha-foundry-allowed.

You can view more details about this finding in the Semgrep AppSec Platform.

with:
bun-version: 1.3.14

- name: Check required configuration
env:
POPUP_URL: ${{ vars.ZKPASSPORT_POPUP_URL }}
CREATE_POLICY_URL: ${{ vars.ZKPASSPORT_CREATE_POLICY_URL }}
run: |
test -n "$POPUP_URL" || { echo "Repo variable ZKPASSPORT_POPUP_URL is not set"; exit 1; }
test -n "$CREATE_POLICY_URL" || { echo "Repo variable ZKPASSPORT_CREATE_POLICY_URL is not set"; exit 1; }

- name: Install dependencies
run: bun install --frozen-lockfile

# Values here are not secrets: a placeholder WalletConnect id (extension
# wallets work without a real one), blanked Privy ids so the provider is
# skipped, and the public demo URLs.
- name: Write env overrides
working-directory: apps/web
env:
POPUP_URL: ${{ vars.ZKPASSPORT_POPUP_URL }}
CREATE_POLICY_URL: ${{ vars.ZKPASSPORT_CREATE_POLICY_URL }}
ATTEST_REGISTRY: ${{ vars.ZKPASSPORT_ATTEST_REGISTRY_SEPOLIA }}
ATTEST_DEPLOY_BLOCK: ${{ vars.ZKPASSPORT_ATTEST_DEPLOY_BLOCK_SEPOLIA }}
run: |
cat > .env.override <<EOF
WALLETCONNECT_PROJECT_ID="walletconnect_project_id"
PRIVY_APP_ID=""
PRIVY_CLIENT_ID=""
ENABLE_ENTRY_GATEWAY_PROXY="true"
ZKPASSPORT_ONCHAIN_BIDS="true"
ZKPASSPORT_ONCHAIN_LAUNCH="true"
ZKPASSPORT_POPUP_URL="$POPUP_URL"
ZKPASSPORT_CREATE_POLICY_URL="$CREATE_POLICY_URL"
EOF
# An empty define would win over the ?? fallback in config.ts, so
# only write the registry override when the variable is set.
if [ -n "$ATTEST_REGISTRY" ]; then
echo "ZKPASSPORT_ATTEST_REGISTRY_SEPOLIA=\"$ATTEST_REGISTRY\"" >> .env.override
fi
if [ -n "$ATTEST_DEPLOY_BLOCK" ]; then
echo "ZKPASSPORT_ATTEST_DEPLOY_BLOCK_SEPOLIA=\"$ATTEST_DEPLOY_BLOCK\"" >> .env.override
fi

- name: Build
env:
SKIP_CONFIG_PULL: "true"
run: bunx nx run @universe/web:build:vercel

- name: Inject basic-auth middleware
run: node .github/scripts/inject-basic-auth.mjs apps/web/.vercel/output

- name: Deploy
working-directory: apps/web
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
run: bunx vercel deploy --prebuilt --prod --token="$VERCEL_TOKEN"
3 changes: 3 additions & 0 deletions apps/cli/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files": []
}
3 changes: 3 additions & 0 deletions apps/dev-portal/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files": []
}
3 changes: 3 additions & 0 deletions apps/mission-control/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files": []
}
48 changes: 42 additions & 6 deletions apps/web/src/features/Toucan/Auction/BidForm/BidForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { AuctionProgressState } from '~/features/Toucan/Auction/store/types'
import { useAuctionStore, useAuctionStoreActions } from '~/features/Toucan/Auction/store/useAuctionStore'
import { getRequiredTestnetMode } from '~/features/Toucan/Shared/getRequiredTestnetMode'
import { InlineAlertBanner } from '~/features/Toucan/Shared/InlineAlertBanner'
import { useZkPassportGate } from '~/features/Toucan/ZkPassport/useZkPassportGate'

const VerticalLineContainer = styled(Flex, {
width: '100%',
Expand Down Expand Up @@ -82,6 +83,7 @@ export function BidForm({ onInputChange, onBidSubmitted }: BidFormProps): JSX.El

const [isReviewModalOpen, setIsReviewModalOpen] = useState(false)
const [isKycInterstitialModalOpen, setIsKycInterstitialModalOpen] = useState(false)
const [isZkInterstitialModalOpen, setIsZkInterstitialModalOpen] = useState(false)
const [isKycFailedModalOpen, setIsKycFailedModalOpen] = useState(false)
const [showTokenWarningModal, setShowTokenWarningModal] = useState(false)

Expand Down Expand Up @@ -139,16 +141,25 @@ export function BidForm({ onInputChange, onBidSubmitted }: BidFormProps): JSX.El
currentBlockNumber,
})

const zkGate = useZkPassportGate({
chainId,
validationHook,
walletAddress: accountAddress,
})
const zkNeedsVerify = zkGate.isGated && isWalletConnected && !zkGate.isEligible

const { showDisabledState, shouldShowWarningBanner, shouldDisableBidForm } = useBidFormWarningState({
chainId,
currency,
auctionProgressState,
userBids,
validationHook,
// A ZKPassport hook is resolved entirely on-chain, so it is neither an
// unsupported validation hook nor a verify-wallet backend concern.
validationHook: zkGate.isGated ? undefined : validationHook,
// Only treat KYC as an unsupported-auction signal once a wallet is connected;
// otherwise the disabled verify-wallet query is misread as an error and surfaces
// the warning banner instead of the connect-wallet CTA on the action button.
validationError: isWalletConnected && kycStatus.isError,
validationError: !zkGate.isGated && isWalletConnected && kycStatus.isError,
})

const handleButtonPress = (): void => {
Expand All @@ -160,7 +171,14 @@ export function BidForm({ onInputChange, onBidSubmitted }: BidFormProps): JSX.El
dispatch(setIsTestnetModeEnabled(requiredTestnetMode))
return
}
if (kycStatus.canBid) {
if (zkNeedsVerify) {
setIsZkInterstitialModalOpen(true)
return
}
// A ZKPassport-gated auction is validated by its on-chain hook, so the
// backend verify-wallet outcome (unreachable from third-party origins)
// must not block a bidder who already passed the zk gate.
if (zkGate.isGated || kycStatus.canBid) {
handleReviewBidClick()
} else if (kycStatus.onKycAction) {
kycStatus.onKycAction()
Expand All @@ -177,17 +195,24 @@ export function BidForm({ onInputChange, onBidSubmitted }: BidFormProps): JSX.El
if (needsTestnetModeSwitch) {
return requiredTestnetMode ? t('toucan.action.enableTestnetMode') : t('toucan.action.disableTestnetMode')
}
if (zkNeedsVerify) {
return t('toucan.zkpassport.verify')
}
return (kycStatus.kycButtonLabel ?? showDisabledState)
? t('toucan.auction.bidForm.auctionConcluded')
: t('toucan.bidForm.reviewBid')
})()

// The testnet-mode-switch CTA stays tappable regardless of the bid inputs, since switching mode is
// always a valid action and is a prerequisite to bidding at all.
// always a valid action and is a prerequisite to bidding at all. The same goes for the ZKPassport
// verify CTA: it opens the verification popup, so the bid inputs don't constrain it.
const buttonDisabled =
isGeoRestricted ||
(isWalletConnected && !needsTestnetModeSwitch
? submitState.isDisabled || !isAuctionInProgress || shouldDisableBidForm || kycStatus.kycButtonDisabled
(isWalletConnected && !needsTestnetModeSwitch && !zkNeedsVerify
? submitState.isDisabled ||
!isAuctionInProgress ||
shouldDisableBidForm ||
(!zkGate.isGated && kycStatus.kycButtonDisabled)
: false)

const shouldShowSwapBanner =
Expand Down Expand Up @@ -343,6 +368,17 @@ export function BidForm({ onInputChange, onBidSubmitted }: BidFormProps): JSX.El
onClose={() => setIsKycInterstitialModalOpen(false)}
onContinue={kycStatus.onKycAction}
/>
<KycInterstitialModal
isOpen={isZkInterstitialModalOpen}
onClose={() => setIsZkInterstitialModalOpen(false)}
onContinue={() => {
setIsZkInterstitialModalOpen(false)
zkGate.openVerify()
}}
providerName="ZKPassport"
providerTermsUrl="https://zkpassport.id/terms"
providerPrivacyUrl="https://zkpassport.id/privacy"
/>
<KycFailedModal isOpen={isKycFailedModalOpen} onClose={() => setIsKycFailedModalOpen(false)} />
{shouldShowTokenWarning && token && (
<TokenWarningModal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useCallback, useRef, useState } from 'react'
import { useSubmitBidMutation } from 'uniswap/src/data/apiClients/dataApiService/auctions/useSubmitBidMutation'
import { logger } from 'utilities/src/logger/logger'
import type { PreparedBidTransaction } from '~/features/Toucan/Auction/hooks/useBidFormSubmit'
import { ZKPASSPORT_ONCHAIN_BIDS } from '~/features/Toucan/ZkPassport/onchainBid'

export enum BidSimulationErrorType {
BELOW_CLEARING_PRICE = 'BELOW_CLEARING_PRICE',
Expand Down Expand Up @@ -118,15 +119,21 @@ export function useBidSimulation({
setSimulationError(undefined)

try {
await submitBidMutation.mutateAsync({
maxPrice: preparedBid.info.maxPriceQ96,
amount: preparedBid.info.amountRaw,
walletAddress: accountAddress,
auctionContractAddress: auctionContractAddress.toLowerCase(),
chainId: chainId as ChainId,
// TODO | Toucan -- determine why this is returning error with true set
simulateTransaction: false,
})
// On-chain bids skip the backend dry-run: the calldata is encoded
// locally, the CCA contract enforces price validity, and the wallet's
// gas estimation surfaces reverts before signing — while the liquidity
// backend is CORS-blocked for third-party origins.
if (!ZKPASSPORT_ONCHAIN_BIDS) {
await submitBidMutation.mutateAsync({
maxPrice: preparedBid.info.maxPriceQ96,
amount: preparedBid.info.amountRaw,
walletAddress: accountAddress,
auctionContractAddress: auctionContractAddress.toLowerCase(),
chainId: chainId as ChainId,
// TODO | Toucan -- determine why this is returning error with true set
simulateTransaction: false,
})
}

// oxlint-disable-next-line typescript/no-unnecessary-condition -- ref may be set during await
if (isAbortedRef.current) {
Expand Down
Loading