Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ CLOUDINARY_TRIAL_PRESET=pravaha_trial
TRIALS_PER_DAY=5
# Read-only demo Studio for visitors without the passcode: on | off
STUDIO_DEMO=on
# Optional: who may frame /embed/ask (a frame-ancestors source list; default any HTTPS page). docs/EMBED.md
EMBED_FRAME_ANCESTORS=

# Neon Postgres — pooled connection string
DATABASE_URL=
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ Colleges, clubs and coaching institutes record hundreds of hours of lectures and
| **Study Packs** | Every session gets a summary, key concepts, a quiz whose explanations **play the moment** the teacher explains it, and a "Session in 60 seconds" highlight reel. Pravaha generates them automatically from the transcript. |
| **Moments** | One tap turns any cited clip into a vertical, AI-cropped, subtitled short for WhatsApp or Instagram, with its own share page and preview card. The short is just a Cloudinary URL; nothing is rendered. |
| **Insights** | Organizers see what learners ask, the **knowledge gaps** the library can't answer yet (what to record next), and which Moments get shared. Visitors can explore a read-only demo of the Studio. |
| **Embed** | Organizers copy one `<iframe>` from the Studio and put **Ask** inside Moodle, Canvas or any course page, for the whole library or one session. Only that route can be framed. See [`docs/EMBED.md`](docs/EMBED.md). |
| **Try it** | Anyone can upload a short video at `/try`, no account: Cloudinary keeps the first 60 seconds, transcribes and chapters it, and about 20 seconds later it has a Study Pack and an **Ask this session** box. Trials are private and deleted after 24 hours. |

> *ChatGPT gives you text. Pravaha gives you the moment your professor said it.*
Expand Down Expand Up @@ -277,6 +278,7 @@ The app deploys to **Vercel**: every push to `main` deploys production, and pull
| [`docs/CLOUDINARY.md`](docs/CLOUDINARY.md) | Every Cloudinary capability, and what breaks without it |
| [`docs/TRD.md`](docs/TRD.md) · [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Stack, reasoning, diagrams |
| [`docs/DATABASE.md`](docs/DATABASE.md) · [`docs/API.md`](docs/API.md) · [`openapi.yaml`](openapi.yaml) | Schema and endpoints |
| [`docs/EMBED.md`](docs/EMBED.md) | Putting Ask inside an LMS: snippet, sizing, framing policy |
| [`docs/AI_EVALUATION.md`](docs/AI_EVALUATION.md) | Ask's retrieval, prompt, citation validation, fallback and eval |
| [`docs/UX_UI.md`](docs/UX_UI.md) · [`docs/DESIGN_SYSTEM.md`](docs/DESIGN_SYSTEM.md) | Screens, interaction and motion, design tokens |
| [`docs/SECURITY.md`](docs/SECURITY.md) · [`docs/COST.md`](docs/COST.md) | Trust boundaries and cost controls |
Expand Down
73 changes: 73 additions & 0 deletions docs/EMBED.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Embedding Ask in an LMS

Learners already live in Moodle, Canvas, Google Classroom sites or a course page. Pravaha's Ask box can sit
there as an iframe, so they ask the recordings without leaving the course or making an account.

## Get the code

In the **Studio**, open the Sessions tab:

- **Embed Ask in your LMS** (above the session list) asks the whole published library.
- **Embed** on a ready session asks just that recording. Unlisted sessions can be embedded too; the organizer
chose to share them. Trial sessions can't (they're deleted within a day).

Each gives a snippet to copy and a **Preview** link:

```html
<iframe src="https://<your-pravaha>/embed/ask?session=<session-id>" title="Ask Overfitting — Pravaha"
width="100%" height="640" style="border:0;border-radius:12px"
allow="clipboard-write; fullscreen" loading="lazy"></iframe>
```

| URL | What it asks |
|---|---|
| `/embed/ask` | Every published session |
| `/embed/ask?session=<id>` | One session |
| `…&theme=dark` or `theme=light` | Forces a theme to match the host page; otherwise it follows the learner's system |

Paste it wherever the LMS accepts HTML: in Moodle a **Page** or **Label** in the HTML editor, in Canvas the
page editor's HTML view, in Google Sites **Embed → Embed code**.

## What the learner gets

