
Web3 businesses selling digital music, sound libraries, 3D models, and indie-game assets face a persistent technical conflict:
The frontend must offer public, smooth audio previews so potential buyers can judge sound quality and rhythm. But after a buyer pays 120 USDC on-chain for a commercial license, the system must deliver an uncompressed 24-bit/96kHz lossless WAV master of up to 500MB, or multitrack project stems.
Teams that reduce Web3 development to connecting a wallet often hard-code the master file’s URL on an IPFS gateway or public AWS S3 bucket, relying on the frontend to show the download button only after payment.
Within 24 hours, scrapers and piracy communities can capture the real master URL from the browser’s Network tab. One user buys a license, and an entire Telegram channel or Discord community downloads the highest-quality master for free, even mirroring it on third-party sites.
Digital-asset delivery requires a strict cryptographic verification gate between on-chain payment and off-chain receipt of the file.
Using the production practices in Fone MusicFlow, this article explains how Next.js, EVM contracts, and Cloudflare R2 / AWS S3 form a secure delivery pipeline with EIP-712 identity verification, live RPC license assertions, and transient signed URLs valid for 60 seconds.
1. Dual-Track Media Delivery: Previews and Licensed Downloads

To support open marketing while protecting files, the architecture must physically separate media into two delivery tracks:
+----------------------------------------------------------------------------------------------------+
| MusicFlow Dual-Track Media Delivery Architecture |
+----------------------------------------------------------------------------------------------------+
[ Public track: Preview Stream ]
- Format: 128kbps lossy MP3 / downsampled AAC
- Protection: intermittent audio watermark ("MusicFlow Preview")
- Storage: public global edge-CDN cache; no authentication; concurrent playback for anyone
================================= Physical Isolation =================================
[ Private track: Entitlement Delivery Stream ]
- Format: 24-bit 96kHz lossless WAV masters / ZIP-packaged multitrack project stems
- Storage: private Cloudflare R2 / AWS S3 bucket, with all public read access disabled
- Access: controlled Next.js API Route / Cloudflare Worker gateway only
- Authorization requirements:
1. Client EIP-712 signature proves possession of the buyer's wallet private key;
2. Gateway queries Ethereum/Base contract: hasValidLicense(buyer, trackId) == true;
3. Issue transient presigned download URL with TTL = 60s and IP/client binding.
+----------------------------------------------------------------------------------------------------+
Under this architecture, captured public traffic contains only watermarked, low-quality lossy previews. High-value clean masters require an on-chain license and cryptographic handshake for a one-time download privilege within a very short window.
2. The End-to-End Anti-Hotlinking Handshake
To prevent replay, shared links, and unauthorized scraping, every download step has strict cryptographic constraints:
+----------------------------------------------------------------------------------------------------+
| EIP-712 Verification and Short-Lived Presigned URL Flow |
+----------------------------------------------------------------------------------------------------+
Client Browser (Next.js dApp) Next.js Edge Route Handler EVM JSON-RPC (Base/L1) Cloudflare R2 Bucket
│ │ │ │
(1) Click "Download lossless master" │ │ │
Wallet prompts to sign EIP-712 DownloadRequest │ │
(includes trackId, nonce, timestamp) │ │ │
│ │ │ │
(2) POST /api/v1/tracks/download-url ──────────>│ │ │
(signature and buyer wallet address) │ │ │
│ │ │ │
│ (3) Verify recovered signing address │ │
│ Check timestamp < 60s │ │
│ │ │ │
│ ├── readContract: hasValidLicense ─>│ │
│ │<── Return true (valid license) ───│ │
│ │ │
│ (4) Generate S3/R2 presigned URL │
│ Set ExpiresIn = 60 seconds │
│ Bind Content-Disposition download header │
│ │ │
(5) Return signed temporary download URL <───────┤ │
(https://cdn.fone.cc/master/...?X-Amz-Signature=...) │
│ │
(6) Browser directly streams the binary master ─────────────────────────────────────────────────────────────>│
(URL expires after 60 seconds; R2 rejects any subsequent third-party access with HTTP 403 Forbidden)
+----------------------------------------------------------------------------------------------------+
3. Production Implementation: Next.js License Checks and an R2 Presigning Gateway
The following Fone MusicFlow API route uses Next.js App Router, viem on-chain reads, and @aws-sdk/s3-request-presigner:
// musicflow/src/app/api/assets/download-signed-url/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifyTypedData, createPublicClient, http, parseAbiItem, getAddress } from 'viem';
import { base } from 'viem/chains';
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
// Initialize Cloudflare R2 / S3 client (never expose private credentials to the frontend)
const r2Client = new S3Client({
region: 'auto',
endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
},
});
const publicClient = createPublicClient({
chain: base,
transport: http(process.env.BASE_RPC_URL),
});
const MUSICFLOW_LICENSING_ADDRESS = getAddress(process.env.MUSICFLOW_CONTRACT_ADDRESS as `0x${string}`);
const EIP712_DOWNLOAD_TYPES = {
DownloadRequest: [
{ name: 'trackId', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'timestamp', type: 'uint64' },
],
} as const;
export async function POST(req: NextRequest) {
try {
const { buyerAddress, trackId, nonce, timestamp, signature } = await req.json();
const now = Math.floor(Date.now() / 1000);
// 1. Replay check: signature timestamp must be within 60 seconds
if (Math.abs(now - Number(timestamp)) > 60) {
return NextResponse.json({ error: 'Signature expired. Please try again.' }, { status: 400 });
}
const domain = {
name: 'MusicFlowEntitlementGateway',
version: '1',
chainId: BigInt(base.id),
verifyingContract: MUSICFLOW_LICENSING_ADDRESS,
};
// 2. Cryptographic check: verify the request was signed by the buyer's wallet private key
const isValidSignature = await verifyTypedData({
address: getAddress(buyerAddress),
domain,
types: EIP712_DOWNLOAD_TYPES,
primaryType: 'DownloadRequest',
message: {
trackId: BigInt(trackId),
nonce: BigInt(nonce),
timestamp: BigInt(timestamp),
},
signature: signature as `0x${string}`,
});
if (!isValidSignature) {
return NextResponse.json({ error: 'Invalid cryptographic signature.' }, { status: 401 });
}
// 3. Strict on-chain assertion: read the contract through RPC to confirm an active commercial license
const hasLicense = await publicClient.readContract({
address: MUSICFLOW_LICENSING_ADDRESS,
abi: [
parseAbiItem('function hasValidLicense(address licensee, uint256 trackId) view returns (bool)'),
],
functionName: 'hasValidLicense',
args: [getAddress(buyerAddress), BigInt(trackId)],
});
if (!hasLicense) {
return NextResponse.json({ error: 'No active commercial license found for this wallet.' }, { status: 403 });
}
// 4. Generate a private Cloudflare R2 download URL valid for only 60 seconds
const bucketKey = `masters/track_${trackId}_lossless_24bit_96k.wav`;
const command = new GetObjectCommand({
Bucket: process.env.R2_PRIVATE_BUCKET_NAME,
Key: bucketKey,
ResponseContentDisposition: `attachment; filename="track_${trackId}_master.wav"`,
});
const signedDownloadUrl = await getSignedUrl(r2Client, command, {
expiresIn: 60, // Core protection: a very short 60-second validity window
});
return NextResponse.json({
downloadUrl: signedDownloadUrl,
expiresInSeconds: 60,
});
} catch (err: any) {
console.error('[DownloadGateway] Error:', err);
return NextResponse.json({ error: 'Internal server error while resolving media.' }, { status: 500 });
}
}
4. Fast Read-Only Contract Queries (hasValidLicense)
To keep gateway responses in milliseconds under concurrent downloads, the contract needs a storage-optimized read-only function without deep iteration:
// musicflow/contracts/src/MusicFlowLicensing.sol (excerpt)
/**
* @notice Let gateways and third-party platforms verify a buyer's active license in milliseconds
*/
function hasValidLicense(address licensee, uint256 trackId) external view returns (bool) {
bytes32 activeLicenseId = userActiveLicenses[licensee][trackId];
if (activeLicenseId == bytes32(0)) {
return false;
}
LicenseReceipt memory receipt = licenses[activeLicenseId];
TrackLicenseConfig memory track = tracks[trackId];
// If the track was bought out, verify the user's license was issued before the buyout timestamp
if (track.state == TrackState.EXCLUSIVELY_LOCKED) {
if (receipt.tier == LicenseTier.EXCLUSIVE_BUYOUT && receipt.licensee == licensee) {
return true;
}
return receipt.issuedAt <= track.buyoutTimestamp;
}
return true;
}
5. Comparing Public Links, JWT Downloads, and On-Chain Signed URLs
The following table compares media-delivery security, bandwidth costs, and protection against unauthorized downloads:
| Dimension | A: Public IPFS / S3 static URL | B: Traditional account/password + JWT download | C: MusicFlow on-chain verification + 60s signed URL |
|---|---|---|---|
| Hotlinking and sharing prevention | No protection (anyone with the URL can download without limits) | Shared accounts or copied JWTs enable unauthorized distribution | Excellent (generated per request, expires in 60 seconds, strongly bound to wallet keys) |
| Storage-node attack resistance | Exposed source bucket can incur huge malicious-traffic bills | Requires a reverse proxy forwarding every large file | Direct edge delivery (R2/S3 connects to client after handshake; zero server forwarding bandwidth) |
| Actual asset ownership | Cannot verify payment | Relies on a centralized database; tampering corrupts entitlements | Tamper-resistant in code (direct state-machine queries support cross-platform recognition) |
| Existing customers’ rights | Cannot distinguish rights before and after a buyout | Complex logic can harm existing users during product changes | Automatically supports grandfathered pre-buyout rights |
| Implementation complexity | Very low (expose URL) | Moderate | High (coordinate contracts, Next.js edge routes, and object-storage SDK) |
6. Integrating Royalty Sharing and Exclusive Licensing
Short-lived signed downloads are the final delivery step in the Web3 music business lifecycle and interlock with the preceding systems:
- Multilevel licensing state-machine integration: After a client purchases personal or commercial sync rights through the Mutually Exclusive Multilevel Licensing Design, the resulting on-chain
LicenseReceiptbecomes the gateway’s sole authorization basis. If a third party buys out the track, the gateway usesbuyoutTimestampto determine subsequent download eligibility. - Dynamic contributor royalty accumulation: Every purchase that enables a signed download has already credited songwriters’ and producers’ unwithdrawn balances through the Dynamic Contributor O(1) Royalty Accumulator, automating revenue sharing at delivery and making those earnings immediately withdrawable.
Consulting and Source-Code Delivery
If you are planning a high-value digital-content marketplace for lossless music, film sound-effect packs, AI training datasets, or 3D assets, and want a Web3 system combining fast previews with military-grade delivery protection:
- Visit Fone’s Client Deliveries and System Demos to explore Fone MusicFlow preview watermarks, on-chain verification, and short-lived presigned master downloads;
- Read our Full-Stack Architecture for On-Chain Music Licensing and Multi-Creator Revenue Splits;
- Book a one-to-one discussion through Fone Architecture Consulting for a standard delivery package containing contract source, Next.js edge-gateway code, and Cloudflare R2 security policies.