Skip to main content
01 // ENGINEERING SPECIFICATION1st Place Winner — Devpost Hackathon

PaperLoom: Physical-to-Cloud Learning Workspace with Fingerprint-Scoped RLS & Grounded Curriculum Audits

A 1st-place Devpost hackathon project that links physical textbook or notebook scans to a 64-character SHA-256 hardware fingerprint, enforces per-document Supabase Row-Level Security via custom short-lived HS256 JWT claims, runs Tavily-grounded Gemini 2.5 Flash curriculum gap audits across 17 verified academic domains, and provisions an adaptive cognitive workspace.

Published 2026-08-01Updated 2026-08-0510 min readGitHub Repository
Next.js App RouterTypeScriptSupabase RLSESP32 (Wokwi / mbedtls)Gemini 2.5 FlashTavily Search APIRender REST APIjose (HS256 JWT)

1. Overview#

PaperLoom is a physical-to-cloud learning system—and 1st Place Winner at a Devpost Hackathon—designed for students who study primarily from physical textbooks and handwritten notes but need structured digital remediation when they hit conceptual roadblocks.

Instead of requiring account registration, manual folder hierarchies, or open-ended chatbot prompting, PaperLoom uses a 64-character hexadecimal SHA-256 fingerprint derived from a scanned page (simulated via an ESP32 + SSD1306 OLED hardware node in Wokwi or captured through the browser scan console) as both the document identifier and the cryptographic authorization boundary. When a page is ingested at /api/ingest, PaperLoom:

  1. Stores the raw scan in Supabase (public.books_and_notes) keyed by fingerprint_hash.
  2. Runs targeted academic web searches via Tavily restricted to 17 allowlisted educational domains (openstax.org, ocw.mit.edu, khanacademy.org, ncert.nic.in, libretexts.org, etc.).
  3. Audits the scanned passage with Gemini 2.5 Flash (responseSchema: educationalAuditJsonSchema) to detect prerequisite conceptual gaps, plain-language explanations, practice checkpoints, and verified citations.
  4. Mints a 10-minute HS256 JWT (scope: "paperloom:fingerprint") signed with SUPABASE_JWT_SECRET so the browser can query only that specific page's rows directly via PostgreSQL Row-Level Security (RLS) on /dashboard/[hash].
  5. Optionally provisions an isolated per-workspace static site via the Render REST API (/api/deploy).

2. The Problem#

Students working from physical paper face four recurring failure modes when switching to digital study tools:

  • High friction between paper and digital context: Taking a photo or retyping notes into a general-purpose LLM loses structural continuity and forces the student to act as their own prompt engineer.
  • Hallucinated educational citations: Standard LLM study assistants frequently invent textbook section numbers or fabricate dead URLs when asked for remedial reading on physics, calculus, or chemistry topics.
  • Heavyweight authentication vs. zero-privacy public links: Traditional EdTech apps either force multi-step account onboarding before showing a single result or expose student notes on unauthenticated public URLs where anyone can enumerate database rows.
  • Cognitive overload on dense diagnostic dashboards: Presenting five missing concepts, ten external links, and raw OCR text simultaneously overwhelms students with ADHD, dyslexia, or high test anxiety.

3. The Approach#

PaperLoom addresses these constraints through four deliberate architectural choices:

  1. Hardware-Derived SHA-256 Identity & Custom JWT RLS: Rather than building an email/password auth wall for an ephemeral study session, the ESP32 scanner computes an mbedtls SHA-256 digest (fingerprint_hash). The backend signs a short-lived (10m) HS256 JWT embedding fingerprint_hash as a custom claim, and PostgreSQL RLS policies enforce auth.jwt() ->> 'fingerprint_hash' = fingerprint_hash on every SELECT, INSERT, and UPDATE.
  2. Retrieval-First Curriculum Auditing with Post-Generation URL Coercion: Instead of asking Gemini to suggest links from parametric memory, /api/ingest extracts significant domain terms, infers a subject hint (physics, chemistry, calculus, biology), queries Tavily across 17 trusted academic domains, and passes those verified sources into Gemini. After Gemini returns structured JSON, coerceAuditResourcesToTavilyUrls() removes or replaces any resource URL that does not match the exact normalized Tavily URL set.
  3. Progressive Multi-Modal Reading Interface: The /dashboard/[hash] workspace renders identical underlying data through three cognitive modes—Standard (tabbed overview, scan, gaps, sources, practice), Bionic (expanded line height/letter spacing with bolded word stems for faster saccadic fixation), and Horizon (single-card focus mode that isolates one high-severity gap at a time).
  4. Resilient Cloud Workspace Provisioning: When a student wants a dedicated cloud endpoint for their workspace, lib/renderDeployer.ts provisions a Render static_site service with exponential backoff, jitter, and Retry-After header parsing.