The same grounded Ask as the site: streamed progress, an answer only from the recordings, a playable clip for
every claim, an Answer Reel and follow-up questions that stay in the embed. Links to the rest of Pravaha
(a session's Watch page, a shared answer) open in a new tab so the course page stays put. The site header and
footer are left out.

## Fitting the frame

`height="640"` fits a question and a short answer; the embed scrolls inside it. Hosts that run their own
scripts can size it to the content instead: the embed posts its height whenever it changes.

```html
<script>
addEventListener("message", (e) => {
if (e.origin !== "https://<your-pravaha>" || e.data?.type !== "pravaha:height") return;
for (const f of document.querySelectorAll('iframe[src^="https://<your-pravaha>/embed/"]')) f.style.height = e.data.height + "px";
});
</script>
```

The message carries only `{ type: "pravaha:height", height }`, never the question or the answer.

## Security

`/embed/*` is the only route that may be framed (`next.config.ts`). Every other page keeps
`X-Frame-Options: DENY` and `frame-ancestors 'none'`, so the Studio, Watch pages and shared answers can't be
clickjacked. The embed itself has no sign-in, cookies or actions beyond asking, which is what makes it safe
to frame.

By default any HTTPS page may frame it. An institute can restrict it to its own LMS with an environment
variable (a [`frame-ancestors`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors)
source list, applied at build time, so redeploy after changing it):

```bash
EMBED_FRAME_ANCESTORS="https://moodle.example.edu https://*.instructure.com"
```

## Limits

Ask is rate-limited per IP address (60 questions an hour) before any paid AI call (`src/lib/rate-limit.ts`).
A whole class behind one campus network shares an address, so a deployment for a large class should raise
`ASK_PER_IP_PER_HOUR`. The library-wide cap of 500 questions a day still bounds the cost.
2 changes: 1 addition & 1 deletion docs/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,4 @@ Rights confirmation is required before upload (`rights_confirmed_at`), sessions

## HTTP Security Headers

Every response carries (`next.config.ts`): `Strict-Transport-Security` (2 years, subdomains, preload), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `X-Frame-Options: DENY` plus `Content-Security-Policy: frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'` (no clickjacking, no base-tag or plugin injection), and a `Permissions-Policy` that turns off camera, microphone, geolocation, payment and USB. `X-Powered-By` is removed. A full script-source CSP is deliberately not set yet: the Cloudinary Video Player loads scripts, styles and HLS segments from several hosts, so that policy needs testing against every player feature first.
Every response carries (`next.config.ts`): `Strict-Transport-Security` (2 years, subdomains, preload), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `X-Frame-Options: DENY` plus `Content-Security-Policy: frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'` (no clickjacking, no base-tag or plugin injection; the one exception is `/embed/*`, the sign-in-free Ask box an LMS frames, whose `frame-ancestors` is `https:` or the `EMBED_FRAME_ANCESTORS` list; see [`EMBED.md`](EMBED.md)), and a `Permissions-Policy` that turns off camera, microphone, geolocation, payment and USB. `X-Powered-By` is removed. A full script-source CSP is deliberately not set yet: the Cloudinary Video Player loads scripts, styles and HLS segments from several hosts, so that policy needs testing against every player feature first.
22 changes: 18 additions & 4 deletions next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,36 @@ import type { NextConfig } from "next";
// Baseline security headers on every response (docs/SECURITY.md). No full script CSP yet: the Cloudinary
// Video Player loads its own scripts, styles and HLS media from several hosts, so a strict policy needs
// testing against every player feature first. frame-ancestors still blocks clickjacking.
const securityHeaders = [
const baseHeaders = [
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Content-Security-Policy", value: "frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'" },
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), payment=(), usb=()" },
];
const policy = (ancestors: string) => `frame-ancestors ${ancestors}; base-uri 'self'; form-action 'self'; object-src 'none'`;

// /embed/* is the one framable route: the Ask box an LMS or course page puts in an iframe (docs/EMBED.md).
// EMBED_FRAME_ANCESTORS narrows it to an institute's own origins; the default allows any HTTPS page.
// Every other route stays unframable (X-Frame-Options can't be relaxed per route, so it skips /embed).
const embedAncestors = process.env.EMBED_FRAME_ANCESTORS?.trim() || "https:";

const nextConfig: NextConfig = {
poweredByHeader: false,
images: {
remotePatterns: [{ protocol: "https", hostname: "res.cloudinary.com" }],
},
async headers() {
return [{ source: "/(.*)", headers: securityHeaders }];
return [
{ source: "/(.*)", headers: baseHeaders },
{
source: "/((?!embed(?:/|$)).*)",
headers: [
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Content-Security-Policy", value: policy("'none'") },
],
},
{ source: "/embed/:path*", headers: [{ key: "Content-Security-Policy", value: policy(embedAncestors) }] },
];
},
};

Expand Down
79 changes: 79 additions & 0 deletions src/app/embed/ask/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import type { Metadata } from "next";
import Link from "next/link";
import { z } from "zod";

import { AskSession } from "@/components/AskSession";
import { EmbedFrame } from "@/components/EmbedFrame";
import { LogoMark } from "@/components/Logo";
import { getLecture, suggestedQuestions } from "@/lib/lectures";
import { getStudyPack } from "@/lib/study-packs";
import { pickSuggestions } from "@/lib/suggestions";

export const metadata: Metadata = {
title: "Ask — Pravaha",
description: "Ask the recordings a question; every answer plays the moment it came from.",
robots: { index: false, follow: false },
};

type Props = { searchParams: Promise<{ session?: string }> };

// The Ask box an LMS or course page puts in an iframe: /embed/ask asks the published library,
// /embed/ask?session=<id> one session (unlisted ones too: the organizer chose to share it). This route alone
// may be framed (next.config.ts); the site header and footer are left out (SiteChrome).
export default async function EmbedAskPage({ searchParams }: Props) {
const { session } = await searchParams;

if (session === undefined) {
const suggestions = await suggestedQuestions(3);
return (
<EmbedShell>
<AskSession heading="Ask the library" suggestions={suggestions} />
</EmbedShell>
);
}

const lecture = z.uuid().safeParse(session).success ? await getLecture(session) : null;
// Trials expire within a day, so an embed of one would break; they never get an embed.
if (!lecture || lecture.status !== "ready" || lecture.trialExpiresAt) {
return (
<EmbedShell>
<p className="mt-6 rounded-2xl border border-border bg-surface p-5 text-sm text-muted">
This session isn&apos;t available to ask. It may still be processing or have been removed.
</p>
</EmbedShell>
);
}

const pack = await getStudyPack(lecture.id);
return (
<EmbedShell>
<p className="mt-4 truncate text-sm text-muted">
<Link href={`/watch/${lecture.id}`} className="font-medium text-fg hover:text-accent">
{lecture.title}
</Link>
{lecture.speaker ? ` · ${lecture.speaker}` : ""}
</p>
<AskSession lectureId={lecture.id} suggestions={pack ? pickSuggestions([pack], 3) : []} />
</EmbedShell>
);
}

function EmbedShell({ children }: { children: React.ReactNode }) {
return (
<EmbedFrame>
<div className="pt-4">
<Link href="/" className="inline-flex items-center gap-2 text-sm font-semibold tracking-tight">
<LogoMark className="size-5" />
Pravaha
</Link>
{children}
<p className="mt-6 text-xs text-muted">
Answers come only from these recordings, with a clip for every claim ·{" "}
<Link href="/privacy" className="underline underline-offset-4 hover:text-fg">
Privacy
</Link>
</p>
</div>
</EmbedFrame>
);
}
99 changes: 52 additions & 47 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Link from "next/link";

import { LogoMark } from "@/components/Logo";
import { SearchShortcut } from "@/components/SearchShortcut";
import { SiteChrome } from "@/components/SiteChrome";
import { THEME_INIT_SCRIPT, ThemeToggle } from "@/components/ThemeToggle";
import { publicBaseUrl } from "@/lib/site";

Expand Down Expand Up @@ -42,57 +43,61 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<a href="#main" className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-50 focus:rounded-lg focus:bg-accent focus:px-3 focus:py-2 focus:text-accent-fg">
Skip to content
</a>
<header className="sticky top-0 z-30 border-b border-transparent bg-bg/80 backdrop-blur supports-[backdrop-filter]:bg-bg/70">
<nav aria-label="Main" className="mx-auto flex max-w-280 items-center justify-between px-4 py-3">
<Link href="/" className="flex items-center gap-2 text-lg font-semibold tracking-tight">
<LogoMark />
Pravaha
</Link>
<div className="flex items-center gap-1 text-sm">
<Link href="/#library" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Library
<SiteChrome>
<header className="sticky top-0 z-30 border-b border-transparent bg-bg/80 backdrop-blur supports-[backdrop-filter]:bg-bg/70">
<nav aria-label="Main" className="mx-auto flex max-w-280 items-center justify-between px-4 py-3">
<Link href="/" className="flex items-center gap-2 text-lg font-semibold tracking-tight">
<LogoMark />
Pravaha
</Link>
<Link href="/saved" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Saved
</Link>
<Link href="/studio" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Studio
</Link>
<Link
href="/try"
className="ml-1 hidden rounded-lg bg-accent px-3 py-1.5 font-medium text-accent-fg hover:brightness-110 sm:inline-block"
>
Try it
</Link>
<ThemeToggle />
</div>
</nav>
</header>
<SearchShortcut />
<div className="flex items-center gap-1 text-sm">
<Link href="/#library" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Library
</Link>
<Link href="/saved" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Saved
</Link>
<Link href="/studio" className="rounded-lg px-3 py-2 text-muted hover:bg-surface hover:text-fg">
Studio
</Link>
<Link
href="/try"
className="ml-1 hidden rounded-lg bg-accent px-3 py-1.5 font-medium text-accent-fg hover:brightness-110 sm:inline-block"
>
Try it
</Link>
<ThemeToggle />
</div>
</nav>
</header>
<SearchShortcut />
</SiteChrome>
<main id="main" className="mx-auto w-full max-w-280 flex-1 px-4 pb-16">
{children}
</main>
<footer className="border-t border-border">
<div className="mx-auto flex max-w-280 flex-col gap-2 px-4 py-6 text-sm text-muted sm:flex-row sm:items-center sm:justify-between">
<p className="flex items-center gap-2">
<LogoMark className="size-5" />
Pravaha · ask your recordings, watch the answer
</p>
<p>
<Link href="/privacy" className="underline-offset-4 hover:text-fg hover:underline">
Privacy
</Link>{" "}
·{" "}
<Link href="/terms" className="underline-offset-4 hover:text-fg hover:underline">
Terms
</Link>{" "}
· Built on <span className="text-fg">Cloudinary</span> · Team Code Blooded ·{" "}
<a href="https://github.com/Monolithic-Dev/Pravaha" className="underline-offset-4 hover:text-fg hover:underline">
GitHub
</a>
</p>
</div>
</footer>
<SiteChrome>
<footer className="border-t border-border">
<div className="mx-auto flex max-w-280 flex-col gap-2 px-4 py-6 text-sm text-muted sm:flex-row sm:items-center sm:justify-between">
<p className="flex items-center gap-2">
<LogoMark className="size-5" />
Pravaha · ask your recordings, watch the answer
</p>
<p>
<Link href="/privacy" className="underline-offset-4 hover:text-fg hover:underline">
Privacy
</Link>{" "}
·{" "}
<Link href="/terms" className="underline-offset-4 hover:text-fg hover:underline">
Terms
</Link>{" "}
· Built on <span className="text-fg">Cloudinary</span> · Team Code Blooded ·{" "}
<a href="https://github.com/Monolithic-Dev/Pravaha" className="underline-offset-4 hover:text-fg hover:underline">
GitHub
</a>
</p>
</div>
</footer>
</SiteChrome>
</body>
</html>
);
Expand Down
15 changes: 12 additions & 3 deletions src/components/AskSession.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@ import { AskAnswer } from "@/components/AskAnswer";

