forked from SamuelZ12/longcut
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.ts
More file actions
221 lines (196 loc) · 7 KB
/
validation.ts
File metadata and controls
221 lines (196 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { z } from 'zod';
import { STRICT_TIMESTAMP_RANGE_REGEX } from '@/lib/timestamp-utils';
// Shared regex
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
// YouTube Video ID validation
const YOUTUBE_ID_REGEX = /^[a-zA-Z0-9_-]{11}$/;
export const youtubeIdSchema = z.string()
.regex(YOUTUBE_ID_REGEX, 'Invalid YouTube video ID format')
.max(11);
// URL validation with YouTube specific checks
export const youtubeUrlSchema = z.string()
.url('Invalid URL format')
.refine((url) => {
try {
const parsed = new URL(url);
return (
parsed.hostname === 'youtube.com' ||
parsed.hostname === 'www.youtube.com' ||
parsed.hostname === 'youtu.be' ||
parsed.hostname === 'm.youtube.com'
);
} catch {
return false;
}
}, 'URL must be a valid YouTube URL');
// Sanitized text fields
export const sanitizedTextSchema = z.string()
.min(1, 'Field cannot be empty')
.max(500, 'Field exceeds maximum length')
.transform((val) => val.trim())
.refine((val) => !/<[^>]*>/g.test(val), 'HTML tags are not allowed');
// Video info validation
export const videoInfoSchema = z.object({
title: z.string().min(1).max(200).transform(val => val.trim()),
author: z.string().max(100).transform(val => val.trim()).optional(),
duration: z.number().int().min(0).max(86400).nullable(), // Max 24 hours, nullable if API doesn't provide it
thumbnail: z.string().url().optional()
});
// Transcript segment validation
export const transcriptSegmentSchema = z.object({
text: z.string().max(5000),
start: z.number().min(0),
duration: z.number().min(0)
});
export const transcriptSchema = z.array(transcriptSegmentSchema)
.min(1, 'Transcript must have at least one segment')
.max(50000, 'Transcript exceeds maximum segments');
// Topic validation
export const topicSchema = z.object({
id: z.string().max(50),
title: z.string().min(1).max(100),
description: z.string().max(500).optional(),
duration: z.number().int().min(0),
segments: z.array(z.object({
start: z.number().min(0),
end: z.number().min(0),
text: z.string().max(10000),
startSegmentIdx: z.number().int().min(0).optional(),
endSegmentIdx: z.number().int().min(0).optional(),
startCharOffset: z.number().int().min(0).optional(),
endCharOffset: z.number().int().min(0).optional(),
hasCompleteSentences: z.boolean().optional(),
confidence: z.number().min(0).max(1).optional()
})).max(100),
keywords: z.array(z.string()).optional(),
quote: z.object({
timestamp: z.string().regex(STRICT_TIMESTAMP_RANGE_REGEX),
text: z.string().max(5000)
}).optional(),
isCitationReel: z.boolean().optional(),
autoPlay: z.boolean().optional()
});
// Model selection validation
export const modelSchema = z.enum(['gemini-2.5-flash', 'gemini-2.0-flash-thinking', 'gemini-2.5-pro']);
export const topicGenerationModeSchema = z.enum(['smart', 'fast']);
// Chat message validation
export const chatMessageSchema = z.object({
id: z.string(),
role: z.enum(['user', 'assistant']),
content: z.string().max(10000),
citations: z.array(z.object({
number: z.number(),
text: z.string().max(5000),
start: z.number().min(0),
end: z.number().min(0),
startSegmentIdx: z.number(),
endSegmentIdx: z.number(),
startCharOffset: z.number(),
endCharOffset: z.number()
})).optional(),
timestamp: z.date()
});
// API Request schemas
export const videoAnalysisRequestSchema = z.object({
videoId: youtubeIdSchema,
videoInfo: videoInfoSchema,
transcript: transcriptSchema,
model: modelSchema.default('gemini-2.5-flash'),
mode: topicGenerationModeSchema.optional(),
forceRegenerate: z.boolean().default(false),
theme: z.string().min(1).max(80).optional(),
includeCandidatePool: z.boolean().optional(),
excludeTopicKeys: z.array(z.string().min(1).max(500)).optional(),
summary: z.any().nullable().optional(),
suggestedQuestions: z.any().nullable().optional()
});
export const generateTopicsRequestSchema = z.object({
transcript: transcriptSchema,
model: modelSchema.optional(),
mode: topicGenerationModeSchema.optional(),
includeCandidatePool: z.boolean().optional(),
excludeTopicKeys: z.array(z.string().min(1).max(500)).optional(),
videoInfo: videoInfoSchema.optional()
});
export const chatRequestSchema = z.object({
message: z.string().min(1).max(5000),
transcript: transcriptSchema,
topics: z.array(topicSchema).optional(),
chatHistory: z.array(z.object({
id: z.string().optional(),
role: z.enum(['user', 'assistant']),
content: z.string(),
citations: z.any().optional(),
timestamp: z.any().optional()
})).max(50).optional()
});
export const toggleFavoriteRequestSchema = z.object({
videoId: youtubeIdSchema,
isFavorite: z.boolean()
});
export const noteSourceSchema = z.enum(['chat', 'takeaways', 'transcript', 'custom']);
export const noteMetadataSchema = z.object({
transcript: z.object({
start: z.number().min(0),
end: z.number().min(0).optional(),
segmentIndex: z.number().int().min(0).optional(),
topicId: z.string().optional()
}).optional(),
chat: z.object({
messageId: z.string().min(1),
role: z.enum(['user', 'assistant']),
timestamp: z.string().optional()
}).optional(),
selectedText: z.string().min(1).max(10000).optional(),
selectionContext: z.string().optional(),
timestampLabel: z.string().optional(),
extra: z.record(z.string(), z.unknown()).optional()
}).passthrough().optional();
export const noteInsertSchema = z.object({
youtubeId: youtubeIdSchema,
videoId: z.string().regex(UUID_REGEX, 'Invalid video record ID').optional(),
source: noteSourceSchema,
sourceId: z.string().optional().nullable(),
text: z.string().min(1).max(5000),
metadata: noteMetadataSchema.nullable()
});
export const noteDeleteSchema = z.object({
noteId: z.string().regex(UUID_REGEX, 'Invalid note ID')
});
export const checkVideoCacheRequestSchema = z.object({
videoId: youtubeIdSchema
});
export const updateVideoAnalysisRequestSchema = z.object({
videoId: youtubeIdSchema,
summary: z.any().optional(),
suggestedQuestions: z.any().optional(),
topics: z.array(z.any()).optional()
});
// Rate limiting validation
export const rateLimitKeySchema = z.string()
.max(100)
.regex(/^[a-zA-Z0-9_-]+$/, 'Invalid rate limit key format');
// Sanitization helpers
export function sanitizeHtml(html: string): string {
// Remove all HTML tags and attributes
return html.replace(/<[^>]*>/g, '');
}
export function sanitizeForDatabase(input: string): string {
// Escape special characters that could be used in SQL injection
return input
.replace(/'/g, "''")
.replace(/;/g, '')
.replace(/--/g, '')
.replace(/\/\*/g, '')
.replace(/\*\//g, '')
.trim();
}
// Validation error formatter
export function formatValidationError(error: z.ZodError<any>): string {
const issues = error.issues || [];
const errors = issues.map((err: any) => {
const field = err.path?.join('.') || 'field';
return `${field}: ${err.message}`;
});
return errors.join(', ');
}