4. System Architecture#

PaperLoom connects an embedded C++ hardware simulation layer, a Next.js App Router ingestion and deployment API layer, a Supabase PostgreSQL database with custom JWT functions, and a client-side cognitive workspace.

SYSTEM SCHEMATIC // PAPERLOOM PHYSICAL-TO-CLOUD INGESTION, CUSTOM JWT RLS & COGNITIVE WORKSPACE PIPELINE
01. Physical & Browser Capture Layer
ESP32 + SSD1306 Scanner Node

Samples 96-point optical fiber array on GPIO 18 trigger and computes hardware SHA-256 digest

wokwi/sketch.ino · mbedtls/sha256.h
Browser Scan Console

Client-side Web Crypto SHA-256 hashing for uploaded Markdown/text study notes

app/page.tsx · crypto.subtle
HTTPS POST /api/ingest (64-char SHA-256 fingerprint + raw_text)
02. Next.js App Router Ingestion, Grounding & Auth Layer
Curriculum Audit Pipeline (/api/ingest)

Infers subject domain, queries 17 trusted academic sites via Tavily, and audits gaps with Gemini 2.5 Flash

app/api/ingest/route.ts · Zod
Fingerprint JWT Issuer

Signs 10-minute HS256 JWT carrying fingerprint_hash and scope=paperloom:fingerprint

jose · SUPABASE_JWT_SECRET
Cloud Provisioner (/api/deploy)

Provisions isolated Render static_site services with Retry-After and exponential backoff

lib/renderDeployer.ts · app/api/deploy/route.ts
Service-Role Upsert + 10m HS256 Bearer Token
03. Persistence & Adaptive Cognitive Workspace
Supabase PostgreSQL + Custom RLS

Enforces paperloom_fingerprint_authorized(fingerprint_hash) across books_and_notes & educational_gaps

supabase/migrations/202608010001_paperloom_core.sql
Adaptive Cognitive Workspace (/dashboard/[hash])

Queries Supabase directly with custom JWT and switches between Standard, Bionic, and Horizon modes

app/dashboard/[hash]/page.tsx · React 19
Figure: PaperLoom Physical-to-Cloud Ingestion, Custom JWT RLS & Cognitive Workspace Pipeline

5. Engineering Deep Dive#

5.1 Embedded ESP32 SHA-256 Fingerprinting (`wokwi/sketch.ino`)#

On the hardware simulation side, an ESP32 wired to a 128x64 SSD1306 I2C OLED display (SDA=21, SCL=22) and a pull-up scan button (GPIO 18) samples a 96-element optical fiber reflectance array (mockFiberSensorData), packs each 16-bit reading into a byte buffer, and computes a SHA-256 digest using mbedtls/sha256.h before posting the JSON payload to /api/ingest:

wokwi/sketch.inocpp
String generateFingerprintHash() {
  uint8_t sensorBytes[sizeof(mockFiberSensorData) * 2];

  for (size_t i = 0; i < sizeof(mockFiberSensorData) / sizeof(mockFiberSensorData[0]); i++) {
    uint16_t value = mockFiberSensorData[i];
    sensorBytes[i * 2] = highByte(value);
    sensorBytes[i * 2 + 1] = lowByte(value);
  }

  uint8_t shaResult[32];
  mbedtls_sha256_context context;
  mbedtls_sha256_init(&context);
  mbedtls_sha256_starts(&context, 0);
  mbedtls_sha256_update(&context, sensorBytes, sizeof(sensorBytes));
  mbedtls_sha256_finish(&context, shaResult);
  mbedtls_sha256_free(&context);

  return bytesToHex(shaResult, sizeof(shaResult));
}

5.2 Tavily Academic Grounding & Post-Generation URL Coercion (`app/api/ingest/route.ts`)#

To prevent Gemini from hallucinating external study links, /api/ingest restricts Tavily searches to 17 verified educational domains (openstax.org, ocw.mit.edu, khanacademy.org, ncert.nic.in, libretexts.org, etc.) and then runs coerceAuditResourcesToTavilyUrls() over Gemini's structured JSON response so every returned VerifiedResource is guaranteed to map to a real URL returned by Tavily in that request:

