mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-10-31 18:19:43 +00:00
Add match archiving, chat enhancements, and daily limits
- Match archives with swipe-to-archive and unread filtering - Chat settings sheet and full-screen media modals - Match notification modal for new matches - Admin AI settings with model/provider configuration - Daily response limit feature with recommended questions - New test coverage for stores, hooks, and components - Claude Code agent and command configurations Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
595d6bd394
commit
b0f1700e40
57 files changed
+8359
-1661
No files matched your search
@@ -9,6 +9,174 @@ const corsHeaders = {
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
};
|
||||
|
||||
const DEFAULT_WHITELIST = [
|
||||
"ok",
|
||||
"okay",
|
||||
"yes",
|
||||
"no",
|
||||
"maybe",
|
||||
"thanks",
|
||||
"thank you",
|
||||
"lol",
|
||||
"lmao",
|
||||
"good night",
|
||||
"goodnight",
|
||||
"good morning",
|
||||
"love you",
|
||||
];
|
||||
|
||||
const DEFAULT_KEYWORD_TRIGGERS = [
|
||||
"suicide",
|
||||
"kill myself",
|
||||
"self harm",
|
||||
"kill you",
|
||||
"hurt you",
|
||||
"rape",
|
||||
"porn",
|
||||
"nude",
|
||||
"explicit",
|
||||
"stab",
|
||||
"shoot",
|
||||
];
|
||||
|
||||
function parseBoolean(value, defaultValue = false) {
|
||||
if (value === null || value === undefined) return defaultValue;
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "number") return value !== 0;
|
||||
if (typeof value === "string") {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["true", "1", "yes", "y", "on"].includes(normalized)) return true;
|
||||
if (["false", "0", "no", "n", "off"].includes(normalized)) return false;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
function parseNumber(value, defaultValue) {
|
||||
if (value === null || value === undefined) return defaultValue;
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
const parsed = Number(String(value).trim());
|
||||
return Number.isFinite(parsed) ? parsed : defaultValue;
|
||||
}
|
||||
|
||||
function parseStringArray(value) {
|
||||
if (!value) return [];
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.filter((item) => typeof item === "string")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return [];
|
||||
if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed
|
||||
.filter((item) => typeof item === "string")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
} catch {
|
||||
// Fall through to delimiter parsing
|
||||
}
|
||||
}
|
||||
return trimmed
|
||||
.split(/[\n,]+/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function normalizeList(values) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
values
|
||||
.map((value) => value.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function getHeuristicConfig(config) {
|
||||
const enabled = parseBoolean(config?.heuristics_enabled, false);
|
||||
const minTextLength = parseNumber(config?.heuristic_min_text_length, 12);
|
||||
const whitelistMaxLength = parseNumber(config?.heuristic_whitelist_max_length, 30);
|
||||
const skipIfNoAlnum = parseBoolean(config?.heuristic_skip_if_no_alnum, true);
|
||||
const skipMediaWithoutText = parseBoolean(config?.heuristic_skip_media_without_text, false);
|
||||
const recordReason = parseBoolean(config?.heuristic_record_reason, false);
|
||||
const useDefaultWhitelist = parseBoolean(config?.heuristic_use_default_whitelist, true);
|
||||
const useDefaultKeywords = parseBoolean(config?.heuristic_use_default_keywords, true);
|
||||
|
||||
const whitelist = parseStringArray(config?.heuristic_whitelist);
|
||||
const keywordTriggers = parseStringArray(config?.heuristic_keyword_triggers);
|
||||
|
||||
const normalizedWhitelist = normalizeList(
|
||||
useDefaultWhitelist ? DEFAULT_WHITELIST.concat(whitelist) : whitelist
|
||||
);
|
||||
const normalizedKeywordTriggers = normalizeList(
|
||||
useDefaultKeywords ? DEFAULT_KEYWORD_TRIGGERS.concat(keywordTriggers) : keywordTriggers
|
||||
);
|
||||
|
||||
return {
|
||||
enabled,
|
||||
minTextLength,
|
||||
whitelistMaxLength,
|
||||
skipIfNoAlnum,
|
||||
skipMediaWithoutText,
|
||||
recordReason,
|
||||
whitelist: normalizedWhitelist,
|
||||
keywordTriggers: normalizedKeywordTriggers,
|
||||
};
|
||||
}
|
||||
|
||||
function evaluateHeuristics(text, hasMedia, config) {
|
||||
if (!config.enabled) {
|
||||
return { shouldCallAi: true, reason: "disabled" };
|
||||
}
|
||||
|
||||
const normalized = (text || "").trim();
|
||||
const lower = normalized.toLowerCase();
|
||||
const hasText = normalized.length > 0;
|
||||
const hasAlnum = /[a-z0-9]/i.test(normalized);
|
||||
|
||||
if (config.keywordTriggers.length > 0) {
|
||||
const keywordHit = config.keywordTriggers.some((keyword) => lower.includes(keyword));
|
||||
if (keywordHit) {
|
||||
return { shouldCallAi: true, reason: "keyword_trigger" };
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasMedia && !hasText) {
|
||||
return { shouldCallAi: false, reason: "no_content" };
|
||||
}
|
||||
|
||||
if (!hasMedia) {
|
||||
if (config.skipIfNoAlnum && !hasAlnum) {
|
||||
return { shouldCallAi: false, reason: "low_signal" };
|
||||
}
|
||||
|
||||
if (normalized.length <= config.whitelistMaxLength) {
|
||||
const isWhitelisted = config.whitelist.includes(lower);
|
||||
if (isWhitelisted) {
|
||||
return { shouldCallAi: false, reason: "whitelist" };
|
||||
}
|
||||
}
|
||||
|
||||
if (normalized.length < config.minTextLength) {
|
||||
return { shouldCallAi: false, reason: "short_text" };
|
||||
}
|
||||
}
|
||||
|
||||
if (hasMedia && config.skipMediaWithoutText && !hasText) {
|
||||
return { shouldCallAi: false, reason: "media_without_text" };
|
||||
}
|
||||
|
||||
return { shouldCallAi: true, reason: "default" };
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: corsHeaders });
|
||||
@@ -42,6 +210,8 @@ Deno.serve(async (req) => {
|
||||
return new Response(JSON.stringify({ message: "Classifier disabled" }), { status: 200, headers: corsHeaders });
|
||||
}
|
||||
|
||||
const heuristicConfig = getHeuristicConfig(config);
|
||||
|
||||
const apiKey = config.openrouter_api_key || Deno.env.get("OPENROUTER_API_KEY");
|
||||
if (!apiKey) {
|
||||
console.error("OpenRouter API Key missing");
|
||||
@@ -64,24 +234,31 @@ Deno.serve(async (req) => {
|
||||
let decryptedText = message.content;
|
||||
let mediaBase64: string | null = null;
|
||||
let mediaMimeType: string | null = null;
|
||||
const hasMedia = !!message.media_path && message.media_type === "image";
|
||||
const keysMetadata = message.keys_metadata as KeysMetadata | null;
|
||||
const encryptionIv = message.encryption_iv as string | null;
|
||||
let aesKey: CryptoKey | null = null;
|
||||
|
||||
if (version === 2) {
|
||||
const keysMetadata = message.keys_metadata as KeysMetadata;
|
||||
const encryptionIv = message.encryption_iv;
|
||||
|
||||
if (version === 2 && (message.encrypted_content || hasMedia)) {
|
||||
if (!keysMetadata || !encryptionIv) {
|
||||
return new Response(JSON.stringify({ error: "Missing encryption metadata" }), { status: 400, headers: corsHeaders });
|
||||
}
|
||||
}
|
||||
|
||||
const getAesKey = async () => {
|
||||
if (aesKey) return aesKey;
|
||||
if (!keysMetadata || !encryptionIv) {
|
||||
throw new Error("Missing encryption metadata");
|
||||
}
|
||||
const adminPrivateKeyJwkStr = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
|
||||
if (!adminPrivateKeyJwkStr) {
|
||||
throw new Error("ADMIN_PRIVATE_KEY_JWK not set");
|
||||
}
|
||||
|
||||
|
||||
const adminPrivateKey = JSON.parse(adminPrivateKeyJwkStr);
|
||||
const rawAesKey = await unwrapWithAdminKey(keysMetadata.admin_wrapped_key, adminPrivateKey);
|
||||
|
||||
const aesKey = await crypto.subtle.importKey(
|
||||
|
||||
aesKey = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
rawAesKey,
|
||||
{ name: "AES-GCM" },
|
||||
@@ -89,45 +266,60 @@ Deno.serve(async (req) => {
|
||||
["decrypt"]
|
||||
);
|
||||
|
||||
// Decrypt Text
|
||||
if (message.encrypted_content) {
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
|
||||
aesKey,
|
||||
base64ToUint8Array(message.encrypted_content)
|
||||
);
|
||||
decryptedText = new TextDecoder().decode(plaintext);
|
||||
}
|
||||
|
||||
// Decrypt Media (Image only for now)
|
||||
if (message.media_path && message.media_type === "image") {
|
||||
return aesKey;
|
||||
};
|
||||
|
||||
if (version === 2 && message.encrypted_content) {
|
||||
const key = await getAesKey();
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv as string) },
|
||||
key,
|
||||
base64ToUint8Array(message.encrypted_content)
|
||||
);
|
||||
decryptedText = new TextDecoder().decode(plaintext);
|
||||
}
|
||||
|
||||
const heuristicDecision = evaluateHeuristics(decryptedText, hasMedia, heuristicConfig);
|
||||
if (heuristicConfig.enabled && !heuristicDecision.shouldCallAi) {
|
||||
console.log(`Heuristic skip for message ${messageId}: ${heuristicDecision.reason}`);
|
||||
await updateStatus(
|
||||
supabaseAdmin,
|
||||
messageId,
|
||||
"safe",
|
||||
heuristicConfig.recordReason ? heuristicDecision.reason : null,
|
||||
"Neutral"
|
||||
);
|
||||
return new Response(JSON.stringify({ status: "safe" }), { headers: corsHeaders });
|
||||
}
|
||||
|
||||
if (hasMedia) {
|
||||
if (version === 2) {
|
||||
const key = await getAesKey();
|
||||
const { data: mediaBlob, error: downloadError } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
|
||||
if (!downloadError && mediaBlob) {
|
||||
const encryptedBytes = await mediaBlob.arrayBuffer();
|
||||
const decryptedBytes = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
|
||||
aesKey,
|
||||
encryptedBytes
|
||||
);
|
||||
mediaBase64 = arrayBufferToBase64(decryptedBytes);
|
||||
mediaMimeType = "image/jpeg"; // Default or infer?
|
||||
const encryptedBytes = await mediaBlob.arrayBuffer();
|
||||
const decryptedBytes = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv as string) },
|
||||
key,
|
||||
encryptedBytes
|
||||
);
|
||||
mediaBase64 = arrayBufferToBase64(decryptedBytes);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
} else {
|
||||
const { data: mediaBlob } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
|
||||
if (mediaBlob) {
|
||||
const buffer = await mediaBlob.arrayBuffer();
|
||||
mediaBase64 = arrayBufferToBase64(buffer);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Version 1 (Plaintext)
|
||||
if (message.media_path && message.media_type === "image") {
|
||||
const { data: mediaBlob } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
if (mediaBlob) {
|
||||
const buffer = await mediaBlob.arrayBuffer();
|
||||
mediaBase64 = arrayBufferToBase64(buffer);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Construct LLM Payload
|
||||
|
||||
@@ -70,27 +70,88 @@ Deno.serve(async (req) => {
|
||||
.eq("id", user.id)
|
||||
.single();
|
||||
|
||||
if (profileError || !profile?.couple_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "User is not in a couple" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Save or update response
|
||||
const { data: response, error: responseError } = await supabase
|
||||
.from("responses")
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
question_id,
|
||||
couple_id: profile.couple_id,
|
||||
answer,
|
||||
},
|
||||
{ onConflict: "user_id,question_id" }
|
||||
)
|
||||
.select()
|
||||
.single();
|
||||
if (profileError || !profile?.couple_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "User is not in a couple" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if this is a new response or an edit (edits bypass daily limit)
|
||||
const { data: existingResponse } = await supabase
|
||||
.from("responses")
|
||||
.select("id")
|
||||
.eq("user_id", user.id)
|
||||
.eq("question_id", question_id)
|
||||
.maybeSingle();
|
||||
|
||||
const isNewResponse = !existingResponse;
|
||||
|
||||
// Enforce daily response limit for new responses only
|
||||
if (isNewResponse) {
|
||||
// Check if user has premium access
|
||||
const { data: hasPremiumData } = await supabase.rpc("has_premium_access", {
|
||||
check_user_id: user.id,
|
||||
});
|
||||
|
||||
const hasPremium = hasPremiumData === true;
|
||||
|
||||
// If non-premium, check daily limit
|
||||
if (!hasPremium) {
|
||||
// Get daily limit from app_config
|
||||
const { data: configData } = await supabase
|
||||
.from("app_config")
|
||||
.select("daily_response_limit")
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
|
||||
const dailyLimit = configData?.daily_response_limit || 0;
|
||||
|
||||
// If daily limit is enabled (> 0), check if user has reached it
|
||||
if (dailyLimit > 0) {
|
||||
// Calculate UTC day boundaries
|
||||
const now = new Date();
|
||||
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||
const tomorrowStart = new Date(todayStart);
|
||||
tomorrowStart.setUTCDate(tomorrowStart.getUTCDate() + 1);
|
||||
|
||||
// Count responses created today (UTC)
|
||||
const { count: dailyCount } = await supabase
|
||||
.from("responses")
|
||||
.select("*", { count: "exact", head: true })
|
||||
.eq("user_id", user.id)
|
||||
.gte("created_at", todayStart.toISOString())
|
||||
.lt("created_at", tomorrowStart.toISOString());
|
||||
|
||||
// If over limit, reject
|
||||
if ((dailyCount || 0) >= dailyLimit) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "Daily response limit reached",
|
||||
daily_limit: dailyLimit,
|
||||
reset_at: tomorrowStart.toISOString(),
|
||||
}),
|
||||
{ status: 429, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save or update response
|
||||
const { data: response, error: responseError } = await supabase
|
||||
.from("responses")
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
question_id,
|
||||
couple_id: profile.couple_id,
|
||||
answer,
|
||||
},
|
||||
{ onConflict: "user_id,question_id" }
|
||||
)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (responseError) {
|
||||
return new Response(
|
||||
|
||||
Reference in new issue
Block a user