// "Ask this session": the same grounded Ask as the home page, scoped to one recording. Follow-up
// questions stay in this session. Suggestions come from the session's Study Pack when it has one.
export function AskSession({ lectureId, suggestions = [] }: { lectureId: string; suggestions?: string[] }) {
// Without `lectureId` it asks the whole library (the /embed/ask box an LMS frames).
export function AskSession({
lectureId,
suggestions = [],
heading = "Ask this session",
}: {
lectureId?: string;
suggestions?: string[];
heading?: string;
}) {
const [draft, setDraft] = useState("");
const [question, setQuestion] = useState<string | null>(null);

Expand All @@ -20,7 +29,7 @@ export function AskSession({ lectureId, suggestions = [] }: { lectureId: string;
return (
<section aria-labelledby="ask-session-heading" className="mt-6">
<h2 id="ask-session-heading" className="text-lg font-semibold">
Ask this session
{heading}
</h2>
<form
onSubmit={(e) => {
Expand All @@ -30,7 +39,7 @@ export function AskSession({ lectureId, suggestions = [] }: { lectureId: string;
className="relative mt-3"
>
<label htmlFor="ask-session" className="sr-only">
Ask a question about this session
{lectureId ? "Ask a question about this session" : "Ask a question about the library"}
</label>
<input
id="ask-session"
Expand Down
Loading
Loading