app/api/ingest/route.tstypescript
function coerceAuditResourcesToTavilyUrls(
  audit: EducationalAuditResult,
  tavilyResources: VerifiedResource[]
): EducationalAuditResult {
  const allowedByNormalizedUrl = new Map<string, VerifiedResource>();

  for (const resource of tavilyResources) {
    const normalized = normalizeUrlKey(resource.url);
    if (normalized && !allowedByNormalizedUrl.has(normalized)) {
      allowedByNormalizedUrl.set(normalized, resource);
    }
  }

  const coercedVerified: VerifiedResource[] = [];
  const usedUrls = new Set<string>();

  for (const candidate of audit.verified_resources) {
    const key = normalizeUrlKey(candidate.url);
    const matched = key ? allowedByNormalizedUrl.get(key) : undefined;
    if (!matched || usedUrls.has(matched.url)) continue;

    usedUrls.add(matched.url);
    coercedVerified.push({
      title: candidate.title.trim() || matched.title,
      url: matched.url,
      domain: extractHostname(matched.url) || matched.domain,
      snippet: candidate.snippet.trim() || matched.snippet,
      relevance_reason: candidate.relevance_reason.trim() || matched.relevance_reason,
      supports_concepts:
        candidate.supports_concepts.length > 0
          ? candidate.supports_concepts
          : matched.supports_concepts
    });
  }

  // Fallback to top Tavily results if model omitted valid URLs
  for (const fallback of tavilyResources) {
    if (coercedVerified.length >= 6) break;
    if (usedUrls.has(fallback.url)) continue;
    usedUrls.add(fallback.url);
    coercedVerified.push(fallback);
  }

  return {
    ...audit,
    verified_resources: coercedVerified.slice(0, 8)
  };
}

5.3 Fingerprint-Scoped PostgreSQL Row-Level Security (`supabase/migrations/202608010001_paperloom_core.sql`)#

After persisting the scan and audit, /api/ingest mints a 10-minute HS256 JWT via jose:

app/api/ingest/route.tstypescript
async function createFingerprintJwt(
  fingerprintHash: string,
  jwtSecret: string,
  deviceId: string
): Promise<{ token: string; expiresAt: string }> {
  const issuedAtSeconds = Math.floor(Date.now() / 1000);
  const expiresAtSeconds = issuedAtSeconds + 10 * 60;
  const secretKey = new TextEncoder().encode(jwtSecret);

  const token = await new SignJWT({
    aud: "authenticated",
    role: "authenticated",
    fingerprint_hash: fingerprintHash,
    device_id: deviceId,
    scope: "paperloom:fingerprint"
  })
    .setProtectedHeader({ alg: "HS256", typ: "JWT" })
    .setIssuedAt(issuedAtSeconds)
    .setExpirationTime(expiresAtSeconds)
    .setIssuer("paperloom-ingest")
    .setSubject(fingerprintHash)
    .sign(secretKey);

  return { token, expiresAt: new Date(expiresAtSeconds * 1000).toISOString() };
}

Inside Supabase PostgreSQL, both public.books_and_notes and public.educational_gaps enforce Row-Level Security (ENABLE ROW LEVEL SECURITY + FORCE ROW LEVEL SECURITY) using SECURITY DEFINER and STABLE SQL helper functions that inspect auth.jwt() ->> 'fingerprint_hash':

supabase/migrations/202608010001_paperloom_core.sqlsql
CREATE OR REPLACE FUNCTION public.paperloom_jwt_fingerprint_hash()
RETURNS text
LANGUAGE sql
STABLE
SET search_path = pg_catalog
AS $$
    SELECT NULLIF(auth.jwt() ->> 'fingerprint_hash', '');
$$;

CREATE OR REPLACE FUNCTION public.paperloom_fingerprint_authorized(row_fingerprint_hash text)
RETURNS boolean
LANGUAGE sql
STABLE
SET search_path = pg_catalog
AS $$
    SELECT COALESCE(row_fingerprint_hash = public.paperloom_jwt_fingerprint_hash(), false);
$$;

CREATE POLICY books_and_notes_select_by_fingerprint_claim
ON public.books_and_notes
FOR SELECT
TO anon, authenticated
USING (
    public.paperloom_fingerprint_authorized(fingerprint_hash)
);

5.4 Fault-Tolerant Render Service Provisioning (`lib/renderDeployer.ts`)#

When a student triggers cloud deployment from /dashboard/[hash], /api/deploy verifies the bearer JWT's fingerprint_hash and scope === "paperloom:fingerprint" claims and calls provisionStudentRenderWorkspace(). The deployer wraps fetch("https://api.render.com/v1/services") with a 45,000ms AbortController timeout, Retry-After header parsing, and bounded exponential backoff (baseDelayMs * 2^(attempt-1) + jitter) across 429 and 5xx responses.

6. Technical Demo#

Technical Walkthrough & Verification
Recorded video walkthrough coming soon

Technical walkthrough recording coming soon

End-to-end walkthrough of the Wokwi ESP32 OLED hardware scan generating an mbedtls SHA-256 document digest, the /api/ingest Tavily + Gemini curriculum gap audit, custom JWT RLS verification in Supabase, and cognitive mode switching (Standard, Bionic, Horizon).

