fix: address all code review findings

- Extract shared permission logic into boardPermissions.ts utility
- Fix DnD drag revert: add dirty flag to prevent  overwrite
- Wrap OAuth group sync in Prisma transaction (N+1 fix)
- Add empty widgetIds validation in widget reorder API
- Add invalidateAll() after guest toggle PATCH
- Replace console.error with user-visible error banners
- Extract WidgetCreationForm component (DraggableSection was 448 lines)
- Remove unused boardId prop from DraggableSection
- Always include OAuth state parameter + validate in callback
- Clean up copyLink timer on component destroy
- Add type-specific widget config validation in addWidget action
This commit is contained in:
2026-03-25 00:03:32 +03:00
parent 5a6002be76
commit cba160ecb8
15 changed files with 588 additions and 447 deletions
@@ -1,21 +1,14 @@
<script lang="ts">
import { t } from 'svelte-i18n';
import { TargetType, PermissionLevel } from '$lib/utils/constants.js';
interface PermissionRecord {
id: string;
entityType: string;
entityId: string;
targetType: string;
targetId: string;
level: string;
createdAt: string;
}
interface SelectOption {
id: string;
name: string;
}
import {
loadBoardPermissions,
grantBoardPermission,
revokeBoardPermission,
getTargetName as resolveTargetName,
type PermissionRecord,
type SelectOption
} from '$lib/utils/boardPermissions.js';
interface Props {
boardId: string;
@@ -50,15 +43,9 @@
loading = true;
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`);
const json = await res.json();
if (json.success) {
permissions = json.data;
} else {
errorMessage = json.error ?? 'Failed to load permissions';
}
} catch {
errorMessage = 'Network error';
permissions = await loadBoardPermissions(boardId);
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
} finally {
loading = false;
}
@@ -68,53 +55,27 @@
if (!selectedTargetId) return;
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
targetType: selectedTargetType,
targetId: selectedTargetId,
level: selectedLevel
})
});
const json = await res.json();
if (json.success) {
selectedTargetId = '';
searchQuery = '';
await loadPermissions();
} else {
errorMessage = json.error ?? 'Failed to grant permission';
}
} catch {
errorMessage = 'Network error';
await grantBoardPermission(boardId, selectedTargetType, selectedTargetId, selectedLevel);
selectedTargetId = '';
searchQuery = '';
await loadPermissions();
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
}
}
async function handleRevoke(perm: PermissionRecord) {
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
targetType: perm.targetType,
targetId: perm.targetId
})
});
const json = await res.json();
if (json.success) {
await loadPermissions();
} else {
errorMessage = json.error ?? 'Failed to revoke permission';
}
} catch {
errorMessage = 'Network error';
await revokeBoardPermission(boardId, perm.targetType, perm.targetId);
await loadPermissions();
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
}
}
function getTargetName(targetType: string, targetId: string): string {
const list = targetType === TargetType.USER ? users : groups;
return list.find((item) => item.id === targetId)?.name ?? targetId;
return resolveTargetName(targetType, targetId, users, groups);
}
function getLevelLabel(level: string): string {
@@ -1,21 +1,14 @@
<script lang="ts">
import { t } from 'svelte-i18n';
import { TargetType, PermissionLevel } from '$lib/utils/constants.js';
interface PermissionRecord {
id: string;
entityType: string;
entityId: string;
targetType: string;
targetId: string;
level: string;
createdAt: string;
}
interface SelectOption {
id: string;
name: string;
}
import {
loadBoardPermissions,
grantBoardPermission,
revokeBoardPermission,
getTargetName as resolveTargetName,
type PermissionRecord,
type SelectOption
} from '$lib/utils/boardPermissions.js';
interface Props {
boardId: string;
@@ -41,6 +34,7 @@
let loading = $state(true);
let errorMessage = $state('');
let copySuccess = $state(false);
let copyTimerId = $state<ReturnType<typeof setTimeout> | null>(null);
let selectedTargetType = $state<string>(TargetType.USER);
let selectedTargetId = $state('');
@@ -63,15 +57,9 @@
loading = true;
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`);
const json = await res.json();
if (json.success) {
permissions = json.data;
} else {
errorMessage = json.error ?? 'Failed to load permissions';
}
} catch {
errorMessage = 'Network error';
permissions = await loadBoardPermissions(boardId);
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
} finally {
loading = false;
}
@@ -81,53 +69,27 @@
if (!selectedTargetId) return;
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
targetType: selectedTargetType,
targetId: selectedTargetId,
level: selectedLevel
})
});
const json = await res.json();
if (json.success) {
selectedTargetId = '';
searchQuery = '';
await loadPermissions();
} else {
errorMessage = json.error ?? 'Failed to grant permission';
}
} catch {
errorMessage = 'Network error';
await grantBoardPermission(boardId, selectedTargetType, selectedTargetId, selectedLevel);
selectedTargetId = '';
searchQuery = '';
await loadPermissions();
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
}
}
async function handleRevoke(perm: PermissionRecord) {
errorMessage = '';
try {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
targetType: perm.targetType,
targetId: perm.targetId
})
});
const json = await res.json();
if (json.success) {
await loadPermissions();
} else {
errorMessage = json.error ?? 'Failed to revoke permission';
}
} catch {
errorMessage = 'Network error';
await revokeBoardPermission(boardId, perm.targetType, perm.targetId);
await loadPermissions();
} catch (err) {
errorMessage = err instanceof Error ? err.message : 'Network error';
}
}
function getTargetName(targetType: string, targetId: string): string {
const list = targetType === TargetType.USER ? users : groups;
return list.find((item) => item.id === targetId)?.name ?? targetId;
return resolveTargetName(targetType, targetId, users, groups);
}
function getLevelLabel(level: string): string {
@@ -148,8 +110,12 @@
const url = `${window.location.origin}/boards/${boardId}`;
await navigator.clipboard.writeText(url);
copySuccess = true;
setTimeout(() => {
if (copyTimerId !== null) {
clearTimeout(copyTimerId);
}
copyTimerId = setTimeout(() => {
copySuccess = false;
copyTimerId = null;
}, 2000);
} catch {
// Fallback: ignore if clipboard API not available
@@ -168,9 +134,14 @@
}
}
// Load permissions on mount
// Load permissions on mount; clean up copy timer on destroy
$effect(() => {
loadPermissions();
return () => {
if (copyTimerId !== null) {
clearTimeout(copyTimerId);
}
};
});
</script>
+19 -5
View File
@@ -53,19 +53,25 @@
}: Props = $props();
let sections = $state<SectionData[]>([...initialSections]);
let dirty = $state(false);
let errorMessage = $state('');
// Keep local state in sync when parent data changes
// Keep local state in sync when parent data changes (skip during drag)
$effect(() => {
sections = [...initialSections];
if (!dirty) {
sections = [...initialSections];
}
});
const flipDurationMs = 200;
function handleConsider(e: CustomEvent<{ items: SectionData[] }>) {
dirty = true;
sections = e.detail.items;
}
async function handleFinalize(e: CustomEvent<{ items: SectionData[] }>) {
dirty = true;
sections = e.detail.items;
const sectionIds = sections.map((s) => s.id);
@@ -76,12 +82,15 @@
body: JSON.stringify({ sectionIds })
});
} catch (err) {
console.error('Failed to persist section reorder:', err);
errorMessage = err instanceof Error ? err.message : 'Failed to persist section reorder';
} finally {
dirty = false;
}
}
async function handleWidgetsUpdate(sectionId: string, widgets: WidgetData[]) {
// Update local state
dirty = true;
sections = sections.map((s) => (s.id === sectionId ? { ...s, widgets } : s));
const widgetIds = widgets.map((w) => w.id);
@@ -93,11 +102,17 @@
body: JSON.stringify({ widgetIds })
});
} catch (err) {
console.error('Failed to persist widget reorder:', err);
errorMessage = err instanceof Error ? err.message : 'Failed to persist widget reorder';
} finally {
dirty = false;
}
}
</script>
{#if errorMessage}
<p class="mb-2 text-sm text-destructive">{errorMessage}</p>
{/if}
{#if sections.length === 0}
<div class="rounded-xl border border-border bg-card/50 p-8 text-center">
<p class="text-muted-foreground">{$t('board.no_sections')}</p>
@@ -113,7 +128,6 @@
<div>
<DraggableSection
{section}
{boardId}
{apps}
onWidgetsUpdate={handleWidgetsUpdate}
{addWidgetSectionId}
@@ -2,6 +2,7 @@
import { t } from 'svelte-i18n';
import { dndzone } from 'svelte-dnd-action';
import DraggableWidget from '$lib/components/widget/DraggableWidget.svelte';
import WidgetCreationForm from '$lib/components/widget/WidgetCreationForm.svelte';
interface WidgetData {
id: string;
@@ -32,7 +33,6 @@
interface Props {
section: SectionData;
boardId: string;
apps: Array<{ id: string; name: string }>;
onWidgetsUpdate: (sectionId: string, widgets: WidgetData[]) => void;
addWidgetSectionId: string | null;
@@ -44,7 +44,6 @@
let {
section,
boardId: _boardId = '',
apps,
onWidgetsUpdate,
addWidgetSectionId,
@@ -54,108 +53,28 @@
onDeleteWidget
}: Props = $props();
// boardId reserved for future per-section API calls
void _boardId;
let widgets = $state<WidgetData[]>([...section.widgets]);
let dirty = $state(false);
// Keep local state in sync when parent data changes
// Keep local state in sync when parent data changes (skip during drag)
$effect(() => {
widgets = [...section.widgets];
if (!dirty) {
widgets = [...section.widgets];
}
});
const flipDurationMs = 200;
function handleConsider(e: CustomEvent<{ items: WidgetData[] }>) {
dirty = true;
widgets = e.detail.items;
}
function handleFinalize(e: CustomEvent<{ items: WidgetData[] }>) {
dirty = true;
widgets = e.detail.items;
onWidgetsUpdate(section.id, widgets);
}
// Widget form state
let selectedWidgetType = $state('app');
let selectedAppId = $state('');
// Bookmark fields
let bookmarkUrl = $state('');
let bookmarkLabel = $state('');
let bookmarkIcon = $state('');
let bookmarkDescription = $state('');
// Note fields
let noteContent = $state('');
let noteFormat = $state<'markdown' | 'text'>('markdown');
// Embed fields
let embedUrl = $state('');
let embedHeight = $state(300);
// Status fields
let statusLabel = $state('');
let statusAppIds = $state<string[]>([]);
function resetForm() {
selectedWidgetType = 'app';
selectedAppId = '';
bookmarkUrl = '';
bookmarkLabel = '';
bookmarkIcon = '';
bookmarkDescription = '';
noteContent = '';
noteFormat = 'markdown';
embedUrl = '';
embedHeight = 300;
statusLabel = '';
statusAppIds = [];
}
function handleSubmitWidget() {
let widgetData: Record<string, unknown> = { type: selectedWidgetType };
switch (selectedWidgetType) {
case 'app':
if (!selectedAppId) return;
widgetData.appId = selectedAppId;
break;
case 'bookmark':
if (!bookmarkUrl || !bookmarkLabel) return;
widgetData.url = bookmarkUrl;
widgetData.label = bookmarkLabel;
if (bookmarkIcon) widgetData.icon = bookmarkIcon;
if (bookmarkDescription) widgetData.description = bookmarkDescription;
break;
case 'note':
if (!noteContent) return;
widgetData.content = noteContent;
widgetData.format = noteFormat;
break;
case 'embed':
if (!embedUrl) return;
widgetData.url = embedUrl;
widgetData.height = embedHeight;
break;
case 'status':
if (statusAppIds.length === 0) return;
widgetData.appIds = statusAppIds;
if (statusLabel) widgetData.label = statusLabel;
break;
default:
return;
}
onAddWidget(section.id, JSON.stringify(widgetData));
resetForm();
}
function toggleStatusApp(appId: string) {
if (statusAppIds.includes(appId)) {
statusAppIds = statusAppIds.filter((id) => id !== appId);
} else {
statusAppIds = [...statusAppIds, appId];
}
dirty = false;
}
function getWidgetLabel(widget: WidgetData): string {
@@ -227,181 +146,11 @@
</div>
{#if addWidgetSectionId === section.id}
<div class="mb-3 rounded-lg border border-border bg-muted/50 p-3">
<!-- Widget Type Selector -->
<div class="mb-3">
<label for="widget-type-{section.id}" class="mb-1 block text-sm font-medium text-foreground">
Widget Type
</label>
<select
id="widget-type-{section.id}"
bind:value={selectedWidgetType}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="app">App</option>
<option value="bookmark">Bookmark</option>
<option value="note">Note</option>
<option value="embed">Embed</option>
<option value="status">Status</option>
</select>
</div>
<!-- Type-specific config forms -->
{#if selectedWidgetType === 'app'}
<div>
<label for="widget-app-{section.id}" class="mb-1 block text-sm font-medium text-foreground">
{$t('widget.select_app')}
</label>
<select
id="widget-app-{section.id}"
bind:value={selectedAppId}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="">{$t('widget.choose_app')}</option>
{#each apps as app (app.id)}
<option value={app.id}>{app.name}</option>
{/each}
</select>
</div>
{:else if selectedWidgetType === 'bookmark'}
<div class="grid gap-3 sm:grid-cols-2">
<div>
<label for="bm-url-{section.id}" class="mb-1 block text-sm font-medium text-foreground">URL</label>
<input
id="bm-url-{section.id}"
type="url"
bind:value={bookmarkUrl}
placeholder="https://example.com"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="bm-label-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Label</label>
<input
id="bm-label-{section.id}"
type="text"
bind:value={bookmarkLabel}
placeholder="My Bookmark"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="bm-icon-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Icon (optional)</label>
<input
id="bm-icon-{section.id}"
type="text"
bind:value={bookmarkIcon}
placeholder="e.g. an emoji or icon name"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
<div>
<label for="bm-desc-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Description (optional)</label>
<input
id="bm-desc-{section.id}"
type="text"
bind:value={bookmarkDescription}
placeholder="A short description"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
</div>
{:else if selectedWidgetType === 'note'}
<div class="space-y-3">
<div>
<label for="note-format-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Format</label>
<select
id="note-format-{section.id}"
bind:value={noteFormat}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="markdown">Markdown</option>
<option value="text">Plain Text</option>
</select>
</div>
<div>
<label for="note-content-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Content</label>
<textarea
id="note-content-{section.id}"
bind:value={noteContent}
rows="4"
placeholder="Write your note here..."
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
></textarea>
</div>
</div>
{:else if selectedWidgetType === 'embed'}
<div class="grid gap-3 sm:grid-cols-2">
<div class="sm:col-span-2">
<label for="embed-url-{section.id}" class="mb-1 block text-sm font-medium text-foreground">URL</label>
<input
id="embed-url-{section.id}"
type="url"
bind:value={embedUrl}
placeholder="https://example.com/embed"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="embed-height-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Height (px)</label>
<input
id="embed-height-{section.id}"
type="number"
bind:value={embedHeight}
min="100"
max="2000"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
</div>
{:else if selectedWidgetType === 'status'}
<div class="space-y-3">
<div>
<label for="status-label-{section.id}" class="mb-1 block text-sm font-medium text-foreground">Label (optional)</label>
<input
id="status-label-{section.id}"
type="text"
bind:value={statusLabel}
placeholder="e.g. Production Services"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
<div>
<span class="mb-1 block text-sm font-medium text-foreground">Select Apps</span>
<div class="max-h-40 space-y-1 overflow-y-auto rounded-lg border border-input bg-background p-2">
{#each apps as app (app.id)}
<label class="flex items-center gap-2 rounded px-2 py-1 text-sm text-foreground hover:bg-accent">
<input
type="checkbox"
checked={statusAppIds.includes(app.id)}
onchange={() => toggleStatusApp(app.id)}
class="h-4 w-4 rounded border-input accent-primary"
/>
{app.name}
</label>
{/each}
</div>
{#if statusAppIds.length > 0}
<p class="mt-1 text-xs text-muted-foreground">{statusAppIds.length} app(s) selected</p>
{/if}
</div>
</div>
{/if}
<div class="mt-3">
<button
type="button"
onclick={handleSubmitWidget}
class="rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
>
{$t('common.add')}
</button>
</div>
</div>
<WidgetCreationForm
sectionId={section.id}
{apps}
onSubmit={onAddWidget}
/>
{/if}
<!-- Widgets drop zone -->
@@ -0,0 +1,270 @@
<script lang="ts">
import { t } from 'svelte-i18n';
interface Props {
sectionId: string;
apps: Array<{ id: string; name: string }>;
onSubmit: (sectionId: string, widgetData: string) => void;
}
let { sectionId, apps, onSubmit }: Props = $props();
// Widget form state
let selectedWidgetType = $state('app');
let selectedAppId = $state('');
// Bookmark fields
let bookmarkUrl = $state('');
let bookmarkLabel = $state('');
let bookmarkIcon = $state('');
let bookmarkDescription = $state('');
// Note fields
let noteContent = $state('');
let noteFormat = $state<'markdown' | 'text'>('markdown');
// Embed fields
let embedUrl = $state('');
let embedHeight = $state(300);
// Status fields
let statusLabel = $state('');
let statusAppIds = $state<string[]>([]);
function resetForm() {
selectedWidgetType = 'app';
selectedAppId = '';
bookmarkUrl = '';
bookmarkLabel = '';
bookmarkIcon = '';
bookmarkDescription = '';
noteContent = '';
noteFormat = 'markdown';
embedUrl = '';
embedHeight = 300;
statusLabel = '';
statusAppIds = [];
}
function handleSubmitWidget() {
let widgetData: Record<string, unknown> = { type: selectedWidgetType };
switch (selectedWidgetType) {
case 'app':
if (!selectedAppId) return;
widgetData.appId = selectedAppId;
break;
case 'bookmark':
if (!bookmarkUrl || !bookmarkLabel) return;
widgetData.url = bookmarkUrl;
widgetData.label = bookmarkLabel;
if (bookmarkIcon) widgetData.icon = bookmarkIcon;
if (bookmarkDescription) widgetData.description = bookmarkDescription;
break;
case 'note':
if (!noteContent) return;
widgetData.content = noteContent;
widgetData.format = noteFormat;
break;
case 'embed':
if (!embedUrl) return;
widgetData.url = embedUrl;
widgetData.height = embedHeight;
break;
case 'status':
if (statusAppIds.length === 0) return;
widgetData.appIds = statusAppIds;
if (statusLabel) widgetData.label = statusLabel;
break;
default:
return;
}
onSubmit(sectionId, JSON.stringify(widgetData));
resetForm();
}
function toggleStatusApp(appId: string) {
if (statusAppIds.includes(appId)) {
statusAppIds = statusAppIds.filter((id) => id !== appId);
} else {
statusAppIds = [...statusAppIds, appId];
}
}
</script>
<div class="mb-3 rounded-lg border border-border bg-muted/50 p-3">
<!-- Widget Type Selector -->
<div class="mb-3">
<label for="widget-type-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">
Widget Type
</label>
<select
id="widget-type-{sectionId}"
bind:value={selectedWidgetType}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="app">App</option>
<option value="bookmark">Bookmark</option>
<option value="note">Note</option>
<option value="embed">Embed</option>
<option value="status">Status</option>
</select>
</div>
<!-- Type-specific config forms -->
{#if selectedWidgetType === 'app'}
<div>
<label for="widget-app-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">
{$t('widget.select_app')}
</label>
<select
id="widget-app-{sectionId}"
bind:value={selectedAppId}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="">{$t('widget.choose_app')}</option>
{#each apps as app (app.id)}
<option value={app.id}>{app.name}</option>
{/each}
</select>
</div>
{:else if selectedWidgetType === 'bookmark'}
<div class="grid gap-3 sm:grid-cols-2">
<div>
<label for="bm-url-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">URL</label>
<input
id="bm-url-{sectionId}"
type="url"
bind:value={bookmarkUrl}
placeholder="https://example.com"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="bm-label-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Label</label>
<input
id="bm-label-{sectionId}"
type="text"
bind:value={bookmarkLabel}
placeholder="My Bookmark"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="bm-icon-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Icon (optional)</label>
<input
id="bm-icon-{sectionId}"
type="text"
bind:value={bookmarkIcon}
placeholder="e.g. an emoji or icon name"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
<div>
<label for="bm-desc-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Description (optional)</label>
<input
id="bm-desc-{sectionId}"
type="text"
bind:value={bookmarkDescription}
placeholder="A short description"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
</div>
{:else if selectedWidgetType === 'note'}
<div class="space-y-3">
<div>
<label for="note-format-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Format</label>
<select
id="note-format-{sectionId}"
bind:value={noteFormat}
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
>
<option value="markdown">Markdown</option>
<option value="text">Plain Text</option>
</select>
</div>
<div>
<label for="note-content-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Content</label>
<textarea
id="note-content-{sectionId}"
bind:value={noteContent}
rows="4"
placeholder="Write your note here..."
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
></textarea>
</div>
</div>
{:else if selectedWidgetType === 'embed'}
<div class="grid gap-3 sm:grid-cols-2">
<div class="sm:col-span-2">
<label for="embed-url-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">URL</label>
<input
id="embed-url-{sectionId}"
type="url"
bind:value={embedUrl}
placeholder="https://example.com/embed"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
required
/>
</div>
<div>
<label for="embed-height-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Height (px)</label>
<input
id="embed-height-{sectionId}"
type="number"
bind:value={embedHeight}
min="100"
max="2000"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
</div>
{:else if selectedWidgetType === 'status'}
<div class="space-y-3">
<div>
<label for="status-label-{sectionId}" class="mb-1 block text-sm font-medium text-foreground">Label (optional)</label>
<input
id="status-label-{sectionId}"
type="text"
bind:value={statusLabel}
placeholder="e.g. Production Services"
class="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus:ring-2 focus:ring-ring/30"
/>
</div>
<div>
<span class="mb-1 block text-sm font-medium text-foreground">Select Apps</span>
<div class="max-h-40 space-y-1 overflow-y-auto rounded-lg border border-input bg-background p-2">
{#each apps as app (app.id)}
<label class="flex items-center gap-2 rounded px-2 py-1 text-sm text-foreground hover:bg-accent">
<input
type="checkbox"
checked={statusAppIds.includes(app.id)}
onchange={() => toggleStatusApp(app.id)}
class="h-4 w-4 rounded border-input accent-primary"
/>
{app.name}
</label>
{/each}
</div>
{#if statusAppIds.length > 0}
<p class="mt-1 text-xs text-muted-foreground">{statusAppIds.length} app(s) selected</p>
{/if}
</div>
</div>
{/if}
<div class="mt-3">
<button
type="button"
onclick={handleSubmitWidget}
class="rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
>
{$t('common.add')}
</button>
</div>
</div>
@@ -25,6 +25,7 @@ import { prisma } from '../../prisma.js';
import {
invalidateOAuthCache,
generateCodeVerifier,
generateState,
calculateCodeChallenge,
generateAuthUrl,
handleCallback,
@@ -69,6 +70,14 @@ describe('oauthService', () => {
});
});
describe('generateState', () => {
it('returns a random state string', () => {
const state = generateState();
expect(state).toBe('mock-state-123');
expect(mockClient.randomState).toHaveBeenCalledOnce();
});
});
describe('calculateCodeChallenge', () => {
it('returns a PKCE code challenge', async () => {
const challenge = await calculateCodeChallenge('my-verifier');
@@ -86,7 +95,7 @@ describe('oauthService', () => {
new URL('https://auth.example.com/authorize?code_challenge=abc')
);
const url = await generateAuthUrl('https://app.example.com/callback', 'test-challenge');
const url = await generateAuthUrl('https://app.example.com/callback', 'test-challenge', 'test-state');
expect(url).toBe('https://auth.example.com/authorize?code_challenge=abc');
expect(mockClient.buildAuthorizationUrl).toHaveBeenCalledWith(
@@ -95,7 +104,8 @@ describe('oauthService', () => {
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile email',
code_challenge: 'test-challenge',
code_challenge_method: 'S256'
code_challenge_method: 'S256',
state: 'test-state'
})
);
});
@@ -111,7 +121,7 @@ describe('oauthService', () => {
delete process.env.OAUTH_DISCOVERY_URL;
await expect(
generateAuthUrl('https://app.example.com/callback', 'challenge')
generateAuthUrl('https://app.example.com/callback', 'challenge', 'state')
).rejects.toThrow('OAuth is not configured');
// Restore
@@ -120,25 +130,20 @@ describe('oauthService', () => {
process.env.OAUTH_DISCOVERY_URL = origDiscovery;
});
it('adds state when provider does not support PKCE', async () => {
it('always includes the state parameter', async () => {
setupOAuthSettings();
const mockConfig = {
serverMetadata: () => ({
issuer: 'https://auth.example.com',
supportsPKCE: () => false
})
};
const mockConfig = createMockOIDCConfig();
mockClient.discovery.mockResolvedValue(mockConfig);
mockClient.buildAuthorizationUrl.mockReturnValue(
new URL('https://auth.example.com/authorize')
);
await generateAuthUrl('https://app.example.com/callback', 'test-challenge');
await generateAuthUrl('https://app.example.com/callback', 'test-challenge', 'custom-state');
expect(mockClient.buildAuthorizationUrl).toHaveBeenCalledWith(
mockConfig,
expect.objectContaining({
state: 'mock-state-123'
state: 'custom-state'
})
);
});
@@ -163,8 +168,9 @@ describe('oauthService', () => {
});
const result = await handleCallback(
new URL('https://app.example.com/callback?code=abc'),
'test-verifier'
new URL('https://app.example.com/callback?code=abc&state=test-state'),
'test-verifier',
'test-state'
);
expect(result).toEqual({
@@ -188,8 +194,9 @@ describe('oauthService', () => {
await expect(
handleCallback(
new URL('https://app.example.com/callback?code=abc'),
'test-verifier'
new URL('https://app.example.com/callback?code=abc&state=test-state'),
'test-verifier',
'test-state'
)
).rejects.toThrow('subject claim');
});
@@ -209,8 +216,9 @@ describe('oauthService', () => {
await expect(
handleCallback(
new URL('https://app.example.com/callback?code=abc'),
'test-verifier'
new URL('https://app.example.com/callback?code=abc&state=test-state'),
'test-verifier',
'test-state'
)
).rejects.toThrow('email');
});
+16 -9
View File
@@ -96,6 +96,13 @@ export function generateCodeVerifier(): string {
return client.randomPKCECodeVerifier();
}
/**
* Generates a cryptographically random state parameter.
*/
export function generateState(): string {
return client.randomState();
}
/**
* Calculates the PKCE code_challenge from a code_verifier.
*/
@@ -105,10 +112,12 @@ export async function calculateCodeChallenge(codeVerifier: string): Promise<stri
/**
* Builds the authorization URL to redirect the user to the OIDC provider.
* Always includes a state parameter for CSRF protection.
*/
export async function generateAuthUrl(
redirectUri: string,
codeChallenge: string
codeChallenge: string,
state: string
): Promise<string> {
const config = await getOIDCConfig();
@@ -116,14 +125,10 @@ export async function generateAuthUrl(
redirect_uri: redirectUri,
scope: 'openid profile email',
code_challenge: codeChallenge,
code_challenge_method: 'S256'
code_challenge_method: 'S256',
state
};
// Add state if the server might not support PKCE
if (!config.serverMetadata().supportsPKCE()) {
parameters.state = client.randomState();
}
const url = client.buildAuthorizationUrl(config, parameters);
return url.href;
}
@@ -133,12 +138,14 @@ export async function generateAuthUrl(
*/
export async function handleCallback(
callbackUrl: URL,
codeVerifier: string
codeVerifier: string,
expectedState: string
): Promise<OAuthUserInfo> {
const config = await getOIDCConfig();
const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
pkceCodeVerifier: codeVerifier
pkceCodeVerifier: codeVerifier,
expectedState
});
// Try to get user info from the userinfo endpoint
+12 -10
View File
@@ -184,14 +184,16 @@ async function syncOAuthGroups(userId: string, oauthGroupNames: readonly string[
return;
}
// Upsert memberships (idempotent — won't fail if already a member)
for (const group of matchingGroups) {
await prisma.userGroup.upsert({
where: {
userId_groupId: { userId, groupId: group.id }
},
update: {},
create: { userId, groupId: group.id }
});
}
// Upsert memberships in a single transaction (idempotent — won't fail if already a member)
await prisma.$transaction(
matchingGroups.map((group) =>
prisma.userGroup.upsert({
where: {
userId_groupId: { userId, groupId: group.id }
},
update: {},
create: { userId, groupId: group.id }
})
)
);
}
+86
View File
@@ -0,0 +1,86 @@
import { TargetType } from './constants.js';
export interface PermissionRecord {
id: string;
entityType: string;
entityId: string;
targetType: string;
targetId: string;
level: string;
createdAt: string;
}
export interface SelectOption {
id: string;
name: string;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: string;
}
/**
* Fetches the permission records for a board.
*/
export async function loadBoardPermissions(boardId: string): Promise<PermissionRecord[]> {
const res = await fetch(`/api/boards/${boardId}/permissions`);
const json: ApiResponse<PermissionRecord[]> = await res.json();
if (json.success && json.data) {
return json.data;
}
throw new Error(json.error ?? 'Failed to load permissions');
}
/**
* Grants a permission on a board to a user or group.
*/
export async function grantBoardPermission(
boardId: string,
targetType: string,
targetId: string,
level: string
): Promise<void> {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetType, targetId, level })
});
const json: ApiResponse<unknown> = await res.json();
if (!json.success) {
throw new Error(json.error ?? 'Failed to grant permission');
}
}
/**
* Revokes a permission on a board for a user or group.
*/
export async function revokeBoardPermission(
boardId: string,
targetType: string,
targetId: string
): Promise<void> {
const res = await fetch(`/api/boards/${boardId}/permissions`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetType, targetId })
});
const json: ApiResponse<unknown> = await res.json();
if (!json.success) {
throw new Error(json.error ?? 'Failed to revoke permission');
}
}
/**
* Resolves a target (user or group) ID to a display name.
*/
export function getTargetName(
targetType: string,
targetId: string,
users: SelectOption[],
groups: SelectOption[]
): string {
const list = targetType === TargetType.USER ? users : groups;
return list.find((item) => item.id === targetId)?.name ?? targetId;
}
@@ -37,8 +37,8 @@ export const PUT: RequestHandler = async (event) => {
}
const { widgetIds } = body as { widgetIds?: string[] };
if (!Array.isArray(widgetIds)) {
return json(error('widgetIds must be an array of strings'), { status: 400 });
if (!Array.isArray(widgetIds) || widgetIds.length === 0) {
return json(error('widgetIds must be a non-empty array of strings'), { status: 400 });
}
if (!widgetIds.every((wid) => typeof wid === 'string')) {
+8 -3
View File
@@ -14,18 +14,23 @@ export const GET: RequestHandler = async ({ cookies, url }) => {
const appUrl = process.env.APP_URL || url.origin;
const redirectUri = process.env.OAUTH_REDIRECT_URI || `${appUrl}/auth/oauth/callback`;
// Generate PKCE values
// Generate PKCE values and state parameter
const codeVerifier = oauthService.generateCodeVerifier();
const codeChallenge = await oauthService.calculateCodeChallenge(codeVerifier);
const state = oauthService.generateState();
// Store code_verifier in HTTP-only cookie for the callback
// Store code_verifier and state in HTTP-only cookies for the callback
cookies.set('oauth_code_verifier', codeVerifier, {
...COOKIE_BASE,
maxAge: 600 // 10 minutes — enough for the auth flow
});
cookies.set('oauth_state', state, {
...COOKIE_BASE,
maxAge: 600
});
// Build authorization URL and redirect
const authUrl = await oauthService.generateAuthUrl(redirectUri, codeChallenge);
const authUrl = await oauthService.generateAuthUrl(redirectUri, codeChallenge, state);
throw redirect(302, authUrl);
} catch (err) {
+15 -3
View File
@@ -26,17 +26,29 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
throw new Error('No authorization code received from OAuth provider');
}
// Retrieve the code_verifier from the cookie
// Retrieve the code_verifier and state from cookies
const codeVerifier = cookies.get('oauth_code_verifier');
if (!codeVerifier) {
throw new Error('OAuth session expired. Please try logging in again.');
}
// Clear the code_verifier cookie
const expectedState = cookies.get('oauth_state');
if (!expectedState) {
throw new Error('OAuth session expired. Please try logging in again.');
}
// Validate the state parameter matches to prevent CSRF
const returnedState = url.searchParams.get('state');
if (returnedState !== expectedState) {
throw new Error('OAuth state mismatch. Possible CSRF attack. Please try logging in again.');
}
// Clear the OAuth cookies
cookies.delete('oauth_code_verifier', { path: '/' });
cookies.delete('oauth_state', { path: '/' });
// Exchange the authorization code for tokens and get user info
const userInfo = await oauthService.handleCallback(url, codeVerifier);
const userInfo = await oauthService.handleCallback(url, codeVerifier, expectedState);
// Find or create local user from OAuth info
const user = await userService.findOrCreateByOAuth({
+15 -3
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { t } from 'svelte-i18n';
import type { PageData } from './$types.js';
import { invalidateAll } from '$app/navigation';
import Board from '$lib/components/board/Board.svelte';
import BoardHeader from '$lib/components/board/BoardHeader.svelte';
import BoardShareDialog from '$lib/components/board/BoardShareDialog.svelte';
@@ -8,16 +9,23 @@
let { data }: { data: PageData } = $props();
let showShareDialog = $state(false);
let guestToggleError = $state('');
async function handleGuestToggle(value: boolean) {
guestToggleError = '';
try {
await fetch(`/api/boards/${data.board.id}`, {
const res = await fetch(`/api/boards/${data.board.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isGuestAccessible: value })
});
} catch (err) {
console.error('Failed to update guest access:', err);
if (res.ok) {
await invalidateAll();
} else {
guestToggleError = 'Failed to update guest access';
}
} catch {
guestToggleError = 'Network error updating guest access';
}
}
</script>
@@ -37,6 +45,10 @@
onShare={() => { showShareDialog = true; }}
/>
{#if guestToggleError}
<p class="mb-2 text-sm text-destructive">{guestToggleError}</p>
{/if}
<Board sections={data.board.sections} allApps={data.allApps} />
</div>
</div>
@@ -6,12 +6,17 @@ import * as permissionService from '$lib/server/services/permissionService.js';
import * as userService from '$lib/server/services/userService.js';
import * as groupService from '$lib/server/services/groupService.js';
import { requireAuth } from '$lib/server/middleware/authenticate.js';
import { EntityType, PermissionLevel, UserRole } from '$lib/utils/constants.js';
import { EntityType, PermissionLevel, UserRole, WidgetType } from '$lib/utils/constants.js';
import {
updateBoardSchema,
createSectionSchema,
updateSectionSchema,
createWidgetSchema
createWidgetSchema,
appWidgetConfigSchema,
bookmarkWidgetConfigSchema,
noteWidgetConfigSchema,
embedWidgetConfigSchema,
statusWidgetConfigSchema
} from '$lib/utils/validators.js';
export const load: PageServerLoad = async (event) => {
@@ -214,6 +219,35 @@ export const actions: Actions = {
return { success: false, error: parsed.error.errors.map((e) => e.message).join(', ') };
}
// Validate config JSON against the type-specific schema
if (config && config !== '{}') {
let parsedConfig: unknown;
try {
parsedConfig = JSON.parse(config);
} catch {
return { success: false, error: 'Invalid config JSON' };
}
const configSchemaMap = {
[WidgetType.APP]: appWidgetConfigSchema,
[WidgetType.BOOKMARK]: bookmarkWidgetConfigSchema,
[WidgetType.NOTE]: noteWidgetConfigSchema,
[WidgetType.EMBED]: embedWidgetConfigSchema,
[WidgetType.STATUS]: statusWidgetConfigSchema
} as const;
const configSchema = configSchemaMap[type as keyof typeof configSchemaMap];
if (configSchema) {
const configResult = configSchema.safeParse(parsedConfig);
if (!configResult.success) {
return {
success: false,
error: configResult.error.errors.map((e) => e.message).join(', ')
};
}
}
}
try {
await boardService.createWidget(parsed.data);
return { success: true };
+13 -3
View File
@@ -11,6 +11,7 @@
let showAddSection = $state(false);
let addWidgetSectionId = $state<string | null>(null);
let errorMessage = $state('');
function handleToggleAddWidget(sectionId: string) {
addWidgetSectionId = addWidgetSectionId === sectionId ? null : sectionId;
@@ -27,7 +28,7 @@
});
await invalidateAll();
} catch (err) {
console.error('Failed to delete section:', err);
errorMessage = err instanceof Error ? err.message : 'Failed to delete section';
}
}
@@ -80,7 +81,7 @@
addWidgetSectionId = null;
await invalidateAll();
} catch (err) {
console.error('Failed to add widget:', err);
errorMessage = err instanceof Error ? err.message : 'Failed to add widget';
}
}
@@ -95,7 +96,7 @@
});
await invalidateAll();
} catch (err) {
console.error('Failed to delete widget:', err);
errorMessage = err instanceof Error ? err.message : 'Failed to delete widget';
}
}
</script>
@@ -106,6 +107,15 @@
<div class="p-6">
<div class="mx-auto max-w-4xl">
{#if errorMessage}
<div class="mb-4 rounded-lg border border-destructive bg-destructive/10 p-3">
<p class="text-sm text-destructive">{errorMessage}</p>
<button type="button" onclick={() => { errorMessage = ''; }} class="mt-1 text-xs text-destructive underline">
{$t('common.dismiss') ?? 'Dismiss'}
</button>
</div>
{/if}
<div class="mb-6 flex items-center justify-between">
<h1 class="text-2xl font-bold text-foreground">{$t('board.edit_board')}</h1>
<a