diff --git a/drizzle/0002_sicherheit_push_recht.sql b/drizzle/0002_sicherheit_push_recht.sql new file mode 100644 index 0000000..d3ba183 --- /dev/null +++ b/drizzle/0002_sicherheit_push_recht.sql @@ -0,0 +1,48 @@ +CREATE TABLE `password_resets` ( + `id` text PRIMARY KEY NOT NULL, + `user_id` integer NOT NULL, + `expires_at` integer NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `push_messages` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `topic` text NOT NULL, + `title` text NOT NULL, + `body` text DEFAULT '' NOT NULL, + `url` text DEFAULT '/' NOT NULL, + `recipients` integer DEFAULT 0 NOT NULL, + `failures` integer DEFAULT 0 NOT NULL, + `sent_by` integer, + `automatic` integer DEFAULT false NOT NULL, + `dedupe_key` text, + `created_at` integer DEFAULT (unixepoch()) NOT NULL, + FOREIGN KEY (`sent_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `push_messages_dedupe_key_unique` ON `push_messages` (`dedupe_key`);--> statement-breakpoint +CREATE TABLE `push_subscriptions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `endpoint` text NOT NULL, + `p256dh` text NOT NULL, + `auth` text NOT NULL, + `topics` text DEFAULT '[]' NOT NULL, + `created_at` integer DEFAULT (unixepoch()) NOT NULL, + `updated_at` integer DEFAULT (unixepoch()) NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `push_subscriptions_endpoint_unique` ON `push_subscriptions` (`endpoint`);--> statement-breakpoint +CREATE TABLE `rate_limits` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `key` text NOT NULL, + `at` integer NOT NULL +); +--> statement-breakpoint +CREATE INDEX `rate_limits_key_idx` ON `rate_limits` (`key`,`at`);--> statement-breakpoint +ALTER TABLE `messages` ADD `kind` text DEFAULT 'contact' NOT NULL;--> statement-breakpoint +ALTER TABLE `messages` ADD `page_url` text DEFAULT '' NOT NULL;--> statement-breakpoint +ALTER TABLE `posts` ADD `notify` integer DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE `posts` ADD `notified_at` integer;--> statement-breakpoint +ALTER TABLE `users` ADD `totp_secret` text;--> statement-breakpoint +ALTER TABLE `users` ADD `totp_enabled` integer DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE `users` ADD `recovery_codes` text DEFAULT '[]' NOT NULL; \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..432e3b4 --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1527 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "0e4c3bd0-5e88-49e2-812a-47ec8aee00c8", + "prevId": "7e0a0b4d-a15e-4201-987a-d7cf4d48cdcc", + "tables": { + "contacts": { + "name": "contacts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "photo_id": { + "name": "photo_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "listed": { + "name": "listed", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": { + "contacts_photo_id_media_id_fk": { + "name": "contacts_photo_id_media_id_fk", + "tableFrom": "contacts", + "tableTo": "media", + "columnsFrom": [ + "photo_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "editorial_comments": { + "name": "editorial_comments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "item_id": { + "name": "item_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "editorial_comments_item_idx": { + "name": "editorial_comments_item_idx", + "columns": [ + "item_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "editorial_comments_item_id_editorial_items_id_fk": { + "name": "editorial_comments_item_id_editorial_items_id_fk", + "tableFrom": "editorial_comments", + "tableTo": "editorial_items", + "columnsFrom": [ + "item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "editorial_comments_user_id_users_id_fk": { + "name": "editorial_comments_user_id_users_id_fk", + "tableFrom": "editorial_comments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "editorial_items": { + "name": "editorial_items", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'post'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'idea'" + }, + "assignee_id": { + "name": "assignee_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "due_date": { + "name": "due_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "post_id": { + "name": "post_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "page_id": { + "name": "page_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "editorial_date_idx": { + "name": "editorial_date_idx", + "columns": [ + "date" + ], + "isUnique": false + }, + "editorial_assignee_idx": { + "name": "editorial_assignee_idx", + "columns": [ + "assignee_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "editorial_items_assignee_id_users_id_fk": { + "name": "editorial_items_assignee_id_users_id_fk", + "tableFrom": "editorial_items", + "tableTo": "users", + "columnsFrom": [ + "assignee_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "editorial_items_post_id_posts_id_fk": { + "name": "editorial_items_post_id_posts_id_fk", + "tableFrom": "editorial_items", + "tableTo": "posts", + "columnsFrom": [ + "post_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "editorial_items_page_id_pages_id_fk": { + "name": "editorial_items_page_id_pages_id_fk", + "tableFrom": "editorial_items", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "editorial_items_created_by_users_id_fk": { + "name": "editorial_items_created_by_users_id_fk", + "tableFrom": "editorial_items", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'event'" + }, + "start_date": { + "name": "start_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "end_date": { + "name": "end_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "end_time": { + "name": "end_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "published": { + "name": "published", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "events_start_idx": { + "name": "events_start_idx", + "columns": [ + "start_date" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "media": { + "name": "media", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_name": { + "name": "original_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mime_type": { + "name": "mime_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "alt": { + "name": "alt", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "media_filename_unique": { + "name": "media_filename_unique", + "columns": [ + "filename" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messages": { + "name": "messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'contact'" + }, + "page_url": { + "name": "page_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "read": { + "name": "read", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "pages": { + "name": "pages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "parent_id": { + "name": "parent_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "teaser": { + "name": "teaser", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'file-text'" + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sky'" + }, + "cover_id": { + "name": "cover_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "content_easy": { + "name": "content_easy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "attachments": { + "name": "attachments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "contact_ids": { + "name": "contact_ids", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "published": { + "name": "published", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "pages_slug_idx": { + "name": "pages_slug_idx", + "columns": [ + "slug" + ], + "isUnique": true + }, + "pages_parent_idx": { + "name": "pages_parent_idx", + "columns": [ + "parent_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "pages_parent_id_pages_id_fk": { + "name": "pages_parent_id_pages_id_fk", + "tableFrom": "pages", + "tableTo": "pages", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "pages_cover_id_media_id_fk": { + "name": "pages_cover_id_media_id_fk", + "tableFrom": "pages", + "tableTo": "media", + "columnsFrom": [ + "cover_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "password_resets": { + "name": "password_resets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "password_resets_user_id_users_id_fk": { + "name": "password_resets_user_id_users_id_fk", + "tableFrom": "password_resets", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "posts": { + "name": "posts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "teaser": { + "name": "teaser", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "cover_id": { + "name": "cover_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "content_easy": { + "name": "content_easy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "video_url": { + "name": "video_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "gallery": { + "name": "gallery", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "attachments": { + "name": "attachments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "contact_ids": { + "name": "contact_ids", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "pinned": { + "name": "pinned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "notify": { + "name": "notify", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "notified_at": { + "name": "notified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "published": { + "name": "published", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "posts_slug_idx": { + "name": "posts_slug_idx", + "columns": [ + "slug" + ], + "isUnique": true + }, + "posts_published_idx": { + "name": "posts_published_idx", + "columns": [ + "published_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "posts_cover_id_media_id_fk": { + "name": "posts_cover_id_media_id_fk", + "tableFrom": "posts", + "tableTo": "media", + "columnsFrom": [ + "cover_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_messages": { + "name": "push_messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "topic": { + "name": "topic", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'/'" + }, + "recipients": { + "name": "recipients", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failures": { + "name": "failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "sent_by": { + "name": "sent_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "automatic": { + "name": "automatic", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "push_messages_dedupe_key_unique": { + "name": "push_messages_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_messages_sent_by_users_id_fk": { + "name": "push_messages_sent_by_users_id_fk", + "tableFrom": "push_messages", + "tableTo": "users", + "columnsFrom": [ + "sent_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "topics": { + "name": "topics", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "rate_limits": { + "name": "rate_limits", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "rate_limits_key_idx": { + "name": "rate_limits_key_idx", + "columns": [ + "key", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tiles": { + "name": "tiles", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'star'" + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sky'" + }, + "href": { + "name": "href", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'editor'" + }, + "totp_secret": { + "name": "totp_secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "totp_enabled": { + "name": "totp_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "recovery_codes": { + "name": "recovery_codes", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index b4362c1..a5cc0c6 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1790780351202, "tag": "0001_redaktionskalender", "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1790788599464, + "tag": "0002_sicherheit_push_recht", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index cb59a1d..685fa47 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,11 @@ "dependencies": { "better-sqlite3": "^13.0.3", "drizzle-orm": "^0.45.3", + "nodemailer": "^10.0.13", + "qrcode": "^1.5.4", "sanitize-html": "^2.17.0", - "sharp": "^0.35.5" + "sharp": "^0.35.5", + "web-push": "^3.6.7" }, "devDependencies": { "@fontsource-variable/montserrat": "^5.3.0", @@ -27,7 +30,10 @@ "@tiptap/starter-kit": "^3.31.3", "@types/better-sqlite3": "^7.6.13", "@types/node": "^24.0.0", + "@types/nodemailer": "^8.0.2", + "@types/qrcode": "^1.5.6", "@types/sanitize-html": "^2.16.0", + "@types/web-push": "^3.6.4", "drizzle-kit": "^0.31.11", "svelte": "^5.57.1", "svelte-check": "^4.7.6", @@ -3231,6 +3237,26 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/resolve": { "version": "1.20.2", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", @@ -3248,6 +3274,16 @@ "htmlparser2": "^12.0" } }, + "node_modules/@types/web-push": { + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz", + "integrity": "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -3261,6 +3297,39 @@ "node": ">=0.4.0" } }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/aria-query": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", @@ -3271,6 +3340,18 @@ "node": ">= 0.4" } }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, "node_modules/axobject-query": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", @@ -3293,6 +3374,18 @@ "node": ">=22" } }, + "node_modules/bn.js": { + "version": "4.12.5", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz", + "integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==", + "license": "MIT" + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -3300,6 +3393,15 @@ "dev": true, "license": "MIT" }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", @@ -3316,6 +3418,17 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -3326,6 +3439,24 @@ "node": ">=6" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/commondir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", @@ -3362,6 +3493,32 @@ "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", "license": "MIT" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -3387,6 +3544,12 @@ "dev": true, "license": "MIT" }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/dom-serializer": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", @@ -4083,6 +4246,21 @@ } } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/enhanced-resolve": { "version": "5.26.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", @@ -4223,6 +4401,19 @@ } } }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -4248,6 +4439,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-tsconfig": { "version": "4.14.3", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.3.tgz", @@ -4303,6 +4503,34 @@ "node": ">=20.19.0" } }, + "node_modules/http_ece": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", + "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, "node_modules/is-core-module": { "version": "2.17.0", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", @@ -4319,6 +4547,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-module": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", @@ -4355,6 +4592,27 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", @@ -4661,6 +4919,18 @@ "dev": true, "license": "MIT" }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -4671,6 +4941,21 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/mri": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", @@ -4691,6 +4976,12 @@ "node": ">=10" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.19", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", @@ -4718,6 +5009,15 @@ "node": "^18 || ^20 || >= 21" } }, + "node_modules/nodemailer": { + "version": "10.0.13", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.13.tgz", + "integrity": "sha512-SzG86OlvcW/NNhUFC6uROMwRTL4n7MswfQqC/T8mhkmnY1YVa23zUEMYi4ijSeXSl9GLz9ZeTJDUatEDuY5FeQ==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/obug": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", @@ -4739,12 +5039,57 @@ "dev": true, "license": "MIT" }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/parse-srcset": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/parse-srcset/-/parse-srcset-1.0.2.tgz", "integrity": "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==", "license": "MIT" }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", @@ -4771,6 +5116,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -4965,6 +5319,23 @@ "prosemirror-transform": "^1.1.0" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/readdirp": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", @@ -4979,6 +5350,21 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/resolve": { "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", @@ -5111,6 +5497,32 @@ "node": ">=6" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/sanitize-html": { "version": "2.17.7", "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.17.7.tgz", @@ -5141,6 +5553,12 @@ "node": ">=10" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/set-cookie-parser": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz", @@ -5242,6 +5660,32 @@ "source-map": "^0.6.0" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", @@ -5797,6 +6241,86 @@ "dev": true, "license": "MIT" }, + "node_modules/web-push": { + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", + "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "license": "MPL-2.0", + "dependencies": { + "asn1.js": "^5.3.0", + "http_ece": "1.2.0", + "https-proxy-agent": "^7.0.0", + "jws": "^4.0.0", + "minimist": "^1.2.5" + }, + "bin": { + "web-push": "src/cli.js" + }, + "engines": { + "node": ">= 16" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/zimmerframe": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", diff --git a/package.json b/package.json index e420e51..59b903f 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,11 @@ "dependencies": { "better-sqlite3": "^13.0.3", "drizzle-orm": "^0.45.3", + "nodemailer": "^10.0.13", + "qrcode": "^1.5.4", "sanitize-html": "^2.17.0", - "sharp": "^0.35.5" + "sharp": "^0.35.5", + "web-push": "^3.6.7" }, "devDependencies": { "@fontsource-variable/montserrat": "^5.3.0", @@ -37,7 +40,10 @@ "@tiptap/starter-kit": "^3.31.3", "@types/better-sqlite3": "^7.6.13", "@types/node": "^24.0.0", + "@types/nodemailer": "^8.0.2", + "@types/qrcode": "^1.5.6", "@types/sanitize-html": "^2.16.0", + "@types/web-push": "^3.6.4", "drizzle-kit": "^0.31.11", "svelte": "^5.57.1", "svelte-check": "^4.7.6", diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 63fee5b..46e4bb3 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -1,12 +1,18 @@ import type { Handle, ServerInit } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit'; import { SESSION_COOKIE, ensureInitialAdmin, purgeExpiredSessions, validateSession } from '$lib/server/auth'; +import { purgeRateLimits } from '$lib/server/ratelimit'; +import { getSettings } from '$lib/server/settings'; import { PREFS_COOKIE, parsePrefs } from '$lib/prefs'; export const init: ServerInit = async () => { await ensureInitialAdmin(); - purgeExpiredSessions(); - setInterval(purgeExpiredSessions, 6 * 3600e3).unref(); + const cleanup = () => { + purgeExpiredSessions(); + purgeRateLimits(); + }; + cleanup(); + setInterval(cleanup, 6 * 3600e3).unref(); }; export const handle: Handle = async ({ event, resolve }) => { @@ -14,10 +20,18 @@ export const handle: Handle = async ({ event, resolve }) => { event.locals.prefs = parsePrefs(cookies.get(PREFS_COOKIE)); event.locals.user = url.pathname.startsWith('/admin') ? validateSession(cookies.get(SESSION_COOKIE)) : null; - if (url.pathname.startsWith('/admin') && !url.pathname.startsWith('/admin/login') && !event.locals.user) { + const publicAdmin = ['/admin/login', '/admin/passwort-vergessen', '/admin/passwort-neu'].some((p) => url.pathname.startsWith(p)); + if (url.pathname.startsWith('/admin') && !publicAdmin && !event.locals.user) { redirect(303, `/admin/login?next=${encodeURIComponent(url.pathname + url.search)}`); } + // Pflicht zur Zwei-Faktor-Anmeldung für Administratoren + const u = event.locals.user; + if (u && u.role === 'admin' && !u.totpEnabled && getSettings().require2faAdmins) { + const allowed = ['/admin/konto', '/admin/logout', '/admin/api'].some((p) => url.pathname.startsWith(p)); + if (!allowed) redirect(303, '/admin/konto?zwei-faktor=pflicht'); + } + const { theme, size } = event.locals.prefs; const response = await resolve(event, { transformPageChunk: ({ html }) => @@ -27,5 +41,7 @@ export const handle: Handle = async ({ event, resolve }) => { response.headers.set('X-Content-Type-Options', 'nosniff'); response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); response.headers.set('X-Frame-Options', 'SAMEORIGIN'); + response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), payment=()'); + response.headers.set('Cross-Origin-Opener-Policy', 'same-origin'); return response; }; diff --git a/src/lib/admin/TwoFactorPanel.svelte b/src/lib/admin/TwoFactorPanel.svelte new file mode 100644 index 0000000..52112b8 --- /dev/null +++ b/src/lib/admin/TwoFactorPanel.svelte @@ -0,0 +1,120 @@ + + +
+
+ +
+

Zwei-Faktor-Anmeldung

+

+ {#if totp.enabled} + Aktiv. Bei der Anmeldung fragen wir zusätzlich nach einem Code aus deiner Authenticator-App. + {:else} + Schützt deinen Zugang, auch wenn jemand dein Passwort kennt. Du brauchst eine Authenticator-App, z. B. Aegis, Google oder Microsoft Authenticator. + {/if} +

+
+
+ + {#if totp.forced} + + {/if} + {#if error}{/if} + + {#if codes} +
+

Deine Wiederherstellungscodes – jetzt sicher aufbewahren!

+

Jeder Code funktioniert einmal, falls du dein Handy nicht zur Hand hast. Sie werden nur jetzt angezeigt.

+ + +
+ {/if} + + {#if totp.enabled} +

Noch {totp.recoveryLeft} von 8 Wiederherstellungscodes übrig.

+
+ + {#if !totp.required} + + {/if} +
+ {#if showRenew || showDisable} +
+
+ + +
+ +
+ {/if} + {:else if totp.setup} +
    +
  1. +

    Scanne den QR-Code mit deiner Authenticator-App.

    +
    + +
    +

    Scannen nicht möglich? Diesen Schlüssel eintippen:

    +

    {totp.setup.secret}

    +
    +
    +
  2. +
  3. +
    +
    + + +
    + +
    +
  4. +
+
+ +
+ {:else} +
+ +
+ {/if} +
diff --git a/src/lib/server/auth.ts b/src/lib/server/auth.ts index 401f0ca..bfaa5f7 100644 --- a/src/lib/server/auth.ts +++ b/src/lib/server/auth.ts @@ -3,7 +3,7 @@ import { promisify } from 'node:util'; import { eq, lt } from 'drizzle-orm'; import type { Cookies } from '@sveltejs/kit'; import { db } from './db'; -import { sessions, users, type User } from './db/schema'; +import { passwordResets, sessions, users, type User } from './db/schema'; const scryptAsync = promisify(scrypt) as (pw: string, salt: Buffer, len: number) => Promise; @@ -38,7 +38,7 @@ export function createSession(cookies: Cookies, userId: number) { }); } -export type SessionUser = Pick; +export type SessionUser = Pick; export function validateSession(token: string | undefined): SessionUser | null { if (!token) return null; @@ -53,8 +53,8 @@ export function validateSession(token: string | undefined): SessionUser | null { db.delete(sessions).where(eq(sessions.id, row.session.id)).run(); return null; } - const { id, email, name, role } = row.user; - return { id, email, name, role }; + const { id, email, name, role, totpEnabled } = row.user; + return { id, email, name, role, totpEnabled }; } export function destroySession(cookies: Cookies) { @@ -65,8 +65,16 @@ export function destroySession(cookies: Cookies) { export function purgeExpiredSessions() { db.delete(sessions).where(lt(sessions.expiresAt, new Date())).run(); + db.delete(passwordResets).where(lt(passwordResets.expiresAt, new Date())).run(); } +/** Alle Sitzungen einer Person beenden (z. B. nach Passwort-Reset) */ +export function destroyAllSessions(userId: number) { + db.delete(sessions).where(eq(sessions.userId, userId)).run(); +} + +export { hashToken }; + /** Legt beim allerersten Start einen Admin aus den Umgebungsvariablen an. */ export async function ensureInitialAdmin() { const existing = db.select({ id: users.id }).from(users).limit(1).get(); diff --git a/src/lib/server/db/schema.ts b/src/lib/server/db/schema.ts index 5194cbc..fcd2491 100644 --- a/src/lib/server/db/schema.ts +++ b/src/lib/server/db/schema.ts @@ -24,9 +24,34 @@ export const users = sqliteTable('users', { role: text('role', { enum: ['admin', 'editor'] }) .notNull() .default('editor'), + /** TOTP-Geheimnis (Base32), nur gesetzt wenn 2FA eingerichtet ist */ + totpSecret: text('totp_secret'), + totpEnabled: integer('totp_enabled', { mode: 'boolean' }).notNull().default(false), + /** Gehashte Wiederherstellungscodes (einmal verwendbar) */ + recoveryCodes: text('recovery_codes', { mode: 'json' }).$type().notNull().default([]), ...timestamps }); +/** Links zum Zurücksetzen des Passworts (nur Hash gespeichert) */ +export const passwordResets = sqliteTable('password_resets', { + id: text('id').primaryKey(), + userId: integer('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull() +}); + +/** Sperren gegen zu viele Versuche (Anmeldung, Formulare) – überstehen Neustarts */ +export const rateLimits = sqliteTable( + 'rate_limits', + { + id: integer('id').primaryKey({ autoIncrement: true }), + key: text('key').notNull(), + at: integer('at').notNull() + }, + (t) => [index('rate_limits_key_idx').on(t.key, t.at)] +); + export const sessions = sqliteTable('sessions', { id: text('id').primaryKey(), userId: integer('user_id') @@ -118,6 +143,9 @@ export const posts = sqliteTable( attachments: text('attachments', { mode: 'json' }).$type().notNull().default([]), contactIds: text('contact_ids', { mode: 'json' }).$type().notNull().default([]), pinned: integer('pinned', { mode: 'boolean' }).notNull().default(false), + /** Beim Erscheinen eine Push-Benachrichtigung senden */ + notify: integer('notify', { mode: 'boolean' }).notNull().default(false), + notifiedAt: integer('notified_at', { mode: 'timestamp' }), published: integer('published', { mode: 'boolean' }).notNull().default(true), publishedAt: integer('published_at', { mode: 'timestamp' }) .notNull() @@ -169,6 +197,12 @@ export const tiles = sqliteTable('tiles', { export const messages = sqliteTable('messages', { id: integer('id').primaryKey({ autoIncrement: true }), + /** contact = Kontaktformular, barrier = Meldung einer Barriere */ + kind: text('kind', { enum: ['contact', 'barrier'] }) + .notNull() + .default('contact'), + /** Seite, auf die sich eine Barriere-Meldung bezieht */ + pageUrl: text('page_url').notNull().default(''), name: text('name').notNull(), email: text('email').notNull(), message: text('message').notNull(), @@ -176,6 +210,36 @@ export const messages = sqliteTable('messages', { ...timestamps }); +// ─── Push-Benachrichtigungen ─────────────────────────────────────────────────── + +export const pushSubscriptions = sqliteTable('push_subscriptions', { + id: integer('id').primaryKey({ autoIncrement: true }), + endpoint: text('endpoint').notNull().unique(), + p256dh: text('p256dh').notNull(), + auth: text('auth').notNull(), + /** abonnierte Themen, z. B. ["news","closures"] */ + topics: text('topics', { mode: 'json' }).$type().notNull().default([]), + ...timestamps +}); + +export const pushMessages = sqliteTable('push_messages', { + id: integer('id').primaryKey({ autoIncrement: true }), + topic: text('topic').notNull(), + title: text('title').notNull(), + body: text('body').notNull().default(''), + url: text('url').notNull().default('/'), + recipients: integer('recipients').notNull().default(0), + failures: integer('failures').notNull().default(0), + sentBy: integer('sent_by').references(() => users.id, { onDelete: 'set null' }), + /** automatisch (Schließzeit/Meldung) oder von Hand */ + automatic: integer('automatic', { mode: 'boolean' }).notNull().default(false), + /** Schlüssel gegen doppeltes Senden, z. B. closure-12 */ + dedupeKey: text('dedupe_key').unique(), + createdAt: integer('created_at', { mode: 'timestamp' }) + .notNull() + .default(sql`(unixepoch())`) +}); + // ─── Redaktionskalender ──────────────────────────────────────────────────────── /** Geplante Beiträge und Aufgaben des Redaktionsteams */ @@ -230,3 +294,4 @@ export type Tile = typeof tiles.$inferSelect; export type Message = typeof messages.$inferSelect; export type EditorialItem = typeof editorialItems.$inferSelect; export type EditorialComment = typeof editorialComments.$inferSelect; +export type PushSubscription = typeof pushSubscriptions.$inferSelect; diff --git a/src/lib/server/login.ts b/src/lib/server/login.ts new file mode 100644 index 0000000..2b1aaab --- /dev/null +++ b/src/lib/server/login.ts @@ -0,0 +1,5 @@ +/** Cookie für den zweiten Anmeldeschritt (Code aus der Authenticator-App) */ +export const TWO_FA_COOKIE = 'wa_2fa'; + +/** Nur Weiterleitungen innerhalb der Redaktion zulassen */ +export const safeNext = (n: string | null) => (n && n.startsWith('/admin') && !n.startsWith('//') ? n : '/admin'); diff --git a/src/lib/server/mail.ts b/src/lib/server/mail.ts new file mode 100644 index 0000000..c071d6c --- /dev/null +++ b/src/lib/server/mail.ts @@ -0,0 +1,38 @@ +import nodemailer, { type Transporter } from 'nodemailer'; +import { getSettings } from './settings'; + +/** + * E-Mail-Versand über SMTP (Einstellungen in der .env). + * Ohne SMTP-Konfiguration wird die Nachricht nur ins Server-Log geschrieben. + */ +const host = process.env.SMTP_HOST; +let transport: Transporter | null = null; + +export const mailConfigured = () => !!host; + +function transporter() { + if (!host) return null; + transport ??= nodemailer.createTransport({ + host, + port: Number(process.env.SMTP_PORT ?? 587), + secure: process.env.SMTP_SECURE === 'true' || process.env.SMTP_PORT === '465', + auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS ?? '' } : undefined + }); + return transport; +} + +export async function sendMail({ to, subject, text }: { to: string; subject: string; text: string }): Promise { + const t = transporter(); + const from = process.env.SMTP_FROM ?? `${getSettings().appName} `; + if (!t) { + console.log(`[mail] SMTP nicht eingerichtet – E-Mail an ${to} nicht versendet:\n Betreff: ${subject}\n ${text.replace(/\n/g, '\n ')}`); + return false; + } + try { + await t.sendMail({ from, to, subject, text }); + return true; + } catch (e) { + console.error('[mail] Versand fehlgeschlagen:', (e as Error).message); + return false; + } +} diff --git a/src/lib/server/ratelimit.ts b/src/lib/server/ratelimit.ts new file mode 100644 index 0000000..f371b3a --- /dev/null +++ b/src/lib/server/ratelimit.ts @@ -0,0 +1,37 @@ +import { and, eq, gte, lt, sql } from 'drizzle-orm'; +import { db } from './db'; +import { rateLimits } from './db/schema'; + +/** + * Einfache Sperre gegen zu viele Versuche, in der Datenbank gespeichert + * (übersteht Neustarts). Schlüssel z. B. `login-ip:1.2.3.4`. + */ +export function attempts(key: string, windowMs: number): number { + return ( + db + .select({ n: sql`count(*)` }) + .from(rateLimits) + .where(and(eq(rateLimits.key, key), gte(rateLimits.at, Date.now() - windowMs))) + .get()?.n ?? 0 + ); +} + +export function record(key: string) { + db.insert(rateLimits).values({ key, at: Date.now() }).run(); +} + +export function clear(key: string) { + db.delete(rateLimits).where(eq(rateLimits.key, key)).run(); +} + +/** Prüft und zählt in einem Schritt. true = erlaubt. */ +export function allow(key: string, limit: number, windowMs: number): boolean { + if (attempts(key, windowMs) >= limit) return false; + record(key); + return true; +} + +/** Alte Einträge (> 2 Tage) entfernen */ +export function purgeRateLimits() { + db.delete(rateLimits).where(lt(rateLimits.at, Date.now() - 2 * 864e5)).run(); +} diff --git a/src/lib/server/secret.ts b/src/lib/server/secret.ts new file mode 100644 index 0000000..1e214bc --- /dev/null +++ b/src/lib/server/secret.ts @@ -0,0 +1,34 @@ +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; +import { eq } from 'drizzle-orm'; +import { db } from './db'; +import { settings } from './db/schema'; + +let cached: Buffer | null = null; + +/** Geheimer Schlüssel des Servers – einmal erzeugt und in der Datenbank abgelegt */ +function secret(): Buffer { + if (cached) return cached; + const row = db.select().from(settings).where(eq(settings.key, 'server-secret')).get(); + if (row) cached = Buffer.from(String(row.value), 'base64'); + else { + cached = randomBytes(32); + db.insert(settings).values({ key: 'server-secret', value: cached.toString('base64') }).run(); + } + return cached; +} + +/** Signiert einen Wert: `wert.signatur` */ +export function sign(value: string): string { + return `${value}.${createHmac('sha256', secret()).update(value).digest('base64url')}`; +} + +/** Prüft eine Signatur und gibt den Wert zurück (oder null) */ +export function unsign(signed: string | undefined): string | null { + if (!signed) return null; + const i = signed.lastIndexOf('.'); + if (i < 1) return null; + const value = signed.slice(0, i); + const expected = Buffer.from(sign(value).slice(i + 1)); + const actual = Buffer.from(signed.slice(i + 1)); + return expected.length === actual.length && timingSafeEqual(expected, actual) ? value : null; +} diff --git a/src/lib/server/totp.ts b/src/lib/server/totp.ts new file mode 100644 index 0000000..62f5034 --- /dev/null +++ b/src/lib/server/totp.ts @@ -0,0 +1,99 @@ +import { createHash, createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'; +import QRCode from 'qrcode'; +import { attempts, record } from './ratelimit'; + +/** Zwei-Faktor-Anmeldung nach RFC 6238 (Authenticator-Apps wie Aegis, Google, Microsoft …) */ + +const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; +const STEP = 30; + +function base32Encode(buf: Buffer): string { + let bits = 0, + value = 0, + out = ''; + for (const byte of buf) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + out += ALPHABET[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]; + return out; +} + +function base32Decode(s: string): Buffer { + const clean = s.replace(/[\s=-]/g, '').toUpperCase(); + let bits = 0, + value = 0; + const out: number[] = []; + for (const ch of clean) { + const i = ALPHABET.indexOf(ch); + if (i < 0) continue; + value = (value << 5) | i; + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 255); + bits -= 8; + } + } + return Buffer.from(out); +} + +export const newSecret = () => base32Encode(randomBytes(20)); + +function code(secret: string, counter: number): string { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(counter)); + const h = createHmac('sha1', base32Decode(secret)).update(buf).digest(); + const o = h[h.length - 1] & 15; + const n = ((h[o] & 127) << 24) | (h[o + 1] << 16) | (h[o + 2] << 8) | h[o + 3]; + return String(n % 1_000_000).padStart(6, '0'); +} + +/** + * Prüft einen 6-stelligen Code (±30 s Toleranz). Jeder Code gilt nur einmal + * (`userId` verhindert Wiederverwendung). + */ +export function verifyTotp(secret: string, input: string, userId: number): boolean { + const clean = input.replace(/\s/g, ''); + if (!/^\d{6}$/.test(clean)) return false; + const now = Math.floor(Date.now() / 1000 / STEP); + for (const c of [now, now - 1, now + 1]) { + const expected = code(secret, c); + if (timingSafeEqual(Buffer.from(expected), Buffer.from(clean))) { + const key = `totp-used:${userId}:${c}`; + if (attempts(key, 3 * STEP * 1000) > 0) return false; + record(key); + return true; + } + } + return false; +} + +export function otpauthUri(secret: string, account: string, issuer: string) { + const label = encodeURIComponent(`${issuer}:${account}`); + return `otpauth://totp/${label}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`; +} + +export const qrSvg = (text: string) => QRCode.toString(text, { type: 'svg', margin: 1, errorCorrectionLevel: 'M' }); + +// ─── Wiederherstellungscodes ───────────────────────────────────────────────── + +const hashCode = (c: string) => createHash('sha256').update(c.replace(/[\s-]/g, '').toLowerCase()).digest('hex'); + +export function newRecoveryCodes(): { plain: string[]; hashed: string[] } { + const chars = 'abcdefghjkmnpqrstuvwxyz23456789'; + const plain = Array.from({ length: 8 }, () => { + const s = Array.from({ length: 8 }, () => chars[randomInt(chars.length)]).join(''); + return `${s.slice(0, 4)}-${s.slice(4)}`; + }); + return { plain, hashed: plain.map(hashCode) }; +} + +/** Gibt die verbleibenden Codes zurück, wenn `input` passt – sonst null */ +export function useRecoveryCode(hashed: string[], input: string): string[] | null { + const h = hashCode(input); + return hashed.includes(h) ? hashed.filter((x) => x !== h) : null; +} diff --git a/src/lib/settings.ts b/src/lib/settings.ts index 8e3b057..b2f682c 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -24,6 +24,8 @@ export type AppSettings = { imprint: string; privacy: string; /** Wie viele Meldungen/Termine die Startseite zeigt */ + /** Administratoren müssen die Zwei-Faktor-Anmeldung einrichten */ + require2faAdmins: boolean; homeNewsCount: number; homeEventsCount: number; }; @@ -44,6 +46,7 @@ export const DEFAULT_SETTINGS: AppSettings = { contactIntro: 'Du hast Fragen oder Ideen für die App? Schreib uns gerne!', imprint: '

Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.

', privacy: '

Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.

', + require2faAdmins: false, homeNewsCount: 4, homeEventsCount: 4 }; diff --git a/src/routes/(app)/kontakt/+page.server.ts b/src/routes/(app)/kontakt/+page.server.ts index c21a0df..ce978e2 100644 --- a/src/routes/(app)/kontakt/+page.server.ts +++ b/src/routes/(app)/kontakt/+page.server.ts @@ -2,9 +2,8 @@ import { fail } from '@sveltejs/kit'; import { db } from '$lib/server/db'; import { messages } from '$lib/server/db/schema'; import { getSettings } from '$lib/server/settings'; +import { allow } from '$lib/server/ratelimit'; -// Einfacher Schutz gegen Spam: max. 5 Nachrichten pro Stunde und IP -const hits = new Map(); export const load = () => { const s = getSettings(); @@ -28,11 +27,9 @@ export const actions = { if (name.length > 200 || email.length > 200 || message.length > 5000) return fail(400, { ...values, error: 'Die Nachricht ist zu lang.' }); - const ip = getClientAddress(); - const now = Date.now(); - const recent = (hits.get(ip) ?? []).filter((t) => now - t < 3600e3); - if (recent.length >= 5) return fail(429, { ...values, error: 'Zu viele Nachrichten. Bitte versuche es später noch einmal.' }); - hits.set(ip, [...recent, now]); + // Schutz gegen Spam: max. 5 Nachrichten pro Stunde und Gerät + if (!allow(`kontakt:${getClientAddress()}`, 5, 3600e3)) + return fail(429, { ...values, error: 'Zu viele Nachrichten. Bitte versuche es später noch einmal.' }); db.insert(messages).values({ name, email, message }).run(); return { sent: true }; diff --git a/src/routes/admin/(panel)/benutzer/+page.server.ts b/src/routes/admin/(panel)/benutzer/+page.server.ts index 912d13a..9bff8c0 100644 --- a/src/routes/admin/(panel)/benutzer/+page.server.ts +++ b/src/routes/admin/(panel)/benutzer/+page.server.ts @@ -6,6 +6,6 @@ import { requireAdmin } from '$lib/server/forms'; export const load = ({ locals }) => { requireAdmin(locals.user); return { - users: db.select({ id: users.id, name: users.name, email: users.email, role: users.role }).from(users).orderBy(asc(users.name)).all() + users: db.select({ id: users.id, name: users.name, email: users.email, role: users.role, totpEnabled: users.totpEnabled }).from(users).orderBy(asc(users.name)).all() }; }; diff --git a/src/routes/admin/(panel)/benutzer/+page.svelte b/src/routes/admin/(panel)/benutzer/+page.svelte index b0b2029..117592b 100644 --- a/src/routes/admin/(panel)/benutzer/+page.svelte +++ b/src/routes/admin/(panel)/benutzer/+page.svelte @@ -2,6 +2,7 @@ import Plus from '@lucide/svelte/icons/plus'; import ShieldCheck from '@lucide/svelte/icons/shield-check'; import Pencil from '@lucide/svelte/icons/pencil'; + import Smartphone from '@lucide/svelte/icons/smartphone'; import PageHeader from '$lib/admin/PageHeader.svelte'; let { data } = $props(); @@ -23,6 +24,9 @@ {u.name}{u.id === data.user.id ? ' (du)' : ''} {u.email} + {#if u.totpEnabled} + + {/if} {#if u.role === 'admin'} Admin {:else} diff --git a/src/routes/admin/(panel)/benutzer/[id]/+page.server.ts b/src/routes/admin/(panel)/benutzer/[id]/+page.server.ts index 4294cd5..ed17599 100644 --- a/src/routes/admin/(panel)/benutzer/[id]/+page.server.ts +++ b/src/routes/admin/(panel)/benutzer/[id]/+page.server.ts @@ -8,8 +8,8 @@ import { hashPassword } from '$lib/server/auth'; export const load = ({ params, locals }) => { requireAdmin(locals.user); const id = parseId(params.id); - if (id === 'new') return { isNew: true, account: { id: 0, name: '', email: '', role: 'editor' as const } }; - const u = db.select({ id: users.id, name: users.name, email: users.email, role: users.role }).from(users).where(eq(users.id, id)).get(); + if (id === 'new') return { isNew: true, account: { id: 0, name: '', email: '', role: 'editor' as const, totpEnabled: false } }; + const u = db.select({ id: users.id, name: users.name, email: users.email, role: users.role, totpEnabled: users.totpEnabled }).from(users).where(eq(users.id, id)).get(); if (!u) error(404); return { isNew: false, account: u }; }; @@ -42,6 +42,15 @@ export const actions = { if (password && id !== locals.user!.id) db.delete(sessions).where(eq(sessions.userId, id)).run(); return { saved: true }; }, + /** Handy verloren? Admin setzt die Zwei-Faktor-Anmeldung zurück */ + reset2fa: ({ params, locals }) => { + requireAdmin(locals.user); + const id = parseId(params.id); + if (id === 'new') return; + db.update(users).set({ totpSecret: null, totpEnabled: false, recoveryCodes: [] }).where(eq(users.id, id)).run(); + db.delete(sessions).where(eq(sessions.userId, id)).run(); + return { saved: true }; + }, delete: ({ params, locals }) => { requireAdmin(locals.user); const id = parseId(params.id); diff --git a/src/routes/admin/(panel)/benutzer/[id]/+page.svelte b/src/routes/admin/(panel)/benutzer/[id]/+page.svelte index 28692bf..560e0e1 100644 --- a/src/routes/admin/(panel)/benutzer/[id]/+page.svelte +++ b/src/routes/admin/(panel)/benutzer/[id]/+page.svelte @@ -2,6 +2,8 @@ import PageHeader from '$lib/admin/PageHeader.svelte'; import EditForm from '$lib/admin/EditForm.svelte'; import Panel from '$lib/admin/Panel.svelte'; + import { enhance } from '$app/forms'; + import { toasts } from '$lib/admin/toast.svelte'; let { data } = $props(); const a = $derived(data.account); @@ -37,3 +39,13 @@ {/key} + +{#if !data.isNew && data.account.totpEnabled && data.account.id !== data.user.id} +
+

Zwei-Faktor-Anmeldung

+

Aktiv. Wenn {data.account.name} das Handy und die Wiederherstellungscodes verloren hat, kannst du sie hier zurücksetzen. Die Person wird dabei überall abgemeldet.

+
async ({ update }) => { await update(); toasts.show('Zwei-Faktor-Anmeldung zurückgesetzt'); }}> + +
+
+{/if} diff --git a/src/routes/admin/(panel)/einstellungen/+page.server.ts b/src/routes/admin/(panel)/einstellungen/+page.server.ts index 0d325f3..3cc6661 100644 --- a/src/routes/admin/(panel)/einstellungen/+page.server.ts +++ b/src/routes/admin/(panel)/einstellungen/+page.server.ts @@ -38,6 +38,7 @@ export const actions = { contactIntro: f.str('contactIntro', 400), imprint: cleanHtml(f.html('imprint')), privacy: cleanHtml(f.html('privacy')), + require2faAdmins: f.bool('require2faAdmins'), homeNewsCount: Math.min(12, Math.max(0, f.int('homeNewsCount') ?? 4)), homeEventsCount: Math.min(12, Math.max(0, f.int('homeEventsCount') ?? 4)) }); diff --git a/src/routes/admin/(panel)/einstellungen/+page.svelte b/src/routes/admin/(panel)/einstellungen/+page.svelte index c9d39f2..fd7cab6 100644 --- a/src/routes/admin/(panel)/einstellungen/+page.svelte +++ b/src/routes/admin/(panel)/einstellungen/+page.svelte @@ -93,6 +93,15 @@ + + + + diff --git a/src/routes/admin/(panel)/konto/+page.server.ts b/src/routes/admin/(panel)/konto/+page.server.ts index 1984adf..d2c4bdc 100644 --- a/src/routes/admin/(panel)/konto/+page.server.ts +++ b/src/routes/admin/(panel)/konto/+page.server.ts @@ -1,4 +1,7 @@ import { fail } from '@sveltejs/kit'; +import { getSettings } from '$lib/server/settings'; +import { newRecoveryCodes, newSecret, otpauthUri, qrSvg, verifyTotp } from '$lib/server/totp'; +import { allow } from '$lib/server/ratelimit'; import { and, eq, ne } from 'drizzle-orm'; import { db } from '$lib/server/db'; import { sessions, users } from '$lib/server/db/schema'; @@ -6,6 +9,26 @@ import { fields } from '$lib/server/forms'; import { hashPassword, verifyPassword, SESSION_COOKIE } from '$lib/server/auth'; import { createHash } from 'node:crypto'; +export const load = async ({ locals, url }) => { + const me = db.select().from(users).where(eq(users.id, locals.user!.id)).get()!; + const s = getSettings(); + const pending = !me.totpEnabled && !!me.totpSecret; + return { + totp: { + enabled: me.totpEnabled, + recoveryLeft: me.recoveryCodes.length, + required: me.role === 'admin' && s.require2faAdmins, + forced: url.searchParams.get('zwei-faktor') === 'pflicht' && !me.totpEnabled, + setup: pending + ? { + secret: me.totpSecret!.replace(/(.{4})/g, '$1 ').trim(), + qr: await qrSvg(otpauthUri(me.totpSecret!, me.email, s.appName)) + } + : null + } + }; +}; + export const actions = { save: async ({ request, locals, cookies }) => { const f = fields(await request.formData()); @@ -26,5 +49,48 @@ export const actions = { db.update(users).set({ name }).where(eq(users.id, me.id)).run(); } return { saved: true }; + }, + + /** 2FA einrichten: neues Geheimnis erzeugen (noch nicht aktiv) */ + totpStart: async ({ locals }) => { + db.update(users).set({ totpSecret: newSecret(), totpEnabled: false }).where(eq(users.id, locals.user!.id)).run(); + return { totpStarted: true }; + }, + + /** Code aus der App bestätigen → 2FA aktiv, Wiederherstellungscodes einmalig anzeigen */ + totpConfirm: async ({ request, locals }) => { + const me = db.select().from(users).where(eq(users.id, locals.user!.id)).get()!; + if (!me.totpSecret) return fail(400, { totpError: 'Bitte starte die Einrichtung neu.' }); + if (!allow(`2fa-setup:${me.id}`, 10, 15 * 60e3)) return fail(429, { totpError: 'Zu viele Versuche. Bitte warte 15 Minuten.' }); + const code = String((await request.formData()).get('code') ?? ''); + if (!verifyTotp(me.totpSecret, code, me.id)) return fail(400, { totpError: 'Der Code stimmt nicht. Prüfe die Uhrzeit deines Handys und versuche den nächsten Code.' }); + const { plain, hashed } = newRecoveryCodes(); + db.update(users).set({ totpEnabled: true, recoveryCodes: hashed }).where(eq(users.id, me.id)).run(); + return { recoveryCodes: plain }; + }, + + totpCancel: async ({ locals }) => { + db.update(users).set({ totpSecret: null, totpEnabled: false }).where(eq(users.id, locals.user!.id)).run(); + return {}; + }, + + /** Neue Wiederherstellungscodes (alte werden ungültig) */ + totpRecovery: async ({ request, locals }) => { + const me = db.select().from(users).where(eq(users.id, locals.user!.id)).get()!; + const pw = String((await request.formData()).get('current') ?? ''); + if (!(await verifyPassword(pw, me.passwordHash))) return fail(400, { totpError: 'Das Passwort stimmt nicht.' }); + const { plain, hashed } = newRecoveryCodes(); + db.update(users).set({ recoveryCodes: hashed }).where(eq(users.id, me.id)).run(); + return { recoveryCodes: plain }; + }, + + totpDisable: async ({ request, locals }) => { + const me = db.select().from(users).where(eq(users.id, locals.user!.id)).get()!; + if (me.role === 'admin' && getSettings().require2faAdmins) + return fail(400, { totpError: 'Für Administratoren ist die Zwei-Faktor-Anmeldung Pflicht.' }); + const pw = String((await request.formData()).get('current') ?? ''); + if (!(await verifyPassword(pw, me.passwordHash))) return fail(400, { totpError: 'Das Passwort stimmt nicht.' }); + db.update(users).set({ totpSecret: null, totpEnabled: false, recoveryCodes: [] }).where(eq(users.id, me.id)).run(); + return { totpDisabled: true }; } }; diff --git a/src/routes/admin/(panel)/konto/+page.svelte b/src/routes/admin/(panel)/konto/+page.svelte index 1655ef7..81a6c65 100644 --- a/src/routes/admin/(panel)/konto/+page.svelte +++ b/src/routes/admin/(panel)/konto/+page.svelte @@ -3,12 +3,15 @@ import EditForm from '$lib/admin/EditForm.svelte'; import Panel from '$lib/admin/Panel.svelte'; import PrefsControls from '$lib/components/PrefsControls.svelte'; + import TwoFactorPanel from '$lib/admin/TwoFactorPanel.svelte'; - let { data } = $props(); + let { data, form } = $props(); + +

Anzeige

Gilt für dieses Gerät – in der Redaktion und in der App. Wird sofort übernommen.

diff --git a/src/routes/admin/login/+page.server.ts b/src/routes/admin/login/+page.server.ts index 3ad7ed9..e53b2eb 100644 --- a/src/routes/admin/login/+page.server.ts +++ b/src/routes/admin/login/+page.server.ts @@ -3,13 +3,15 @@ import { eq } from 'drizzle-orm'; import { db } from '$lib/server/db'; import { users } from '$lib/server/db/schema'; import { createSession, verifyPassword, SESSION_COOKIE, validateSession } from '$lib/server/auth'; +import { allow, clear } from '$lib/server/ratelimit'; +import { sign } from '$lib/server/secret'; +import { TWO_FA_COOKIE, safeNext } from '$lib/server/login'; -const attempts = new Map(); - -const safeNext = (n: string | null) => (n && n.startsWith('/admin') && !n.startsWith('//') ? n : '/admin'); +const WINDOW = 15 * 60e3; export const load = ({ cookies, url }) => { if (validateSession(cookies.get(SESSION_COOKIE))) redirect(303, safeNext(url.searchParams.get('next'))); + return { notice: url.searchParams.get('hinweis') }; }; export const actions = { @@ -18,19 +20,34 @@ export const actions = { const email = String(form.get('email') ?? '').trim().toLowerCase(); const password = String(form.get('password') ?? ''); - // Brute-Force-Bremse: max. 10 Versuche in 15 Minuten pro IP - const ip = getClientAddress(); - const now = Date.now(); - const recent = (attempts.get(ip) ?? []).filter((t) => now - t < 15 * 60e3); - if (recent.length >= 10) return fail(429, { email, error: 'Zu viele Versuche. Bitte warte ein paar Minuten.' }); - + // Bremse: 10 Fehlversuche je Gerät bzw. 5 je Konto in 15 Minuten + const ipKey = `login-ip:${getClientAddress()}`; + const userKey = `login-user:${email}`; const user = db.select().from(users).where(eq(users.email, email)).get(); - if (!user || !(await verifyPassword(password, user.passwordHash))) { - attempts.set(ip, [...recent, now]); - return fail(400, { email, error: 'E-Mail oder Passwort stimmt nicht.' }); + const ok = !!user && (await verifyPassword(password, user.passwordHash)); + if (!ok) { + const underLimit = allow(ipKey, 10, WINDOW) && allow(userKey, 5, WINDOW); + return fail(underLimit ? 400 : 429, { + email, + error: underLimit ? 'E-Mail oder Passwort stimmt nicht.' : 'Zu viele Versuche. Bitte warte 15 Minuten.' + }); + } + if (!allow(ipKey, 10, WINDOW)) return fail(429, { email, error: 'Zu viele Versuche. Bitte warte 15 Minuten.' }); + clear(ipKey); + clear(userKey); + + const next = safeNext(url.searchParams.get('next')); + if (user.totpEnabled) { + // Zweiter Schritt: Code aus der Authenticator-App (5 Minuten gültig) + cookies.set(TWO_FA_COOKIE, sign(`${user.id}:${Date.now() + 5 * 60e3}`), { + path: '/admin/login', + httpOnly: true, + sameSite: 'strict', + maxAge: 300 + }); + redirect(303, `/admin/login/zwei-faktor?next=${encodeURIComponent(next)}`); } - attempts.delete(ip); createSession(cookies, user.id); - redirect(303, safeNext(url.searchParams.get('next'))); + redirect(303, next); } }; diff --git a/src/routes/admin/login/+page.svelte b/src/routes/admin/login/+page.svelte index dd3f81f..661210f 100644 --- a/src/routes/admin/login/+page.svelte +++ b/src/routes/admin/login/+page.svelte @@ -1,36 +1,48 @@ Anmelden · {data.brand.appName} -
+
{#if data.brand.logo} {:else} - + {/if} -

Redaktion

+

Redaktion

{data.brand.appName}

- {#if form?.error}{/if} + {#if form?.error} + + {:else if data.notice && notices[data.notice]} +

{notices[data.notice]}

+ {/if}
- +
+ + Vergessen? +

← Zur App

-
+ diff --git a/src/routes/admin/login/zwei-faktor/+page.server.ts b/src/routes/admin/login/zwei-faktor/+page.server.ts new file mode 100644 index 0000000..443ed4b --- /dev/null +++ b/src/routes/admin/login/zwei-faktor/+page.server.ts @@ -0,0 +1,45 @@ +import { fail, redirect } from '@sveltejs/kit'; +import { eq } from 'drizzle-orm'; +import { db } from '$lib/server/db'; +import { users } from '$lib/server/db/schema'; +import { createSession } from '$lib/server/auth'; +import { unsign } from '$lib/server/secret'; +import { allow } from '$lib/server/ratelimit'; +import { useRecoveryCode, verifyTotp } from '$lib/server/totp'; +import { TWO_FA_COOKIE, safeNext } from '$lib/server/login'; + +/** Wer hat den ersten Schritt (Passwort) bestanden? */ +function pendingUser(cookie: string | undefined) { + const value = unsign(cookie); + if (!value) return null; + const [id, until] = value.split(':').map(Number); + if (!id || !until || until < Date.now()) return null; + return db.select().from(users).where(eq(users.id, id)).get() ?? null; +} + +export const load = ({ cookies }) => { + if (!pendingUser(cookies.get(TWO_FA_COOKIE))) redirect(303, '/admin/login?hinweis=abgelaufen'); +}; + +export const actions = { + default: async ({ request, cookies, url }) => { + const user = pendingUser(cookies.get(TWO_FA_COOKIE)); + if (!user?.totpSecret) redirect(303, '/admin/login?hinweis=abgelaufen'); + if (!allow(`2fa:${user.id}`, 5, 15 * 60e3)) return fail(429, { error: 'Zu viele Versuche. Bitte warte 15 Minuten.' }); + + const input = String((await request.formData()).get('code') ?? '').trim(); + let ok = verifyTotp(user.totpSecret, input, user.id); + if (!ok && input.replace(/[\s-]/g, '').length === 8) { + const remaining = useRecoveryCode(user.recoveryCodes, input); + if (remaining) { + db.update(users).set({ recoveryCodes: remaining }).where(eq(users.id, user.id)).run(); + ok = true; + } + } + if (!ok) return fail(400, { error: 'Der Code stimmt nicht. Bitte den aktuellen Code aus der App eingeben.' }); + + cookies.delete(TWO_FA_COOKIE, { path: '/admin/login' }); + createSession(cookies, user.id); + redirect(303, safeNext(url.searchParams.get('next'))); + } +}; diff --git a/src/routes/admin/login/zwei-faktor/+page.svelte b/src/routes/admin/login/zwei-faktor/+page.svelte new file mode 100644 index 0000000..2b34b3f --- /dev/null +++ b/src/routes/admin/login/zwei-faktor/+page.svelte @@ -0,0 +1,44 @@ + + +Bestätigen · {data.brand.appName} + +
+
+
+ +

Anmeldung bestätigen

+

+ {recovery ? 'Gib einen deiner Wiederherstellungscodes ein.' : 'Gib den 6-stelligen Code aus deiner Authenticator-App ein.'} +

+
+
+ {#if form?.error}{/if} +
+ + {#key recovery} + + + {/key} +
+ + +
+

← Zurück zur Anmeldung

+
+
diff --git a/src/routes/admin/passwort-neu/[token]/+page.server.ts b/src/routes/admin/passwort-neu/[token]/+page.server.ts new file mode 100644 index 0000000..9b6466a --- /dev/null +++ b/src/routes/admin/passwort-neu/[token]/+page.server.ts @@ -0,0 +1,32 @@ +import { fail, redirect } from '@sveltejs/kit'; +import { and, eq, gt } from 'drizzle-orm'; +import { db } from '$lib/server/db'; +import { passwordResets, users } from '$lib/server/db/schema'; +import { destroyAllSessions, hashPassword, hashToken } from '$lib/server/auth'; + +function findReset(token: string) { + return db + .select() + .from(passwordResets) + .where(and(eq(passwordResets.id, hashToken(token)), gt(passwordResets.expiresAt, new Date()))) + .get(); +} + +export const load = ({ params }) => ({ valid: !!findReset(params.token) }); + +export const actions = { + default: async ({ request, params }) => { + const reset = findReset(params.token); + if (!reset) return fail(400, { error: 'Der Link ist abgelaufen oder wurde schon benutzt. Bitte fordere einen neuen an.' }); + const form = await request.formData(); + const password = String(form.get('password') ?? ''); + const repeat = String(form.get('repeat') ?? ''); + if (password.length < 10) return fail(400, { error: 'Das Passwort muss mindestens 10 Zeichen haben.' }); + if (password !== repeat) return fail(400, { error: 'Die beiden Passwörter stimmen nicht überein.' }); + + db.update(users).set({ passwordHash: await hashPassword(password) }).where(eq(users.id, reset.userId)).run(); + db.delete(passwordResets).where(eq(passwordResets.userId, reset.userId)).run(); + destroyAllSessions(reset.userId); + redirect(303, '/admin/login?hinweis=passwort-geaendert'); + } +}; diff --git a/src/routes/admin/passwort-neu/[token]/+page.svelte b/src/routes/admin/passwort-neu/[token]/+page.svelte new file mode 100644 index 0000000..0639331 --- /dev/null +++ b/src/routes/admin/passwort-neu/[token]/+page.svelte @@ -0,0 +1,32 @@ + + +Neues Passwort · {data.brand.appName} + +
+
+

Neues Passwort festlegen

+ {#if !data.valid} + + {:else} +
+ {#if form?.error}{/if} +
+ + + +

Mindestens 10 Zeichen. Ein Satz aus mehreren Wörtern ist leicht zu merken und sicher.

+
+
+ + +
+ +
+ {/if} +
+
diff --git a/src/routes/admin/passwort-vergessen/+page.server.ts b/src/routes/admin/passwort-vergessen/+page.server.ts new file mode 100644 index 0000000..407085c --- /dev/null +++ b/src/routes/admin/passwort-vergessen/+page.server.ts @@ -0,0 +1,34 @@ +import { fail } from '@sveltejs/kit'; +import { randomBytes } from 'node:crypto'; +import { eq } from 'drizzle-orm'; +import { db } from '$lib/server/db'; +import { passwordResets, users } from '$lib/server/db/schema'; +import { hashToken } from '$lib/server/auth'; +import { allow } from '$lib/server/ratelimit'; +import { sendMail } from '$lib/server/mail'; +import { getSettings } from '$lib/server/settings'; + +export const actions = { + default: async ({ request, url, getClientAddress }) => { + const email = String((await request.formData()).get('email') ?? '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return fail(400, { email, error: 'Bitte gib eine gültige E-Mail-Adresse ein.' }); + if (!allow(`reset-ip:${getClientAddress()}`, 5, 60 * 60e3) || !allow(`reset-mail:${email}`, 3, 60 * 60e3)) + return fail(429, { email, error: 'Zu viele Anfragen. Bitte versuche es in einer Stunde noch einmal.' }); + + const user = db.select().from(users).where(eq(users.email, email)).get(); + if (user) { + const token = randomBytes(32).toString('base64url'); + db.delete(passwordResets).where(eq(passwordResets.userId, user.id)).run(); + db.insert(passwordResets).values({ id: hashToken(token), userId: user.id, expiresAt: new Date(Date.now() + 60 * 60e3) }).run(); + const origin = process.env.ORIGIN ?? url.origin; + const app = getSettings().appName; + await sendMail({ + to: user.email, + subject: `${app}: Passwort zurücksetzen`, + text: `Hallo ${user.name},\n\nfür deinen Zugang zur Redaktion von „${app}“ wurde ein neues Passwort angefordert.\n\nÜber diesen Link kannst du es festlegen (1 Stunde gültig):\n${origin}/admin/passwort-neu/${token}\n\nWenn du das nicht warst, kannst du diese E-Mail einfach ignorieren – dein Passwort bleibt unverändert.` + }); + } + // Immer dieselbe Antwort – verrät nicht, ob es das Konto gibt + return { sent: true }; + } +}; diff --git a/src/routes/admin/passwort-vergessen/+page.svelte b/src/routes/admin/passwort-vergessen/+page.svelte new file mode 100644 index 0000000..6b6b246 --- /dev/null +++ b/src/routes/admin/passwort-vergessen/+page.svelte @@ -0,0 +1,31 @@ + + +Passwort vergessen · {data.brand.appName} + +
+
+

Passwort vergessen

+ {#if form?.sent} +
+ +

Falls es ein Konto mit dieser Adresse gibt, haben wir dir eine E-Mail mit einem Link geschickt. Er ist eine Stunde gültig.

+

Keine E-Mail bekommen? Schau im Spam-Ordner nach oder frag eine Administratorin.

+
+ {:else} +

Gib deine E-Mail-Adresse ein. Du bekommst einen Link, mit dem du ein neues Passwort festlegst.

+
+ {#if form?.error}{/if} +
+ + + +
+ +
+ {/if} +

← Zur Anmeldung

+
+
diff --git a/svelte.config.js b/svelte.config.js index 1e98b23..d8b6bf4 100644 --- a/svelte.config.js +++ b/svelte.config.js @@ -4,7 +4,28 @@ import adapter from '@sveltejs/adapter-node'; const config = { kit: { adapter: adapter(), - csrf: { trustedOrigins: [] } + csrf: { trustedOrigins: [] }, + // Content-Security-Policy: nur eigene Skripte (Inline-Skripte von SvelteKit per Nonce), + // eingebettete Videos nur von YouTube (nocookie) und Vimeo. + csp: { + mode: 'auto', + directives: { + 'default-src': ['self'], + 'script-src': ['self'], + 'style-src': ['self', 'unsafe-inline'], + 'img-src': ['self', 'data:', 'blob:'], + 'font-src': ['self', 'data:'], + 'connect-src': ['self'], + 'media-src': ['self'], + 'frame-src': ['https://www.youtube-nocookie.com', 'https://player.vimeo.com'], + 'worker-src': ['self'], + 'manifest-src': ['self'], + 'object-src': ['none'], + 'base-uri': ['self'], + 'form-action': ['self'], + 'frame-ancestors': ['self'] + } + } } };