Skip to content
Open
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
18 changes: 16 additions & 2 deletions apps/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,8 @@ struct RecordingsArgs {
enum RecordingsCommands {
/// List '.cap' recordings discovered on disk
List(RecordingsListArgs),
/// Fetch AI summary, title, and chapters from a share link or video ID
Info(RecordingsInfoArgs),
}

#[derive(Args)]
Expand All @@ -396,6 +398,14 @@ struct RecordingsListArgs {
format: OutputFormat,
}

#[derive(Args)]
struct RecordingsInfoArgs {
/// Share URL or video ID (e.g. https://cap.so/s/abc123xyz or abc123xyz)
target: String,
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
format: OutputFormat,
}

#[derive(Args)]
struct DesktopArgs {
#[command(subcommand)]
Expand Down Expand Up @@ -584,7 +594,7 @@ async fn run(cli: Cli) -> Result<(), String> {
None => args.run(json).await,
},
Commands::Screenshot(s) => s.run(json).await,
Commands::Recordings(args) => args.run(json),
Commands::Recordings(args) => args.run(json).await,
Commands::Upload(args) => args.run(json).await,
Commands::Update(args) => {
let format = resolve_format(json, args.format);
Expand Down Expand Up @@ -724,12 +734,16 @@ impl ProjectArgs {
}

impl RecordingsArgs {
fn run(self, json: bool) -> Result<(), String> {
async fn run(self, json: bool) -> Result<(), String> {
match self.command {
RecordingsCommands::List(args) => {
let format = resolve_format(json, args.format);
finish_json(format, recordings::list(args.dir, format))
}
RecordingsCommands::Info(args) => {
let format = resolve_format(json, args.format);
finish_json(format, recordings::info(args.target, format).await)
}
}
}
}
Expand Down
55 changes: 55 additions & 0 deletions apps/cli/src/recordings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,58 @@ pub fn list(dir: Option<PathBuf>, format: OutputFormat) -> Result<(), String> {
}
}
}

pub async fn info(url_or_id: String, format: OutputFormat) -> Result<(), String> {
let video_id = if url_or_id.contains('/') {
url_or_id
.rsplit('/')
.next()
.unwrap_or(&url_or_id)
.to_string()
} else {
url_or_id
Comment on lines +110 to +118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Share URL suffix becomes video ID

When a valid share URL contains a query parameter or trailing slash, rsplit('/') includes the query suffix or returns an empty segment, causing cap recordings info to send the wrong videoId and receive a 400 or 404 instead of metadata.

Knowledge Base Used: Cap CLI (apps/cli)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/cli/src/recordings.rs
Line: 110-118

Comment:
**Share URL suffix becomes video ID**

When a valid share URL contains a query parameter or trailing slash, `rsplit('/')` includes the query suffix or returns an empty segment, causing `cap recordings info` to send the wrong `videoId` and receive a 400 or 404 instead of metadata.

**Knowledge Base Used:** [Cap CLI (`apps/cli`)](https://app.greptile.com/cap/-/custom-context/knowledge-base/capsoftware/cap/-/docs/cli.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

};

let server_url = std::env::var("CAP_SERVER_URL")
.unwrap_or_else(|_| "https://cap.so".to_string());

let endpoint = format!("{}/api/video/metadata?videoId={}", server_url.trim_end_matches('/'), video_id);
let client = reqwest::Client::new();
let response = client
.get(&endpoint)
.send()
.await
.map_err(|e| format!("Failed to fetch video info: {e}"))?;

if !response.status().is_success() {
return Err(format!("Server returned error status: {}", response.status()));
}

let val: serde_json::Value = response
.json()
.await
.map_err(|e| format!("Failed to parse response JSON: {e}"))?;

match format {
OutputFormat::Json => write_json(&val),
OutputFormat::Text => {
if let Some(title) = val.get("title").and_then(|v| v.as_str()) {
println!("Title: {}", title);
}
if let Some(summary) = val.get("summary").and_then(|v| v.as_str()) {
println!("Summary:\n{}", summary);
}
if let Some(chapters) = val.get("chapters").and_then(|v| v.as_array()) {
if !chapters.is_empty() {
println!("\nChapters:");
for chapter in chapters {
let t = chapter.get("title").and_then(|v| v.as_str()).unwrap_or("");
let s = chapter.get("start").and_then(|v| v.as_f64()).unwrap_or(0.0);
println!(" - [{:.1}s] {}", s, t);
}
}
}
Ok(())
}
}
}
4 changes: 3 additions & 1 deletion apps/desktop/src/routes/teleprompter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,11 @@ export default function Teleprompter() {
return;
}

resizeEditor();
const element = scrollElement;
if (!element || !hasScript()) return;
const currentScrollTop = element.scrollTop;
resizeEditor();
element.scrollTop = currentScrollTop;
const maximumScroll = Math.max(
0,
element.scrollHeight - element.clientHeight,
Expand Down
10 changes: 7 additions & 3 deletions apps/mobile/src/recording/TeleprompterOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,13 @@ export function TeleprompterOverlay({
};

const onTextLayout = (event: LayoutChangeEvent) => {
cancelAnimation(progress);
progress.value = 0;
setTextHeight(event.nativeEvent.layout.height);
const newHeight = event.nativeEvent.layout.height;
setTextHeight((prev) => {
if (prev === 0) {
progress.value = 0;
}
return newHeight;
});
};

return (
Expand Down
65 changes: 65 additions & 0 deletions apps/web/__tests__/unit/rate-limit-ids.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { RATE_LIMIT_IDS } from "../../lib/rate-limit";

// Rate limit IDs declared in advance for firewall rules or separate app packages
// that are intentionally not yet wired in apps/web endpoints.
Comment on lines +6 to +7

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Comments duplicate constant purpose

These comments only narrate the self-descriptive UNWIRED_RATE_LIMIT_IDS constant rather than preserving a non-obvious invariant or workaround, adding redundant text that must be maintained.

Suggested change
// Rate limit IDs declared in advance for firewall rules or separate app packages
// that are intentionally not yet wired in apps/web endpoints.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/__tests__/unit/rate-limit-ids.test.ts
Line: 6-7

Comment:
**Comments duplicate constant purpose**

These comments only narrate the self-descriptive `UNWIRED_RATE_LIMIT_IDS` constant rather than preserving a non-obvious invariant or workaround, adding redundant text that must be maintained.

```suggestion

```

**Context Used:** AGENTS.md ([source](https://github.com/capsoftware/cap/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

const UNWIRED_RATE_LIMIT_IDS = new Set([
"AUTH_OTP_VERIFY",
"AUTH_OTP_SEND",
"LOOM_DOWNLOAD",
"MESSENGER_MESSAGE",
"DESKTOP_LOGS",
]);

function getAllTsFiles(dir: string): string[] {
let results: string[] = [];
const list = readdirSync(dir);
for (const file of list) {
const filePath = join(dir, file);
const stat = statSync(filePath);
if (stat && stat.isDirectory()) {
if (file !== "node_modules" && file !== ".next" && file !== "dist") {
results = results.concat(getAllTsFiles(filePath));
}
} else if (file.endsWith(".ts") || file.endsWith(".tsx")) {
if (!filePath.endsWith("lib/rate-limit.ts") && !filePath.endsWith("rate-limit-ids.test.ts")) {
results.push(filePath);
}
}
}
return results;
}

describe("RATE_LIMIT_IDS reference contract", () => {
it("ensures every active declared RATE_LIMIT_ID is referenced outside lib/rate-limit.ts", () => {
const webAppDir = join(process.cwd());
const tsFiles = getAllTsFiles(webAppDir);

let combinedSource = "";
for (const file of tsFiles) {
combinedSource += readFileSync(file, "utf8") + "\n";
}

const unreferencedKeys: string[] = [];

for (const [key, value] of Object.entries(RATE_LIMIT_IDS)) {
if (UNWIRED_RATE_LIMIT_IDS.has(key)) {
continue;
}

const hasKeyRef = combinedSource.includes(`RATE_LIMIT_IDS.${key}`);
const hasValueRef = combinedSource.includes(`"${value}"`) || combinedSource.includes(`'${value}'`);

if (!hasKeyRef && !hasValueRef) {
unreferencedKeys.push(key);
}
}

expect(
unreferencedKeys,
`The following RATE_LIMIT_IDS are declared but never referenced: ${unreferencedKeys.join(", ")}`,
).toEqual([]);
});
});
12 changes: 12 additions & 0 deletions apps/web/app/api/analytics/track/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
createAnonymousViewNotification,
sendFirstViewEmail,
} from "@/lib/Notification";
import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";
import { runPromise } from "@/lib/server";

interface TrackPayload {
Expand Down Expand Up @@ -42,6 +43,17 @@ const decodeUrlEncodedHeaderValue = (value?: string | null) => {
};

export async function POST(request: NextRequest) {
if (
await isRateLimited(RATE_LIMIT_IDS.ANALYTICS_TRACK, {
headers: request.headers,
})
) {
return Response.json(
{ error: "Too many tracking requests. Please try again later." },
{ status: 429 },
);
}

let body: TrackPayload;
try {
body = (await request.json()) as TrackPayload;
Expand Down
13 changes: 13 additions & 0 deletions apps/web/app/api/settings/billing/guest-checkout/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,22 @@ import { serverEnv } from "@cap/env";
import { stripe } from "@cap/utils";
import type { NextRequest } from "next/server";
import { getCheckoutRedirectUrls } from "@/lib/mobile-checkout";

import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";
import { trackServerEvent } from "@/lib/server-analytics";

export async function POST(request: NextRequest) {
if (
await isRateLimited(RATE_LIMIT_IDS.GUEST_CHECKOUT, {
headers: request.headers,
})
) {
return Response.json(
{ error: "Too many checkout attempts. Please try again later." },
{ status: 429 },
);
}

console.log("Starting guest checkout process");
const { priceId, quantity, platform } = await request.json();
const checkoutPlatform = platform === "mobile" ? "mobile" : "web";
Expand Down
33 changes: 33 additions & 0 deletions apps/web/app/api/video/metadata/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,36 @@ export async function PUT(request: NextRequest) {

return Response.json(true, { status: 200 });
}

export async function GET(request: NextRequest) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Metadata route bypasses API architecture

This new operation uses an ad-hoc Next.js handler and direct database query instead of the required HttpApi builder and backend service pattern, bypassing shared policy, typed errors, and request-context wiring.

Context Used: AGENTS.md (source)

Knowledge Base Used: Web App (apps/web)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/video/metadata/route.ts
Line: 43

Comment:
**Metadata route bypasses API architecture**

This new operation uses an ad-hoc Next.js handler and direct database query instead of the required `HttpApi` builder and backend service pattern, bypassing shared policy, typed errors, and request-context wiring.

**Context Used:** AGENTS.md ([source](https://github.com/capsoftware/cap/blob/main/AGENTS.md))

**Knowledge Base Used:** [Web App (apps/web)](https://app.greptile.com/cap/-/custom-context/knowledge-base/capsoftware/cap/-/docs/web-app.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

const { searchParams } = new URL(request.url);
const videoId = searchParams.get("videoId");

if (!videoId) {
return Response.json({ error: "Missing videoId parameter" }, { status: 400 });
}

const query = await db().select().from(videos).where(eq(videos.id, videoId));

if (query.length === 0 || !query[0]) {
return Response.json({ error: "Video not found" }, { status: 404 });
}

const video = query[0];
const user = await getCurrentUser();

if (!video.public && video.ownerId !== user?.id) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
Comment on lines +60 to +62

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 security Password policy bypassed for metadata

When a public video is password-protected, this check authorizes unauthenticated and non-owner requests solely because video.public is true, exposing its title, AI summary, chapters, and generation status without the required password.

How this was verified: The video schema permits public videos with passwords, while the established public-view policy verifies password candidates before granting access.

Knowledge Base Used: Web App (apps/web)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/video/metadata/route.ts
Line: 60-62

Comment:
**Password policy bypassed for metadata**

When a public video is password-protected, this check authorizes unauthenticated and non-owner requests solely because `video.public` is true, exposing its title, AI summary, chapters, and generation status without the required password.

**How this was verified:** The video schema permits public videos with passwords, while the established public-view policy verifies password candidates before granting access.

**Knowledge Base Used:** [Web App (apps/web)](https://app.greptile.com/cap/-/custom-context/knowledge-base/capsoftware/cap/-/docs/web-app.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


const meta = (video.metadata as Record<string, any>) ?? {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Explicit any breaks lint contract

The new Record<string, any> cast violates the repository's enabled noExplicitAny rule, causing the changed route to fail the required Biome check; use a defined metadata type or unknown with narrowing.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/app/api/video/metadata/route.ts
Line: 64

Comment:
**Explicit any breaks lint contract**

The new `Record<string, any>` cast violates the repository's enabled `noExplicitAny` rule, causing the changed route to fail the required Biome check; use a defined metadata type or `unknown` with narrowing.

**Context Used:** AGENTS.md ([source](https://github.com/capsoftware/cap/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


return Response.json({
videoId: video.id,
title: video.title || meta.aiTitle || null,
aiTitle: meta.aiTitle || null,
summary: meta.summary || null,
chapters: meta.chapters || [],
aiGenerationStatus: meta.aiGenerationStatus || "SKIPPED",
});
}
3 changes: 2 additions & 1 deletion apps/web/lib/messenger/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,8 +588,9 @@ const callOpenAi = async ({
history,
supportEmailTool,
createCompletion: async ({ messages, tools, maxTokens }) => {
const baseUrl = (serverEnv().OPENAI_BASE_URL || "https://api.openai.com/v1").replace(/\/+$/, "");
const response = await fetch(
"https://api.openai.com/v1/chat/completions",
`${baseUrl}/chat/completions`,
{
method: "POST",
headers: {
Expand Down
3 changes: 2 additions & 1 deletion apps/web/workflows/generate-ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,8 @@ async function callAiApi(
}

async function callOpenAi(prompt: string): Promise<string> {
const aiRes = await fetch("https://api.openai.com/v1/chat/completions", {
const baseUrl = (serverEnv().OPENAI_BASE_URL || "https://api.openai.com/v1").replace(/\/+$/, "");
const aiRes = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
4 changes: 4 additions & 0 deletions packages/env/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ function createServerEnv() {
ASSEMBLY_API_KEY: z.string().optional().describe("Audio transcription"),
ANTHROPIC_API_KEY: z.string().optional().describe("AI chat"),
OPENAI_API_KEY: z.string().optional().describe("AI summaries"),
OPENAI_BASE_URL: z
.string()
.optional()
.describe("Custom base URL for OpenAI-compatible LLM endpoints"),
GROQ_API_KEY: z.string().optional().describe("AI summaries"),
REPLICATE_API_TOKEN: z
.string()
Expand Down