Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 6 min read

Building a Zero-Account Phone-Camera QR Handoff Bridge on Cloudflare Workers + D1 (No WebSockets, No Redis)

When someone sits at a desktop computer drafting a floor plan, the hand-drawn sketch they want to digitize is almost always sitting on a clipboard or kitchen table right next to their keyboard. Asking them to take a phot

When someone sits at a desktop computer drafting a floor plan, the hand-drawn sketch they want to digitize is almost always sitting on a clipboard or kitchen table right next to their keyboard. Asking them to take a photo on their phone, email or AirDrop it to themselves, convert HEIC to JPEG, and hunt through Downloads kills momentum before they ever draw their first wall.

For PlanCaliber, we needed a desktop-to-phone camera bridge with four strict constraints:

  1. Zero sign-in on either device. A first-time desktop visitor should be able to scan a QR code and snap a sketch in under 15 seconds without creating an account or typing a password on mobile.
  2. Zero persistent connection infrastructure. No WebSockets, no Redis pub/sub, and no Durable Objectsβ€”just stateless Cloudflare Workers backed by SQLite (D1).
  3. No raw pairing tokens stored at rest, and immediate erasure of uploaded image previews upon delivery.
  4. Race-safe against impatient double-taps on mobile and concurrent browser tabs polling on desktop.

Here is the exact 5-step TypeScript and SQLite state machine we shipped in production (src/lib/cad/qr.ts and src/lib/server/handoff.ts).

1. 128-Bit Pairing Tokens & Single-Path SVG QR Rendering

We generate a 128-bit cryptographic token using Web Crypto (crypto.getRandomValues), encode it as URL-safe Base64 with a pcs_ prefix, and reject any malformed token at the edge with a strict regex before touching D1:

import QRCode from 'qrcode';

const HANDOFF_TOKEN_RE = /^pcs_[A-Za-z0-9_-]{22}$/;
const MAX_PREVIEW_DATA_URL_CHARS = 180_000;
const SAFE_JPEG_DATA_URL_RE = /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/;

export function generateHandoffToken(): string {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  let binary = '';
  for (const b of bytes) binary += String.fromCharCode(b);
  const b64url = btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
  return `pcs_${b64url}`;
}

export function isValidHandoffToken(token: unknown): token is string {
  return typeof token === 'string' && HANDOFF_TOKEN_RE.test(token);
}

Instead of rendering the QR code to a blurry raster <canvas> or injecting raw SVG strings via innerHTML (which widens XSS surface), we inspect the boolean module matrix from QRCode.create() and compile every dark cell into a single static SVG <path d="..."> string:

export function buildQrSvgPath(url: string): { qrSize: number; qrPath: string } {
  const qr = QRCode.create(url, { errorCorrectionLevel: 'M' });
  const size = qr.modules.size;
  const data = qr.modules.data;
  const margin = 2;
  let d = '';
  for (let r = 0; r < size; r++) {
    for (let c = 0; c < size; c++) {
      if (data[r * size + c]) {
        d += `M${c + margin} ${r + margin}h1v1h-1z`;
      }
    }
  }
  return { qrSize: size + margin * 2, qrPath: d };
}

The frontend drops {qrPath} straight into a native <svg viewBox="0 0 {qrSize} {qrSize}"><path d={qrPath} /></svg>. Zero {@html} calls, razor-sharp on any Retina display, and ~1.4 KB over the wire.

2. Storing Only SHA-256(token) + Binding Desktop Ownership

When the desktop browser requests POST /api/vision/handoff, we:

  • Require either a signed-in user ID or an HTTP-only __Host- guest draft cookie hash.
  • Sweep expired rows (expires_at < now) inline so stale tokens self-clean without needing a separate cron job.
  • Rate-limit pairing generation per hashed client IP (15 codes/hour).
  • Hash the 128-bit token with SHA-256 and never store the plaintext token in D1.
const HANDOFF_TTL_MS = 15 * 60 * 1000;
const MAX_HANDOFFS_PER_HOUR = 15;
const MAX_ATTEMPTS_PER_TOKEN = 3;

const token = generateHandoffToken();
const tokenHash = await sha256Hex(token);
const expiresAt = new Date(nowMs + HANDOFF_TTL_MS).toISOString();
const snapUrl = `${params.origin.replace(/\/$/, '')}/s/${token}`;
const { qrSize, qrPath } = buildQrSvgPath(snapUrl);

await db()
  .prepare(
    `INSERT INTO sketch_handoffs (
      token_hash, owner_user_id, draft_token_hash, ip_hash, status, attempts, created_at, expires_at
    ) VALUES (?, ?, ?, ?, 'pending', 0, ?, ?)`
  )
  .bind(tokenHash, ownerUserId, draftHash, ipHash, nowIso, expiresAt)
  .run();