Walkthrough Sequence & Checkpoints

  1. 00:00
    ESP32 Hardware Node & mbedtls SHA-256 Digest — Triggering the Wokwi ESP32 scanner over GPIO 18, inspecting SSD1306 OLED status frames, and computing the 64-character SHA-256 fingerprint.
  2. 00:50
    Tavily Academic Grounding & Gemini 2.5 Flash Audit — Executing parallel targeted searches across 17 allowlisted educational domains and stripping unverified URLs via coerceAuditResourcesToTavilyUrls().
  3. 01:45
    Custom HS256 JWT Minting & Supabase RLS Verification — Inspecting the 10-minute paperloom:fingerprint bearer token and querying books_and_notes and educational_gaps directly from the browser under RLS.
  4. 02:30
    Adaptive Cognitive Workspace & Render Service Provisioning — Toggling Bionic stem emphasis and Horizon single-card focus mode on /dashboard/[hash] and triggering /api/deploy.
View Written Walkthrough Summary / Transcript ▾

PaperLoom bridges physical study materials—textbooks and handwritten problem sets—with an isolated, grounded cloud workspace without forcing students through account creation or open-ended chatbot prompting.

When a scan is triggered on the ESP32 node (or via the browser scan console), the firmware samples a 96-point optical reflectance array and computes a 64-character SHA-256 digest using mbedtls. That digest acts as both the document primary key and the cryptographic authorization claim.

During ingestion at /api/ingest, the server infers the academic subject, executes parallel Tavily searches restricted to 17 verified educational domains (such as OpenStax, MIT OpenCourseWare, Khan Academy, and NCERT), audits prerequisite gaps with Gemini 2.5 Flash, and intersects every returned URL against the live Tavily result set before minting a 10-minute custom HS256 JWT for Supabase Row-Level Security.

7. Challenges and Trade-offs#

  • Short-Lived Custom JWTs vs. Persistent User Accounts: Minting a 10-minute HS256 JWT scoped to fingerprint_hash eliminates sign-up friction during hardware demonstrations and prevents cross-document enumeration in Supabase. The trade-off is that browser sessions expire after 10 minutes unless re-authenticated via a fresh scan or /api/ingest token refresh.
  • Strict URL Coercion vs. Recall: Stripping every Gemini-suggested URL that is not verbatim in the current Tavily response occasionally drops valid canonical links the model knew from pretraining, but guarantees zero fabricated URLs in the student workspace.
  • Simulated Optical Fiber Sensor Array in Wokwi: Because physical optical paper-fiber microscopy requires custom optics beyond standard breadboard components, the Wokwi sketch uses a deterministic 96-point reflectance curve (mockFiberSensorData) combined with real mbedtls SHA-256 hashing and live HTTPS ingestion so the cryptographic and cloud pipeline remains 100% real.

8. Testing and Validation#

  • Row-Level Security Claim Enforcement: Verified in Supabase PostgreSQL (202608010001_paperloom_core.sql) with FORCE ROW LEVEL SECURITY enabled that anon and authenticated roles return zero rows from books_and_notes and educational_gaps unless the bearer JWT carries a matching fingerprint_hash claim.
  • Schema & Citation Coercion Validation: Tested /api/ingest against physics, chemistry, calculus, and biology passages with educationalAuditSchema.safeParse() and coerceAuditResourcesToTavilyUrls(), confirming that any non-Tavily URL is deterministically stripped and backfilled from verified domain results.
  • Render API Retry & Timeout Handling: Validated lib/renderDeployer.ts against 401/403 (RenderAuthenticationError), 429 with Retry-After headers (RenderRateLimitError), and AbortController request timeouts.

9. What I Learned#

  • PostgreSQL RLS with Custom JWT Claims Is a Powerful Zero-Login Primitive: Encoding hardware or document provenance (fingerprint_hash) directly into a short-lived HS256 JWT lets the browser use the standard Supabase client safely without exposing a service-role key or requiring user accounts.
  • LLM Grounding Needs Deterministic Post-Filtering: Passing search results into the prompt is necessary but insufficient; intersecting model output URLs against the retrieval set in TypeScript (coerceAuditResourcesToTavilyUrls) is what actually enforces citation integrity.
  • Cognitive Presentation Modes Should Share One Data Contract: Driving Standard, Bionic, and Horizon modes from the same EducationalAuditResult schema kept the React state machine simple while drastically changing reading ergonomics.

10. Future Improvements#

  • ESP32-CAM + Vision OCR Ingestion: Pair an ESP32-CAM module with Gemini multimodal vision so handwritten notebook pages and drawn circuit diagrams are transcribed directly from camera frames.
  • Refresh Token Rotation for Extended Study Sessions: Add an encrypted HTTP-only refresh cookie bound to the device fingerprint so students can revisit /dashboard/[hash] across multi-hour study sessions without rescanning.
  • Spaced-Repetition Export: Allow one-click export of practice_questions and missing_concepts into Anki .apkg or Markdown flashcards.