10d30fc956
Comprehensive multi-area pass driven by a parallel 8-agent production
review. Frontend, backend, database, security, performance, operational,
plus a new self-monitoring feature.
## Critical fixes
- Planka webhook: reads bounded raw body (was NameError on every call)
- HA quiet hours: ha_state_changed/automation_triggered/service_called/
event_fired added to deferrable set (were silently dropped)
- DNS-rebinding SSRF: PinnedResolver wired into shared aiohttp session
- Telegram inbound webhook: secret now mandatory (401 without)
- Generic webhook: auth_mode="none" requires explicit
acknowledge_unauthenticated=true; per-IP rate limit 60/min
- svelte-check: 5 null-narrowing errors in EventDetailModal fixed
- Provider hardcoding: Immich-only block extracted to descriptor
featureDiscoveryHint
- command_sync: snapshot+expunge bot before exiting AsyncSession
## Bug fixes
- notifier asyncio.gather(return_exceptions=True) — one bad chat no longer
cancels peer sends
- NotificationDispatcher hoisted out of per-tracker loop
- Provider credential resolution unified across all 5 dispatch sites
- HA asyncio.shield now drains inner task on cancellation
- Provider construction switched from if/elif ladder to factory registry
- NUT first poll seeds silently (no spurious ups_on_battery)
- Quiet-hours gate: event-type-disabled now wins over deferral
- APScheduler drain job ID resolution upgraded to seconds
- HA on_status_change wired through to EventLog
- Webhook payload rollback failures now logged (not swallowed)
- Batched receivers/chats/bots in load_link_data (was per-target N+1)
- flag_modified on JSON column reassignments in deferred_dispatch
## Database
- UNIQUE indexes on service_provider.webhook_token,
telegram_bot.webhook_path_id, partial UNIQUE on telegram_bot.bot_id,
telegram_chat(bot_id, chat_id), notification_tracker_target unique link,
partial UNIQUE on bridge_self provider per user
- Composite ix_event_log_user_event_type_created index
- save_chat_from_webhook switched to ON CONFLICT DO UPDATE
- ondelete=CASCADE on user-id FKs (model annotation; app-side cascade
delete added for existing data)
- delete_notification_tracker converted from N+1 to bulk DELETE/UPDATE
- Module-level asyncio.Lock replaced with lazy _get_lock() pattern
- VACUUM INTO snapshot now PRAGMA integrity_check verified
## Performance
- Jinja2 template compilation LRU cached (lru_cache maxsize=512)
- Per-locale render cache in NotificationDispatcher (skips re-rendering
identical content for receivers sharing a locale)
- Tracker list cached per provider_id with 5s TTL + explicit invalidation
on tracker CRUD (relieves HA chat-bus rate query pressure)
- Nav-counts collapsed from 16 round-trips to single UNION ALL
- HA event_log: skip persisting empty assets_added/removed events
## Security hardening
- Mass-assignment guard on Action create/update; cron sub-minute reject
- Backup JSON depth/node-count cap (depth ≤ 10, nodes ≤ 100k)
- _sanitize_config extended to all JSON-typed fields on backup import
- Telegram _safe_get walks redirects manually with SSRF revalidation
- Bcrypt 72-byte password length cap with clear 422
- Webhook payload body redaction; sensitive substring set extended with
oauth/client_secret/webhook_secret/csrf in both header filter and
template extras filter
## Frontend
- 76 catch (err: any) sites converted to errMsg(err) helper
- globalProviderFilter: pure getter; reconciliation moved to one-time
$effect in +layout
- Provider-filter binding: removed paired $effects + _syncingFilter flag,
now one-way derived
- entity-cache: separate _refreshing flag for background re-fetches
- api.ts 401 handling: AuthRedirectError class + dedup _redirecting flag,
goto() instead of window.location.href
- a11y: aria-expanded on mobile More, role=switch + aria-checked on
Telegram bot toggles
## Tests & operations
- CI pytest gate added to .gitea/workflows/build.yml + release.yml
(wheel-built install to dodge editable-install slowness)
- /api/ready upgraded to deep healthcheck (db SELECT 1, scheduler.running,
HA supervisor presence) returning {ready, checks, errors, version}
- /api/metrics endpoint with prometheus_client (deferred_pending,
event_log_total, dispatch_duration, poll_failures, send_failures)
- New OPERATIONS.md covering deploy, healthchecks, metrics, backup/restore
procedures, log handling, common scenarios, upgrade flow
- New tests: test_bridge_self (11), test_gitea_parser (9),
test_planka_parser (6), test_immich_change_detector (6),
test_backup_roundtrip (1)
## New feature: bridge self-monitoring
- New bridge_self provider type — internal sink for bridge health events
- Three event types: bridge_self_poll_failures (consecutive tracker poll
failures), bridge_self_deferred_backlog (pending count crosses
threshold), bridge_self_target_failures (consecutive 5xx/network
failures per target)
- Per-user thresholds (defaults: 3 / 100 / 5) configurable via the
provider config form
- Auto-seeded on user create + /setup + boot backfill for existing users
- Anti-spam: counters reset after emission; backlog uses transition latch
- Self-loop guard: bridge_self failures don't count toward target-failure
thresholds (logged only) — wire to your own Telegram/Email/Matrix to
get notified when polls/dispatches/sends fail
- 6 default templates (3 events × 2 locales), tracking config columns
with backfill migration, frontend descriptor (excluded from "create
provider" wizard since auto-managed)
Operator-visible behavior changes (call out in release notes):
- NOTIFY_BRIDGE_TELEGRAM_WEBHOOK_SECRET now REQUIRED for webhook mode
- Existing webhook providers with auth_mode="none" need explicit opt-in
- Generic webhook endpoint rate-limited 60/min per source IP
- HA disconnect/reconnect writes ha_status_* EventLog rows
- Every user gets a bridge_self provider — wire it to a target to
receive failure alerts
Pre-existing test failures (test_ssrf, test_release_provider) on
Python 3.13 are unrelated; CI runs on 3.12.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
292 lines
13 KiB
Svelte
292 lines
13 KiB
Svelte
<script lang="ts">
|
|
import { slide } from 'svelte/transition';
|
|
import { t } from '$lib/i18n';
|
|
import Card from '$lib/components/Card.svelte';
|
|
import IconPicker from '$lib/components/IconPicker.svelte';
|
|
import Hint from '$lib/components/Hint.svelte';
|
|
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
|
import EntitySelect from '$lib/components/EntitySelect.svelte';
|
|
import MultiEntitySelect from '$lib/components/MultiEntitySelect.svelte';
|
|
import TagInput from '$lib/components/TagInput.svelte';
|
|
import { getDescriptor } from '$lib/providers';
|
|
|
|
interface Props {
|
|
form: {
|
|
name: string;
|
|
icon: string;
|
|
provider_id: number;
|
|
collection_ids: string[];
|
|
scan_interval: number;
|
|
adaptive_max_skip: number | null;
|
|
default_tracking_config_id: number;
|
|
default_template_config_id: number;
|
|
filters: Record<string, any>;
|
|
};
|
|
providerItems: { value: number; label: string; icon: string; desc: string }[];
|
|
collections: any[];
|
|
users?: { id: string; name: string }[];
|
|
collectionFilter?: string;
|
|
trackingConfigItems?: { value: number; label: string; icon: string }[];
|
|
templateConfigItems?: { value: number; label: string; icon: string }[];
|
|
editing: number | null;
|
|
submitting: boolean;
|
|
linkCheckLoading: boolean;
|
|
error: string;
|
|
providerType: string;
|
|
onsave: (e: SubmitEvent) => void;
|
|
ontoggleCollection?: (collectionId: string) => void;
|
|
formatDate?: (dateStr: string) => string;
|
|
onnameinput?: () => void;
|
|
}
|
|
|
|
let {
|
|
form = $bindable(),
|
|
providerItems,
|
|
collections,
|
|
users = [],
|
|
collectionFilter = $bindable(),
|
|
trackingConfigItems = [],
|
|
templateConfigItems = [],
|
|
editing,
|
|
submitting,
|
|
linkCheckLoading,
|
|
error,
|
|
providerType = '',
|
|
onsave,
|
|
ontoggleCollection,
|
|
formatDate,
|
|
onnameinput,
|
|
}: Props = $props();
|
|
|
|
let descriptor = $derived(getDescriptor(providerType));
|
|
let colMeta = $derived(descriptor?.collectionMeta);
|
|
// Providers without a collection (currently just the scheduler) drive the
|
|
// scheduler-specific form layout. Reading from the descriptor keeps the
|
|
// branch out of the component and lets a future provider opt in by
|
|
// declaring `collectionMeta: null`.
|
|
let isScheduler = $derived(colMeta == null);
|
|
let isWebhook = $derived(descriptor?.webhookBased ?? false);
|
|
|
|
/**
|
|
* Resolve `{tracking_config_id}` / `{template_config_id}` placeholders in a
|
|
* descriptor-declared CTA href. When the corresponding form field is unset
|
|
* (value 0), strip the entire `?edit=...` query so the link still goes to
|
|
* the list page. Centralising this here avoids per-provider href logic
|
|
* leaking back into the template.
|
|
*/
|
|
function resolveHintHref(href: string): string {
|
|
const tcId = form.default_tracking_config_id;
|
|
const tplId = form.default_template_config_id;
|
|
if (href.includes('{tracking_config_id}')) {
|
|
return tcId
|
|
? href.replace('{tracking_config_id}', String(tcId))
|
|
: href.split('?')[0];
|
|
}
|
|
if (href.includes('{template_config_id}')) {
|
|
return tplId
|
|
? href.replace('{template_config_id}', String(tplId))
|
|
: href.split('?')[0];
|
|
}
|
|
return href;
|
|
}
|
|
|
|
// Custom variable management for scheduler
|
|
function addVariable() {
|
|
const vars = { ...(form.filters.custom_variables || {}) };
|
|
const key = `var_${Object.keys(vars).length + 1}`;
|
|
vars[key] = '';
|
|
form.filters = { ...form.filters, custom_variables: vars };
|
|
}
|
|
function removeVariable(key: string) {
|
|
const vars = { ...(form.filters.custom_variables || {}) };
|
|
delete vars[key];
|
|
form.filters = { ...form.filters, custom_variables: vars };
|
|
}
|
|
function updateVariableKey(oldKey: string, newKey: string) {
|
|
if (!newKey || newKey === oldKey) return;
|
|
const vars = { ...(form.filters.custom_variables || {}) };
|
|
const val = vars[oldKey] ?? '';
|
|
delete vars[oldKey];
|
|
vars[newKey] = val;
|
|
form.filters = { ...form.filters, custom_variables: vars };
|
|
}
|
|
function updateVariableValue(key: string, value: string) {
|
|
const vars = { ...(form.filters.custom_variables || {}) };
|
|
vars[key] = value;
|
|
form.filters = { ...form.filters, custom_variables: vars };
|
|
}
|
|
</script>
|
|
|
|
<div in:slide={{ duration: 200 }}>
|
|
<Card class="mb-6">
|
|
{#if error}<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>{/if}
|
|
<form onsubmit={onsave} class="space-y-4">
|
|
<div>
|
|
<label for="trk-name" class="block text-sm font-medium mb-1">{t('notificationTracker.name')}</label>
|
|
<div class="flex gap-2">
|
|
<IconPicker value={form.icon} onselect={(v: string) => form.icon = v} />
|
|
<input id="trk-name" bind:value={form.name} oninput={() => onnameinput?.()} required placeholder={t('notificationTracker.namePlaceholder')} class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<div class="block text-sm font-medium mb-1">{t('notificationTracker.server')}</div>
|
|
<EntitySelect items={providerItems} bind:value={form.provider_id} placeholder={t('notificationTracker.selectServer')} />
|
|
</div>
|
|
{#if !isScheduler && colMeta && collections.length > 0}
|
|
<div>
|
|
<div class="block text-sm font-medium mb-1">{t(colMeta.label)}</div>
|
|
<MultiEntitySelect
|
|
items={collections.map(col => ({
|
|
value: col.id,
|
|
label: col.albumName || col.name,
|
|
icon: colMeta.icon,
|
|
desc: colMeta.desc(col),
|
|
}))}
|
|
bind:values={form.collection_ids}
|
|
placeholder={t(colMeta.placeholder)}
|
|
/>
|
|
</div>
|
|
{/if}
|
|
|
|
{#if descriptor?.userFilters && descriptor.userFilters.length > 0}
|
|
{@const userItems = users.map(u => ({ value: u.id, label: u.name }))}
|
|
{#each descriptor.userFilters as uf (uf.key)}
|
|
{@const filterKey = uf.filterKey ?? uf.key}
|
|
<div>
|
|
<div class="block text-sm font-medium mb-1">{t(uf.label)}</div>
|
|
{#if uf.inputMode === 'tags'}
|
|
<TagInput
|
|
values={form.filters[filterKey] || []}
|
|
onchange={(vals) => form.filters = { ...form.filters, [filterKey]: vals }}
|
|
placeholder={t(uf.placeholder)}
|
|
icon={uf.icon}
|
|
/>
|
|
{:else}
|
|
<MultiEntitySelect
|
|
items={userItems.map(i => ({ ...i, icon: uf.icon }))}
|
|
values={form.filters[filterKey] || []}
|
|
onchange={(vals) => form.filters = { ...form.filters, [filterKey]: vals }}
|
|
placeholder={t(uf.placeholder)}
|
|
/>
|
|
{/if}
|
|
</div>
|
|
{/each}
|
|
{/if}
|
|
|
|
{#if isScheduler}
|
|
<!-- Schedule type -->
|
|
<fieldset class="border border-[var(--color-border)] rounded-md p-3">
|
|
<legend class="text-sm font-medium px-1">{t('notificationTracker.scheduleType')}</legend>
|
|
<div class="flex gap-4 mt-1">
|
|
<label class="flex items-center gap-2 text-sm">
|
|
<input type="radio" name="schedule_type" value="interval"
|
|
checked={!form.filters.schedule_type || form.filters.schedule_type === 'interval'}
|
|
onchange={() => form.filters = { ...form.filters, schedule_type: 'interval' }} />
|
|
{t('notificationTracker.intervalMode')}
|
|
</label>
|
|
<label class="flex items-center gap-2 text-sm">
|
|
<input type="radio" name="schedule_type" value="cron"
|
|
checked={form.filters.schedule_type === 'cron'}
|
|
onchange={() => form.filters = { ...form.filters, schedule_type: 'cron' }} />
|
|
{t('notificationTracker.cronMode')}
|
|
</label>
|
|
</div>
|
|
{#if form.filters.schedule_type === 'cron'}
|
|
<div class="mt-3">
|
|
<label for="trk-cron" class="block text-xs mb-1">{t('notificationTracker.cronExpression')}</label>
|
|
<input id="trk-cron" value={form.filters.cron_expression || ''}
|
|
oninput={(e) => form.filters = { ...form.filters, cron_expression: (e.target as HTMLInputElement).value }}
|
|
placeholder="0 9 * * 1-5" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
|
|
<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('notificationTracker.cronHint')}</p>
|
|
</div>
|
|
{:else}
|
|
<div class="mt-3">
|
|
<label for="trk-interval" class="block text-xs mb-1">{t('notificationTracker.scanInterval')}<Hint text={t('hints.scanInterval')} /></label>
|
|
<input id="trk-interval" type="number" bind:value={form.scan_interval} min="60" max="86400" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
</div>
|
|
{/if}
|
|
</fieldset>
|
|
|
|
<!-- Custom variables -->
|
|
<fieldset class="border border-[var(--color-border)] rounded-md p-3">
|
|
<legend class="text-sm font-medium px-1">{t('notificationTracker.customVariables')}</legend>
|
|
<p class="text-xs text-[var(--color-muted-foreground)] mb-2">{t('notificationTracker.customVariablesHint')}</p>
|
|
{#each Object.entries(form.filters.custom_variables || {}) as [key, value]}
|
|
<div class="flex gap-2 mb-2 items-center">
|
|
<input value={key} onblur={(e) => updateVariableKey(key, (e.target as HTMLInputElement).value)}
|
|
placeholder="key" class="w-1/3 px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
|
|
<input value={value} oninput={(e) => updateVariableValue(key, (e.target as HTMLInputElement).value)}
|
|
placeholder="value" class="flex-1 px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
<button type="button" onclick={() => removeVariable(key)}
|
|
class="text-[var(--color-error-fg)] hover:opacity-70 text-sm px-1">✕</button>
|
|
</div>
|
|
{/each}
|
|
<button type="button" onclick={addVariable}
|
|
class="text-xs text-[var(--color-primary)] hover:underline mt-1">+ {t('notificationTracker.addVariable')}</button>
|
|
</fieldset>
|
|
{:else}
|
|
{#if !isWebhook}
|
|
<div class="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label for="trk-interval" class="block text-sm font-medium mb-1">{t('notificationTracker.scanInterval')}<Hint text={t('hints.scanInterval')} /></label>
|
|
<input id="trk-interval" type="number" bind:value={form.scan_interval} min="10" max="3600" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
</div>
|
|
<div>
|
|
<label for="trk-adaptive" class="block text-sm font-medium mb-1">{t('notificationTracker.adaptiveMaxSkip')}<Hint text={t('hints.adaptiveMaxSkip')} /></label>
|
|
<input id="trk-adaptive" type="number" bind:value={form.adaptive_max_skip} min="0" max="10" placeholder={t('notificationTracker.adaptiveMaxSkipPlaceholder')} class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
</div>
|
|
</div>
|
|
{/if}
|
|
{/if}
|
|
|
|
<!-- Default configs -->
|
|
{#if trackingConfigItems.length > 0 || templateConfigItems.length > 0}
|
|
<div class="grid grid-cols-2 gap-3">
|
|
{#if trackingConfigItems.length > 0}
|
|
<div>
|
|
<label class="block text-sm font-medium mb-1">{t('notificationTracker.defaultTrackingConfig')}<Hint text={t('hints.defaultTrackingConfig')} /></label>
|
|
<EntitySelect items={[{value: 0, label: t('common.none'), icon: 'mdiMinus'}, ...trackingConfigItems]} bind:value={form.default_tracking_config_id} placeholder={t('common.none')} />
|
|
</div>
|
|
{/if}
|
|
{#if templateConfigItems.length > 0}
|
|
<div>
|
|
<label class="block text-sm font-medium mb-1">{t('notificationTracker.defaultTemplateConfig')}<Hint text={t('hints.defaultTemplateConfig')} /></label>
|
|
<EntitySelect items={[{value: 0, label: t('common.none'), icon: 'mdiMinus'}, ...templateConfigItems]} bind:value={form.default_template_config_id} placeholder={t('common.none')} />
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
|
|
<!-- Feature discovery: the periodic/scheduled/memory/quiet-hours controls
|
|
live on the tracking config, not on the tracker itself. The hint
|
|
content (message + CTAs) is declared on the provider descriptor so
|
|
each provider can surface its own discoverability links without
|
|
embedding `if (type === 'xyz')` here. -->
|
|
{#if descriptor?.featureDiscoveryHint}
|
|
{@const hint = descriptor.featureDiscoveryHint}
|
|
<div class="flex items-start gap-2 rounded-md border border-[var(--color-border)] bg-[var(--color-muted)]/30 px-3 py-2">
|
|
<span style="color: var(--color-primary);"><MdiIcon name="mdiInformationOutline" size={16} /></span>
|
|
<div class="flex-1 text-xs">
|
|
<p style="color: var(--color-muted-foreground);">{t(hint.messageKey)}</p>
|
|
{#if hint.ctas && hint.ctas.length > 0}
|
|
<div class="flex flex-wrap gap-x-4 gap-y-1 mt-1">
|
|
{#each hint.ctas as cta}
|
|
<a href={resolveHintHref(cta.href)}
|
|
class="inline-flex items-center gap-1 text-[var(--color-primary)] hover:underline">
|
|
<MdiIcon name={cta.icon ?? 'mdiArrowRight'} size={12} />
|
|
{t(cta.labelKey)}
|
|
</a>
|
|
{/each}
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
{/if}
|
|
|
|
<button type="submit" disabled={submitting || linkCheckLoading} class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">
|
|
{#if linkCheckLoading}{t('notificationTracker.checkingLinks')}{:else}{editing ? t('common.save') : t('notificationTracker.createTracker')}{/if}
|
|
</button>
|
|
</form>
|
|
</Card>
|
|
</div>
|