An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: implement PostgreSQL Row-Level Security (RLS)
Yoshiki Miura2ad28cfe4e87
diff --git a/drizzle/0006_brainy_wrecking_crew.sql b/drizzle/0006_brainy_wrecking_crew.sqlnew file mode 100644index 00000000..5f4a6364--- /dev/null+++ b/drizzle/0006_brainy_wrecking_crew.sql@@ -0,0 +1,21 @@+CREATE POLICY "users_manage_own_chats" ON "chats" AS PERMISSIVE FOR ALL TO public USING (user_id = current_setting('app.current_user_id', true)) WITH CHECK (user_id = current_setting('app.current_user_id', true));--> statement-breakpoint+CREATE POLICY "users_manage_chat_messages" ON "messages" AS PERMISSIVE FOR ALL TO public USING (EXISTS (+ SELECT 1 FROM "chats"+ WHERE "chats".id = chat_id+ AND "chats".user_id = current_setting('app.current_user_id', true)+ )) WITH CHECK (EXISTS (+ SELECT 1 FROM "chats"+ WHERE "chats".id = chat_id+ AND "chats".user_id = current_setting('app.current_user_id', true)+ ));--> statement-breakpoint+CREATE POLICY "users_manage_message_parts" ON "parts" AS PERMISSIVE FOR ALL TO public USING (EXISTS (+ SELECT 1 FROM "messages"+ INNER JOIN "chats" ON "chats".id = "messages".chat_id+ WHERE "messages".id = message_id+ AND "chats".user_id = current_setting('app.current_user_id', true)+ )) WITH CHECK (EXISTS (+ SELECT 1 FROM "messages"+ INNER JOIN "chats" ON "chats".id = "messages".chat_id+ WHERE "messages".id = message_id+ AND "chats".user_id = current_setting('app.current_user_id', true)+ ));\ No newline at end of filediff --git a/drizzle/0007_illegal_mephistopheles.sql b/drizzle/0007_illegal_mephistopheles.sqlnew file mode 100644index 00000000..2ed55913--- /dev/null+++ b/drizzle/0007_illegal_mephistopheles.sql@@ -0,0 +1,12 @@+CREATE POLICY "public_chats_readable" ON "chats" AS PERMISSIVE FOR SELECT TO public USING (visibility = 'public');--> statement-breakpoint+CREATE POLICY "public_chat_messages_readable" ON "messages" AS PERMISSIVE FOR SELECT TO public USING (EXISTS (+ SELECT 1 FROM "chats"+ WHERE "chats".id = chat_id+ AND "chats".visibility = 'public'+ ));--> statement-breakpoint+CREATE POLICY "public_chat_parts_readable" ON "parts" AS PERMISSIVE FOR SELECT TO public USING (EXISTS (+ SELECT 1 FROM "messages"+ INNER JOIN "chats" ON "chats".id = "messages".chat_id+ WHERE "messages".id = message_id+ AND "chats".visibility = 'public'+ ));\ No newline at end of filediff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.jsonnew file mode 100644index 00000000..09b5a87f--- /dev/null+++ b/drizzle/meta/0006_snapshot.json@@ -0,0 +1,657 @@+{+ "id": "60e18ccb-ad03-4315-bee3-286b827d26fe",+ "prevId": "c2240142-0d69-482e-b6e0-a9561c421aa2",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.chats": {+ "name": "chats",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "visibility": {+ "name": "visibility",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ }+ },+ "indexes": {+ "chats_user_id_idx": {+ "name": "chats_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_user_id_created_at_idx": {+ "name": "chats_user_id_created_at_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_created_at_idx": {+ "name": "chats_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_own_chats": {+ "name": "users_manage_own_chats",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "user_id = current_setting('app.current_user_id', true)",+ "withCheck": "user_id = current_setting('app.current_user_id', true)"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.feedback": {+ "name": "feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "sentiment": {+ "name": "sentiment",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feedback_user_id_idx": {+ "name": "feedback_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_created_at_idx": {+ "name": "feedback_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "anyone_can_insert_feedback": {+ "name": "anyone_can_insert_feedback",+ "as": "PERMISSIVE",+ "for": "INSERT",+ "to": ["public"],+ "withCheck": "true"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.messages": {+ "name": "messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "messages_chat_id_idx": {+ "name": "messages_chat_id_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_chat_id_created_at_idx": {+ "name": "messages_chat_id_created_at_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "messages_chat_id_chats_id_fk": {+ "name": "messages_chat_id_chats_id_fk",+ "tableFrom": "messages",+ "tableTo": "chats",+ "columnsFrom": ["chat_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_chat_messages": {+ "name": "users_manage_chat_messages",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.parts": {+ "name": "parts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "text_text": {+ "name": "text_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reasoning_text": {+ "name": "reasoning_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "file_media_type": {+ "name": "file_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "file_filename": {+ "name": "file_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "file_url": {+ "name": "file_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_source_id": {+ "name": "source_url_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_url": {+ "name": "source_url_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_title": {+ "name": "source_url_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_source_id": {+ "name": "source_document_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_media_type": {+ "name": "source_document_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_title": {+ "name": "source_document_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_filename": {+ "name": "source_document_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_url": {+ "name": "source_document_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_snippet": {+ "name": "source_document_snippet",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_tool_call_id": {+ "name": "tool_tool_call_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_state": {+ "name": "tool_state",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_error_text": {+ "name": "tool_error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_input": {+ "name": "tool_search_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_output": {+ "name": "tool_search_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_input": {+ "name": "tool_fetch_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_output": {+ "name": "tool_fetch_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_input": {+ "name": "tool_question_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_output": {+ "name": "tool_question_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_input": {+ "name": "tool_todoWrite_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_output": {+ "name": "tool_todoWrite_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_input": {+ "name": "tool_todoRead_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_output": {+ "name": "tool_todoRead_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_input": {+ "name": "tool_dynamic_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_output": {+ "name": "tool_dynamic_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_name": {+ "name": "tool_dynamic_name",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_type": {+ "name": "tool_dynamic_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_prefix": {+ "name": "data_prefix",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_content": {+ "name": "data_content",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "data_id": {+ "name": "data_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "provider_metadata": {+ "name": "provider_metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "parts_message_id_idx": {+ "name": "parts_message_id_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "parts_message_id_order_idx": {+ "name": "parts_message_id_order_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "order",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "parts_message_id_messages_id_fk": {+ "name": "parts_message_id_messages_id_fk",+ "tableFrom": "parts",+ "tableTo": "messages",+ "columnsFrom": ["message_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_message_parts": {+ "name": "users_manage_message_parts",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ }+ },+ "checkConstraints": {+ "text_text_required": {+ "name": "text_text_required",+ "value": "(type != 'text' OR text_text IS NOT NULL)"+ },+ "reasoning_text_required": {+ "name": "reasoning_text_required",+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"+ },+ "file_fields_required": {+ "name": "file_fields_required",+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))"+ },+ "tool_state_valid": {+ "name": "tool_state_valid",+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"+ },+ "tool_fields_required": {+ "name": "tool_fields_required",+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"+ }+ },+ "isRLSEnabled": true+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/drizzle/meta/0007_snapshot.json b/drizzle/meta/0007_snapshot.jsonnew file mode 100644index 00000000..a07f4599--- /dev/null+++ b/drizzle/meta/0007_snapshot.json@@ -0,0 +1,678 @@+{+ "id": "a1b15544-fb28-4c05-82c2-8e81ea3d5689",+ "prevId": "60e18ccb-ad03-4315-bee3-286b827d26fe",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.chats": {+ "name": "chats",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true+ },+ "visibility": {+ "name": "visibility",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true,+ "default": "'private'"+ }+ },+ "indexes": {+ "chats_user_id_idx": {+ "name": "chats_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_user_id_created_at_idx": {+ "name": "chats_user_id_created_at_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chats_created_at_idx": {+ "name": "chats_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_own_chats": {+ "name": "users_manage_own_chats",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "user_id = current_setting('app.current_user_id', true)",+ "withCheck": "user_id = current_setting('app.current_user_id', true)"+ },+ "public_chats_readable": {+ "name": "public_chats_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "visibility = 'public'"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.feedback": {+ "name": "feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false+ },+ "sentiment": {+ "name": "sentiment",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feedback_user_id_idx": {+ "name": "feedback_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_created_at_idx": {+ "name": "feedback_created_at_idx",+ "columns": [+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "anyone_can_insert_feedback": {+ "name": "anyone_can_insert_feedback",+ "as": "PERMISSIVE",+ "for": "INSERT",+ "to": ["public"],+ "withCheck": "true"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.messages": {+ "name": "messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "messages_chat_id_idx": {+ "name": "messages_chat_id_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "messages_chat_id_created_at_idx": {+ "name": "messages_chat_id_created_at_idx",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "messages_chat_id_chats_id_fk": {+ "name": "messages_chat_id_chats_id_fk",+ "tableFrom": "messages",+ "tableTo": "chats",+ "columnsFrom": ["chat_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_chat_messages": {+ "name": "users_manage_chat_messages",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ },+ "public_chat_messages_readable": {+ "name": "public_chat_messages_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"+ }+ },+ "checkConstraints": {},+ "isRLSEnabled": true+ },+ "public.parts": {+ "name": "parts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(191)",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "varchar(191)",+ "primaryKey": false,+ "notNull": true+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": true+ },+ "text_text": {+ "name": "text_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reasoning_text": {+ "name": "reasoning_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "file_media_type": {+ "name": "file_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "file_filename": {+ "name": "file_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "file_url": {+ "name": "file_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_source_id": {+ "name": "source_url_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_url": {+ "name": "source_url_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_url_title": {+ "name": "source_url_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_source_id": {+ "name": "source_document_source_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_media_type": {+ "name": "source_document_media_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_title": {+ "name": "source_document_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_filename": {+ "name": "source_document_filename",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_url": {+ "name": "source_document_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_snippet": {+ "name": "source_document_snippet",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_tool_call_id": {+ "name": "tool_tool_call_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_state": {+ "name": "tool_state",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_error_text": {+ "name": "tool_error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_input": {+ "name": "tool_search_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_search_output": {+ "name": "tool_search_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_input": {+ "name": "tool_fetch_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_fetch_output": {+ "name": "tool_fetch_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_input": {+ "name": "tool_question_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_question_output": {+ "name": "tool_question_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_input": {+ "name": "tool_todoWrite_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoWrite_output": {+ "name": "tool_todoWrite_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_input": {+ "name": "tool_todoRead_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_todoRead_output": {+ "name": "tool_todoRead_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_input": {+ "name": "tool_dynamic_input",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_output": {+ "name": "tool_dynamic_output",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_name": {+ "name": "tool_dynamic_name",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "tool_dynamic_type": {+ "name": "tool_dynamic_type",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_prefix": {+ "name": "data_prefix",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "data_content": {+ "name": "data_content",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "data_id": {+ "name": "data_id",+ "type": "varchar(256)",+ "primaryKey": false,+ "notNull": false+ },+ "provider_metadata": {+ "name": "provider_metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "parts_message_id_idx": {+ "name": "parts_message_id_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "parts_message_id_order_idx": {+ "name": "parts_message_id_order_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "order",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "parts_message_id_messages_id_fk": {+ "name": "parts_message_id_messages_id_fk",+ "tableFrom": "parts",+ "tableTo": "messages",+ "columnsFrom": ["message_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {+ "users_manage_message_parts": {+ "name": "users_manage_message_parts",+ "as": "PERMISSIVE",+ "for": "ALL",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"+ },+ "public_chat_parts_readable": {+ "name": "public_chat_parts_readable",+ "as": "PERMISSIVE",+ "for": "SELECT",+ "to": ["public"],+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"+ }+ },+ "checkConstraints": {+ "text_text_required": {+ "name": "text_text_required",+ "value": "(type != 'text' OR text_text IS NOT NULL)"+ },+ "reasoning_text_required": {+ "name": "reasoning_text_required",+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"+ },+ "file_fields_required": {+ "name": "file_fields_required",+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))"+ },+ "tool_state_valid": {+ "name": "tool_state_valid",+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"+ },+ "tool_fields_required": {+ "name": "tool_fields_required",+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"+ }+ },+ "isRLSEnabled": true+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 18821628..b647fa30 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -43,6 +43,20 @@"when": 1755654069349,"tag": "0005_awesome_riptide","breakpoints": true+ },+ {+ "idx": 6,+ "version": "7",+ "when": 1755686097019,+ "tag": "0006_brainy_wrecking_crew",+ "breakpoints": true+ },+ {+ "idx": 7,+ "version": "7",+ "when": 1755737289769,+ "tag": "0007_illegal_mephistopheles",+ "breakpoints": true}]}diff --git a/lib/actions/chat.ts b/lib/actions/chat.tsindex 444e5bf7..7b79a0f6 100644--- a/lib/actions/chat.ts+++ b/lib/actions/chat.ts@@ -166,11 +166,14 @@ export async function upsertMessage(// Skip access check - userId is required for audit/logging but not for authorization// Caller MUST ensure authorization before calling this functionconst messageId = message.id || generateId()- const dbMessage = await dbActions.upsertMessage({- ...message,- id: messageId,- chatId- })+ const dbMessage = await dbActions.upsertMessage(+ {+ ...message,+ id: messageId,+ chatId+ },+ userId+ )// Revalidate cacherevalidateTag(`chat-${chatId}`)diff --git a/lib/db/actions.ts b/lib/db/actions.tsindex 23bb3554..d1910619 100644--- a/lib/db/actions.ts+++ b/lib/db/actions.ts@@ -14,6 +14,7 @@ import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'import type { Chat, Message } from './schema'import { chats, generateId, messages, parts } from './schema'+import { withOptionalRLS, withRLS } from './with-rls'import { db } from '.'/**@@ -30,17 +31,19 @@ export async function createChat({userId: stringvisibility?: 'public' | 'private'}): Promise<Chat> {- const [chat] = await db- .insert(chats)- .values({- id,- title,- userId,- visibility- })- .returning()+ return withRLS(userId, async tx => {+ const [chat] = await tx+ .insert(chats)+ .values({+ id,+ title,+ userId,+ visibility+ })+ .returning()- return chat+ return chat+ })}/**@@ -50,37 +53,49 @@ export async function getChat(chatId: string,userId?: string): Promise<Chat | null> {- const [chat] = await db- .select()- .from(chats)- .where(eq(chats.id, chatId))- .limit(1)+ // For public chats or when no userId, use regular db connection+ // For private chats with userId, use RLS+ return withOptionalRLS(userId || null, async tx => {+ const [chat] = await tx+ .select()+ .from(chats)+ .where(eq(chats.id, chatId))+ .limit(1)- if (!chat) {- return null- }+ if (!chat) {+ return null+ }- // Permission check- if (chat.visibility === 'public') {- return chat- }+ // Additional permission check for backward compatibility+ if (chat.visibility === 'public') {+ return chat+ }- if (chat.visibility === 'private' && userId && chat.userId === userId) {- return chat- }+ if (chat.visibility === 'private' && userId && chat.userId === userId) {+ return chat+ }- return null+ return null+ })}/*** Upsert a message with its parts+ * Note: This function should be called with appropriate userId context*/export async function upsertMessage(- message: PersistableUIMessage & { chatId: string }+ message: PersistableUIMessage & { chatId: string },+ userId?: string): Promise<Message> {const count = incrementDbOperationCount()perfLog(`DB - upsertMessage called - count: ${count}`)- const result = await db.transaction(async tx => {++ // Use RLS if userId is provided, otherwise use regular db+ const executeFn = userId+ ? (callback: (tx: any) => Promise<Message>) => withRLS(userId, callback)+ : (callback: (tx: any) => Promise<Message>) => db.transaction(callback)++ const result = await executeFn(async tx => {// 1. Insert or update the messageconst messageData = mapUIMessageToDBMessage(message)const [dbMessage] = await tx@@ -111,21 +126,27 @@ export async function upsertMessage(/*** Load chat messages with parts+ * Note: Caller should verify chat access permissions before calling this*/-export async function loadChat(chatId: string): Promise<UIMessage[]> {- // Use Drizzle's query API with relations- const result = await db.query.messages.findMany({- where: eq(messages.chatId, chatId),- with: {- parts: {- orderBy: [asc(parts.order)]- }- },- orderBy: [asc(messages.createdAt)]- })+export async function loadChat(+ chatId: string,+ userId?: string+): Promise<UIMessage[]> {+ return withOptionalRLS(userId || null, async tx => {+ // Use Drizzle's query API with relations+ const result = await tx.query.messages.findMany({+ where: eq(messages.chatId, chatId),+ with: {+ parts: {+ orderBy: [asc(parts.order)]+ }+ },+ orderBy: [asc(messages.createdAt)]+ })- // Convert to UI format- return result.map(msg => buildUIMessageFromDB(msg, msg.parts))+ // Convert to UI format+ return result.map(msg => buildUIMessageFromDB(msg, msg.parts))+ })}/**@@ -137,37 +158,38 @@ export async function loadChatWithMessages(): Promise<(Chat & { messages: UIMessage[] }) | null> {const count = incrementDbOperationCount()perfLog(`DB - loadChatWithMessages called - count: ${count}`)- // Don't check cache yet - need to verify permissions first- // Get chat and messages in parallel- const [chatResult, messagesResult] = await Promise.all([- db.select().from(chats).where(eq(chats.id, chatId)).limit(1),- db.query.messages.findMany({- where: eq(messages.chatId, chatId),- with: {- parts: {- orderBy: [asc(parts.order)]- }- },- orderBy: [asc(messages.createdAt)]- })- ])+ return withOptionalRLS(userId || null, async tx => {+ // Get chat and messages in parallel+ const [chatResult, messagesResult] = await Promise.all([+ tx.select().from(chats).where(eq(chats.id, chatId)).limit(1),+ tx.query.messages.findMany({+ where: eq(messages.chatId, chatId),+ with: {+ parts: {+ orderBy: [asc(parts.order)]+ }+ },+ orderBy: [asc(messages.createdAt)]+ })+ ])- const chat = chatResult[0]- if (!chat) {- return null- }+ const chat = chatResult[0]+ if (!chat) {+ return null+ }- // Permission check- if (chat.visibility === 'private' && (!userId || chat.userId !== userId)) {- return null- }+ // Permission check for backward compatibility+ if (chat.visibility === 'private' && (!userId || chat.userId !== userId)) {+ return null+ }- // Build result- const uiMessages = messagesResult.map(msg =>- buildUIMessageFromDB(msg, msg.parts)- )- return { ...chat, messages: uiMessages }+ // Build result+ const uiMessages = messagesResult.map(msg =>+ buildUIMessageFromDB(msg, msg.parts)+ )+ return { ...chat, messages: uiMessages }+ })}/**@@ -175,38 +197,41 @@ export async function loadChatWithMessages(*/export async function deleteMessagesAfter(chatId: string,- messageId: string+ messageId: string,+ userId?: string): Promise<{ count: number }> {- // Get the message's timestamp- const [targetMessage] = await db- .select({ createdAt: messages.createdAt })- .from(messages)- .where(eq(messages.id, messageId))- .limit(1)-- if (!targetMessage) {- return { count: 0 }- }+ return withOptionalRLS(userId || null, async tx => {+ // Get the message's timestamp+ const [targetMessage] = await tx+ .select({ createdAt: messages.createdAt })+ .from(messages)+ .where(eq(messages.id, messageId))+ .limit(1)++ if (!targetMessage) {+ return { count: 0 }+ }- // Find messages to delete- const messagesToDelete = await db- .select({ id: messages.id })- .from(messages)- .where(- and(- eq(messages.chatId, chatId),- gt(messages.createdAt, targetMessage.createdAt)+ // Find messages to delete+ const messagesToDelete = await tx+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.chatId, chatId),+ gt(messages.createdAt, targetMessage.createdAt)+ ))- )- const messageIds = messagesToDelete.map(m => m.id)+ const messageIds = messagesToDelete.map(m => m.id)- if (messageIds.length > 0) {- // Delete messages (parts will be cascade deleted)- await db.delete(messages).where(inArray(messages.id, messageIds))- }+ if (messageIds.length > 0) {+ // Delete messages (parts will be cascade deleted)+ await tx.delete(messages).where(inArray(messages.id, messageIds))+ }- return { count: messageIds.length }+ return { count: messageIds.length }+ })}/**@@ -214,42 +239,47 @@ export async function deleteMessagesAfter(*/export async function deleteMessagesFromIndex(chatId: string,- messageId: string+ messageId: string,+ userId?: string): Promise<{ count: number }> {- // Get all messages for the chat- const allMessages = await db- .select({ id: messages.id, createdAt: messages.createdAt })- .from(messages)- .where(eq(messages.chatId, chatId))- .orderBy(asc(messages.createdAt))-- // Find the index of the target message- const messageIndex = allMessages.findIndex(m => m.id === messageId)-- if (messageIndex === -1) {- return { count: 0 }- }+ return withOptionalRLS(userId || null, async tx => {+ // Get all messages for the chat+ const allMessages = await tx+ .select({ id: messages.id, createdAt: messages.createdAt })+ .from(messages)+ .where(eq(messages.chatId, chatId))+ .orderBy(asc(messages.createdAt))++ // Find the index of the target message+ const messageIndex = allMessages.findIndex(m => m.id === messageId)++ if (messageIndex === -1) {+ return { count: 0 }+ }- // Get messages to delete (from index onwards)- const messagesToDelete = allMessages.slice(messageIndex)- const messageIds = messagesToDelete.map(m => m.id)+ // Get messages to delete (from index onwards)+ const messagesToDelete = allMessages.slice(messageIndex)+ const messageIds = messagesToDelete.map(m => m.id)- if (messageIds.length > 0) {- await db.delete(messages).where(inArray(messages.id, messageIds))- }+ if (messageIds.length > 0) {+ await tx.delete(messages).where(inArray(messages.id, messageIds))+ }- return { count: messageIds.length }+ return { count: messageIds.length }+ })}/*** Get all chats for a user*/export async function getChats(userId: string): Promise<Chat[]> {- return db- .select()- .from(chats)- .where(eq(chats.userId, userId))- .orderBy(desc(chats.createdAt))+ return withRLS(userId, async tx => {+ return tx+ .select()+ .from(chats)+ .where(eq(chats.userId, userId))+ .orderBy(desc(chats.createdAt))+ })}/**@@ -261,20 +291,22 @@ export async function getChatsPage(offset = 0): Promise<{ chats: Chat[]; nextOffset: number | null }> {try {- const results = await db- .select()- .from(chats)- .where(eq(chats.userId, userId))- .orderBy(desc(chats.createdAt))- .limit(limit)- .offset(offset)-- const nextOffset = results.length === limit ? offset + limit : null-- return {- chats: results,- nextOffset- }+ return withRLS(userId, async tx => {+ const results = await tx+ .select()+ .from(chats)+ .where(eq(chats.userId, userId))+ .orderBy(desc(chats.createdAt))+ .limit(limit)+ .offset(offset)++ const nextOffset = results.length === limit ? offset + limit : null++ return {+ chats: results,+ nextOffset+ }+ })} catch (error) {console.error('Error fetching chat page:', error)return { chats: [], nextOffset: null }@@ -289,16 +321,23 @@ export async function deleteChat(userId: string): Promise<{ success: boolean; error?: string }> {try {- // Verify ownership- const chat = await getChat(chatId, userId)- if (!chat || chat.userId !== userId) {- return { success: false, error: 'Unauthorized' }- }+ return withRLS(userId, async tx => {+ // Verify ownership+ const [chat] = await tx+ .select()+ .from(chats)+ .where(eq(chats.id, chatId))+ .limit(1)++ if (!chat || chat.userId !== userId) {+ return { success: false, error: 'Unauthorized' }+ }- // Delete the chat (messages and parts will cascade)- await db.delete(chats).where(eq(chats.id, chatId))+ // Delete the chat (messages and parts will cascade)+ await tx.delete(chats).where(eq(chats.id, chatId))- return { success: true }+ return { success: true }+ })} catch (error) {console.error('Error deleting chat:', error)return { success: false, error: 'Failed to delete chat' }@@ -313,18 +352,20 @@ export async function updateChatVisibility(userId: string,visibility: 'public' | 'private'): Promise<Chat | null> {- const chat = await getChat(chatId, userId)- if (!chat || chat.userId !== userId) {- return null- }+ return withRLS(userId, async tx => {+ const chat = await getChat(chatId, userId)+ if (!chat || chat.userId !== userId) {+ return null+ }- const [updatedChat] = await db- .update(chats)- .set({ visibility })- .where(eq(chats.id, chatId))- .returning()+ const [updatedChat] = await tx+ .update(chats)+ .set({ visibility })+ .where(eq(chats.id, chatId))+ .returning()- return updatedChat+ return updatedChat+ })}/**@@ -332,15 +373,18 @@ export async function updateChatVisibility(*/export async function updateChatTitle(chatId: string,- title: string+ title: string,+ userId?: string): Promise<Chat | null> {- const [updatedChat] = await db- .update(chats)- .set({ title })- .where(eq(chats.id, chatId))- .returning()+ return withOptionalRLS(userId || null, async tx => {+ const [updatedChat] = await tx+ .update(chats)+ .set({ title })+ .where(eq(chats.id, chatId))+ .returning()- return updatedChat || null+ return updatedChat || null+ })}/**@@ -360,7 +404,7 @@ export async function createChatWithFirstMessageTransaction({}): Promise<{ chat: Chat; message: Message }> {perfLog(`DB - createChatWithFirstMessageTransaction start`)const dbStart = performance.now()- return await db.transaction(async tx => {+ return await withRLS(userId, async tx => {// 1. Create chatconst [chat] = await tx.insert(chats)diff --git a/lib/db/index.ts b/lib/db/index.tsindex 50f10d9a..4f356dba 100644--- a/lib/db/index.ts+++ b/lib/db/index.ts@@ -5,19 +5,41 @@ import * as relations from './relations'import * as schema from './schema'// For server-side usage only-if (!process.env.DATABASE_URL && process.env.NODE_ENV !== 'test') {- throw new Error('DATABASE_URL environment variable is not set')+// Use restricted user for application if available, otherwise fall back to regular user+const isDevelopment = process.env.NODE_ENV === 'development'+const isTest = process.env.NODE_ENV === 'test'++if (+ !process.env.DATABASE_URL &&+ !process.env.DATABASE_RESTRICTED_URL &&+ !isTest+) {+ throw new Error(+ 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'+ )}// Connection with connection pooling for server environments+// Prefer restricted user for application runtimeconst connectionString =+ process.env.DATABASE_RESTRICTED_URL ?? // Prefer restricted userprocess.env.DATABASE_URL ??- (process.env.NODE_ENV === 'test'- ? 'postgres://user:pass@localhost:5432/testdb'- : undefined)+ (isTest ? 'postgres://user:pass@localhost:5432/testdb' : undefined)if (!connectionString) {- throw new Error('DATABASE_URL environment variable is not set')+ throw new Error(+ 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'+ )+}++// Log which connection is being used (for debugging)+if (isDevelopment) {+ console.log(+ '[DB] Using connection:',+ process.env.DATABASE_RESTRICTED_URL+ ? 'Restricted User (RLS Active)'+ : 'Owner User (RLS Bypassed)'+ )}const client = postgres(connectionString, {ssl: { rejectUnauthorized: false },diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 05631bfc..19683d90 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -46,7 +46,22 @@ export const chats = pgTable(table.userId,table.createdAt.desc()),- index('chats_created_at_idx').on(table.createdAt.desc())+ index('chats_created_at_idx').on(table.createdAt.desc()),++ // RLS Policies+ pgPolicy('users_manage_own_chats', {+ as: 'permissive',+ for: 'all',+ to: 'public',+ using: sql`user_id = current_setting('app.current_user_id', true)`,+ withCheck: sql`user_id = current_setting('app.current_user_id', true)`+ }),+ pgPolicy('public_chats_readable', {+ as: 'permissive',+ for: 'select',+ to: 'public',+ using: sql`visibility = 'public'`+ })]).enableRLS()@@ -69,7 +84,34 @@ export const messages = pgTable(},table => [index('messages_chat_id_idx').on(table.chatId),- index('messages_chat_id_created_at_idx').on(table.chatId, table.createdAt)+ index('messages_chat_id_created_at_idx').on(table.chatId, table.createdAt),++ // RLS Policies - allow access to messages if user owns the chat+ pgPolicy('users_manage_chat_messages', {+ as: 'permissive',+ for: 'all',+ to: 'public',+ using: sql`EXISTS (+ SELECT 1 FROM ${chats}+ WHERE ${chats}.id = chat_id+ AND ${chats}.user_id = current_setting('app.current_user_id', true)+ )`,+ withCheck: sql`EXISTS (+ SELECT 1 FROM ${chats}+ WHERE ${chats}.id = chat_id+ AND ${chats}.user_id = current_setting('app.current_user_id', true)+ )`+ }),+ pgPolicy('public_chat_messages_readable', {+ as: 'permissive',+ for: 'select',+ to: 'public',+ using: sql`EXISTS (+ SELECT 1 FROM ${chats}+ WHERE ${chats}.id = chat_id+ AND ${chats}.visibility = 'public'+ )`+ })]).enableRLS()@@ -177,7 +219,37 @@ export const parts = pgTable(check('tool_fields_required',sql`(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))`- )+ ),++ // RLS Policies - allow access to parts if user owns the related chat+ pgPolicy('users_manage_message_parts', {+ as: 'permissive',+ for: 'all',+ to: 'public',+ using: sql`EXISTS (+ SELECT 1 FROM ${messages}+ INNER JOIN ${chats} ON ${chats}.id = ${messages}.chat_id+ WHERE ${messages}.id = message_id+ AND ${chats}.user_id = current_setting('app.current_user_id', true)+ )`,+ withCheck: sql`EXISTS (+ SELECT 1 FROM ${messages}+ INNER JOIN ${chats} ON ${chats}.id = ${messages}.chat_id+ WHERE ${messages}.id = message_id+ AND ${chats}.user_id = current_setting('app.current_user_id', true)+ )`+ }),+ pgPolicy('public_chat_parts_readable', {+ as: 'permissive',+ for: 'select',+ to: 'public',+ using: sql`EXISTS (+ SELECT 1 FROM ${messages}+ INNER JOIN ${chats} ON ${chats}.id = ${messages}.chat_id+ WHERE ${messages}.id = message_id+ AND ${chats}.visibility = 'public'+ )`+ })]).enableRLS()diff --git a/lib/db/with-rls.ts b/lib/db/with-rls.tsnew file mode 100644index 00000000..4775a34b--- /dev/null+++ b/lib/db/with-rls.ts@@ -0,0 +1,92 @@+import { sql } from 'drizzle-orm'++import { db } from '.'++// Type for transaction or database instance+type DbInstance = typeof db+type TxInstance = Parameters<Parameters<typeof db.transaction>[0]>[0]++/**+ * Custom error class for RLS violations+ */+export class RLSViolationError extends Error {+ constructor(message = 'Row level security policy violation') {+ super(message)+ this.name = 'RLSViolationError'+ // Maintains proper stack trace for where our error was thrown (only available on V8)+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, RLSViolationError)+ }+ }+}++/**+ * Execute database operations with Row-Level Security context+ * Sets the current user ID for the transaction scope+ *+ * @param userId - The user ID to set for RLS policies+ * @param callback - The database operations to execute+ * @returns The result of the callback function+ * @throws {RLSViolationError} If RLS policy is violated+ *+ * @example+ * ```typescript+ * const result = await withRLS(userId, async (tx) => {+ * return tx.select().from(chats)+ * })+ * ```+ */+export async function withRLS<T>(+ userId: string,+ callback: (tx: TxInstance) => Promise<T>+): Promise<T> {+ try {+ return await db.transaction(async tx => {+ // Set the user ID for this transaction+ // Using SET LOCAL ensures it's only valid for this transaction+ // Note: SET LOCAL doesn't support parameterized queries, so we use sql.raw+ await tx.execute(+ sql.raw(+ `SET LOCAL app.current_user_id = '${userId.replace(/'/g, "''")}'`+ )+ )++ // Execute the callback with the transaction+ return await callback(tx)+ })+ } catch (error) {+ // Check for RLS policy violations+ const errorMessage = error instanceof Error ? error.message : String(error)+ if (+ errorMessage.includes('new row violates row-level security policy') ||+ errorMessage.includes('row-level security policy')+ ) {+ throw new RLSViolationError(+ `Access denied for user ${userId}. ${errorMessage}`+ )+ }++ // Re-throw other errors+ throw error+ }+}++/**+ * Execute database operations with optional RLS context+ * If userId is null, executes without RLS context (for public operations)+ *+ * @param userId - The user ID to set for RLS policies, or null for public access+ * @param callback - The database operations to execute+ * @returns The result of the callback function+ */+export async function withOptionalRLS<T>(+ userId: string | null,+ callback: (tx: TxInstance | DbInstance) => Promise<T>+): Promise<T> {+ if (userId) {+ return withRLS(userId, callback as (tx: TxInstance) => Promise<T>)+ }++ // Execute without RLS context for public operations+ return callback(db)+}diff --git a/lib/streaming/helpers/handle-stream-finish.ts b/lib/streaming/helpers/handle-stream-finish.tsindex e07e635a..fe593159 100644--- a/lib/streaming/helpers/handle-stream-finish.ts+++ b/lib/streaming/helpers/handle-stream-finish.ts@@ -97,7 +97,7 @@ export async function handleStreamFinish(// Update title after message is savedif (chatTitle && chatTitle !== DEFAULT_CHAT_TITLE) {- updateChatTitle(chatId, chatTitle).catch(error =>+ updateChatTitle(chatId, chatTitle, userId).catch(error =>console.error('Error updating title:', error))}