If anyone ever dumped the sketch_handoffs table, they still could not reconstruct active /s/pcs_... URLs. And because the desktop's owner_user_id or draft_token_hash is recorded on creation, a third party who happens to glance over a shoulder and scan the QR code still cannot poll and read back the parsed geometryβ€”only the originating desktop session passes callerOwnsHandoff().

3. Atomic Compare-and-Swap Lock Against Mobile Double-Submits

On cellular connections, users routinely tap "Upload Sketch" twice when a request takes more than a second. Without an atomic transition, two parallel vision parses can race on the same pairing token and burn quota twice.

In SQLite / D1, a single conditional UPDATE acts as an optimistic mutex:

const lockRes = await db()
  .prepare(
    `UPDATE sketch_handoffs
     SET status = 'processing', attempts = attempts + 1
     WHERE token_hash = ? AND status = 'pending' AND expires_at > ? AND attempts < ?`
  )
  .bind(tokenHash, nowIso, MAX_ATTEMPTS_PER_TOKEN)
  .run();

if ((lockRes.meta?.changes ?? 0) !== 1) {
  return {
    httpStatus: 409,
    body: { status: 'error', detail: 'Sketch upload is already processing. Hold steady for a moment.' }
  };
}

Notice the recovery path too: if the vision parser returns a transient error or rejects an unreadable photo, we reset status = 'pending' while keeping the incremented attempts counter (capped at 3 per QR code). That gives the user two clean retries on the same QR code without unlocking infinite abuse.

Before storing a thumbnail overlay for the desktop tracing layer, sanitizePreviewDataUrl() validates both the MIME prefix and strict character cap:

export function sanitizePreviewDataUrl(raw: unknown): string | null {
  if (typeof raw !== 'string') return null;
  const trimmed = raw.trim();
  if (trimmed.length === 0 || trimmed.length > MAX_PREVIEW_DATA_URL_CHARS) return null;
  if (!SAFE_JPEG_DATA_URL_RE.test(trimmed)) return null;
  return trimmed;
}

Any SVG, HTML, or oversized payload is dropped to null before hitting the database.

4. One-Shot Atomic Claim & Instant Payload Erasure

On desktop, the modal polls GET /api/vision/handoff/[token] every ~2 seconds while displaying live state (Waiting for phone... -> Processing sketch...).

The moment status === 'completed', the desktop claims the payload using a second compare-and-swap update that simultaneously transitions the row to claimed and wipes result_json and preview_data_url to NULL:

if (row.status === 'completed' && row.result_json) {
  const claimRes = await db()
    .prepare(
      `UPDATE sketch_handoffs
       SET status = 'claimed', result_json = NULL, preview_data_url = NULL
       WHERE token_hash = ? AND status = 'completed'`
    )
    .bind(tokenHash)
    .run();

  if ((claimRes.meta?.changes ?? 0) === 1) {
    const vision = JSON.parse(row.result_json) as VisionParseResponse;
    return {
      httpStatus: 200,
      body: {
        status: 'completed',
        vision,
        previewDataUrl: row.preview_data_url
      }
    };
  }
}

Checking claimRes.meta?.changes === 1 guarantees two things at once:

  1. Exactly-once delivery, even if two tabs or overlapping poll timers hit the endpoint in the same millisecond.
  2. Zero lingering sketch images in D1: the parsed CAD JSON and JPEG underlay live in SQLite only for the ~2 seconds between phone completion and desktop pickup.

Why Polling + D1 Beat WebSockets Here

For a high-frequency chat room or multiplayer cursor sync, WebSockets and Durable Objects are the right architecture. For a single-event phone-to-desktop camera handoff that lasts 15 to 45 seconds:

  • A 2-second poll hits a single indexed primary-key lookup (WHERE token_hash = ?) in D1β€”sub-millisecond SQLite work with zero stateful socket teardown bugs when a phone switches from Wi-Fi to LTE mid-upload.
  • Every state transition (pending -> processing -> completed -> claimed) is auditable, idempotent, and survives Worker cold starts cleanly.
  • No extra cloud services, no connection fees, and zero auth friction for the person holding the phone.

Try It Live

You can test the Phone QR handoff directly inside the PlanCaliber 2D/3D Floor Plan & Sketch-to-CAD Studio (click Phone QR in the top barβ€”no account required), or upload an existing raster/PDF drawing via our PDF Floor Plan to CAD Converter.

(Note: PlanCaliber generates preliminary space-planning and CAD drafting sheets for design coordination; always verify dimensions and building codes on site.)

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.