@octarq/plugin-links 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,552 @@
1
+ import {
2
+ Alert,
3
+ Empty,
4
+ Field,
5
+ PageShell,
6
+ PageCard,
7
+ Panel,
8
+ Button,
9
+ Input,
10
+ Skeleton,
11
+ StatCard,
12
+ StatusBadge,
13
+ Table,
14
+ THead,
15
+ TBody,
16
+ TR,
17
+ TH,
18
+ TD,
19
+ TabBar,
20
+ TableError,
21
+ TableSkeleton,
22
+ Textarea,
23
+ confirmDialog,
24
+ toast,
25
+ useTranslation,
26
+ roleSatisfies,
27
+ useCurrentRole,
28
+ usePluginGate,
29
+ } from "@octarq/plugin-sdk";
30
+ import { useCallback, useEffect, useMemo, useState } from "react";
31
+ import { useSearchParams } from "react-router-dom";
32
+ import { api, linksApi, Link, Domain, effectiveLinkHosts } from "../api";
33
+ import { AlertCircle, Download, Link2, Search, Settings, Plus, Activity, ShieldCheck, AlertTriangle } from "lucide-react";
34
+ import { parseLinksFilter, buildLinksFilterQuery } from "../filters";
35
+ import { LinkTableRow } from "./LinkTableRow";
36
+ import { LinkModals } from "./LinkModals";
37
+
38
+ export const SYSTEM_RESERVED_SLUGS = [
39
+ "admin",
40
+ "api",
41
+ "app",
42
+ "assets",
43
+ "auth",
44
+ "dashboard",
45
+ "docs",
46
+ "healthz",
47
+ "help",
48
+ "instance",
49
+ "login",
50
+ "logout",
51
+ "portal",
52
+ "settings",
53
+ "static",
54
+ "status",
55
+ "webhook",
56
+ ];
57
+
58
+ export default function LinksPage() {
59
+ const { role, isInstanceAdmin } = useCurrentRole();
60
+ const canDeleteLink = roleSatisfies("admin", role, isInstanceAdmin);
61
+ const [links, setLinks] = useState<Link[]>([]);
62
+ const [domains, setDomains] = useState<Domain[]>([]);
63
+ const [tab, setTab] = useState<"links" | "anomalies" | "reserved">("links");
64
+
65
+ const [searchParams, setSearchParams] = useSearchParams();
66
+ const { q, archived } = useMemo(() => parseLinksFilter(searchParams), [searchParams]);
67
+ const [searchInput, setSearchInput] = useState(q);
68
+
69
+ useEffect(() => {
70
+ setSearchInput(q);
71
+ }, [q]);
72
+
73
+ useEffect(() => {
74
+ const timer = setTimeout(() => {
75
+ if (searchInput !== q) {
76
+ setSearchParams(
77
+ (prev) => buildLinksFilterQuery({ q: searchInput, archived }, prev),
78
+ { replace: true },
79
+ );
80
+ }
81
+ }, 250);
82
+ return () => clearTimeout(timer);
83
+ }, [searchInput, archived, q, setSearchParams]);
84
+
85
+ const [createOpen, setCreateOpen] = useState(false);
86
+ const [editingLink, setEditingLink] = useState<Link | null>(null);
87
+ const [analyticsLink, setAnalyticsLink] = useState<Link | null>(null);
88
+ const [qrLink, setQrLink] = useState<Link | null>(null);
89
+
90
+ const [page, setPage] = useState(0);
91
+ const [hasMore, setHasMore] = useState(true);
92
+ const [loading, setLoading] = useState(false);
93
+ const [error, setError] = useState<{ detail?: string } | null>(null);
94
+ const [copiedId, setCopiedId] = useState<number | null>(null);
95
+ const [exporting, setExporting] = useState(false);
96
+ const { t } = useTranslation();
97
+ const pluginGate = usePluginGate();
98
+
99
+ const [reservedSlugs, setReservedSlugs] = useState("");
100
+ const [savingReserved, setSavingReserved] = useState(false);
101
+
102
+ const loadReserved = useCallback(async () => {
103
+ try {
104
+ const data = await linksApi.getSettings();
105
+ setReservedSlugs(data.reservedSlugs || "");
106
+ } catch {
107
+ }
108
+ }, []);
109
+
110
+ useEffect(() => {
111
+ if (tab === "reserved") {
112
+ void loadReserved();
113
+ }
114
+ }, [tab, loadReserved]);
115
+
116
+ const handleSaveReserved = async () => {
117
+ setSavingReserved(true);
118
+ try {
119
+ const res = await linksApi.updateSettings({ reservedSlugs });
120
+ setReservedSlugs(res.reservedSlugs || "");
121
+ toast.success(t("links.settingsSaved", "Settings saved"));
122
+ } catch (e: any) {
123
+ toast.error(e?.message || t("links.saveFailed", "Could not save settings; retry the request"));
124
+ } finally {
125
+ setSavingReserved(false);
126
+ }
127
+ };
128
+
129
+ const customReservedList = useMemo(() => {
130
+ return reservedSlugs
131
+ .split(/[\n,]/)
132
+ .map((s) => s.trim().toLowerCase())
133
+ .filter((s) => s.length > 0 && !SYSTEM_RESERVED_SLUGS.includes(s));
134
+ }, [reservedSlugs]);
135
+
136
+ const allReservedSlugs = useMemo(() => {
137
+ return [...SYSTEM_RESERVED_SLUGS, ...customReservedList];
138
+ }, [customReservedList]);
139
+
140
+ useEffect(() => {
141
+ if (searchParams.get("create") === "1") {
142
+ setCreateOpen(true);
143
+ setSearchParams(
144
+ (prev) => {
145
+ const next = new URLSearchParams(prev);
146
+ next.delete("create");
147
+ return next;
148
+ },
149
+ { replace: true },
150
+ );
151
+ }
152
+ }, [searchParams, setSearchParams]);
153
+
154
+ const linkHostOptions = Array.from(new Set(domains.flatMap(effectiveLinkHosts)));
155
+
156
+ async function loadMore(reset = false) {
157
+ if (loading || (!hasMore && !reset)) return;
158
+ setLoading(true);
159
+ if (reset) setError(null);
160
+ try {
161
+ const limit = 50;
162
+ const offset = reset ? 0 : page * limit;
163
+ const res = await linksApi.links({ q, archived, limit, offset });
164
+ if (res.length < limit) setHasMore(false);
165
+ else setHasMore(true);
166
+
167
+ setLinks((prev) => (reset ? res : [...prev, ...res]));
168
+ setPage(reset ? 1 : page + 1);
169
+ setError(null);
170
+ } catch (e: unknown) {
171
+ const err = e as { status?: number; message?: string };
172
+ if (err.status === 404 || err.status === 402) {
173
+ pluginGate.degrade(err.status);
174
+ return;
175
+ }
176
+ setError({ detail: err.status ? `HTTP ${err.status}` : err.message });
177
+ } finally {
178
+ setLoading(false);
179
+ }
180
+ }
181
+
182
+ useEffect(() => {
183
+ loadMore(true);
184
+ }, [q, archived]);
185
+
186
+ useEffect(() => {
187
+ api.domains().then(setDomains).catch(() => {});
188
+ }, []);
189
+
190
+ const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
191
+ const bottom =
192
+ e.currentTarget.scrollHeight - e.currentTarget.scrollTop <=
193
+ e.currentTarget.clientHeight + 100;
194
+ if (bottom) loadMore();
195
+ };
196
+
197
+ function linkURL(l: Link) {
198
+ return l.host ? `https://${l.host}/${l.slug}` : `${location.origin}/${l.slug}`;
199
+ }
200
+
201
+ const copy = (l: Link) => {
202
+ navigator.clipboard.writeText(linkURL(l));
203
+ setCopiedId(l.id);
204
+ setTimeout(() => setCopiedId(null), 2000);
205
+ };
206
+
207
+ const toggleArchive = async (l: Link) => {
208
+ try {
209
+ await linksApi.updateLink(l.id, { archived: !l.archived });
210
+ loadMore(true);
211
+ } catch {
212
+ toast.error(t("links.actionFailed"));
213
+ }
214
+ };
215
+
216
+ const handleDelete = async (l: Link) => {
217
+ if (!(await confirmDialog(t("links.confirmDelete", { slug: l.slug })))) return;
218
+ try {
219
+ await linksApi.deleteLink(l.id);
220
+ loadMore(true);
221
+ } catch {
222
+ toast.error(t("links.actionFailed"));
223
+ }
224
+ };
225
+
226
+ const handleExportCsv = async () => {
227
+ if (exporting) return;
228
+ setExporting(true);
229
+ try {
230
+ const blob = await linksApi.exportCsv();
231
+ const url = URL.createObjectURL(blob);
232
+ const a = document.createElement("a");
233
+ a.href = url;
234
+ a.download = "links.csv";
235
+ document.body.appendChild(a);
236
+ a.click();
237
+ a.remove();
238
+ URL.revokeObjectURL(url);
239
+ } catch {
240
+ toast.error(t("links.actionFailed"));
241
+ } finally {
242
+ setExporting(false);
243
+ }
244
+ };
245
+
246
+ const emptyStateOwnsCreate = tab === "links" && !error && !loading && links.length === 0 && !q;
247
+
248
+ return (
249
+ <PageShell
250
+ title={t("links.pageTitle")}
251
+ description={t("links.pageDescription")}
252
+ action={
253
+ emptyStateOwnsCreate ? undefined : (
254
+ <Button variant="primary" size="sm" onClick={() => setCreateOpen(true)}>
255
+ <Plus className="h-3.5 w-3.5" />
256
+ {t("links.newLink")}
257
+ </Button>
258
+ )
259
+ }
260
+ >
261
+
262
+ <TabBar
263
+ className="mb-6"
264
+ value={tab}
265
+ onValueChange={(v) => setTab(v as "links" | "anomalies" | "reserved")}
266
+ items={[
267
+ { value: "links", label: t("links.tabLinks", "Links"), testId: "tab-links" },
268
+ { value: "anomalies", label: t("links.tabAnomalies", "Anomaly Monitoring"), testId: "tab-anomalies" },
269
+ { value: "reserved", label: t("links.tabReserved", "Reserved Words"), testId: "tab-reserved" },
270
+ ]}
271
+ />
272
+
273
+ {tab === "links" && (
274
+ <div className="space-y-4" data-testid="links-projection-view">
275
+ <div className="flex flex-wrap items-center justify-between gap-3">
276
+ <div className="flex max-w-sm flex-1 items-center gap-2">
277
+ <div className="relative w-full">
278
+ <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
279
+ <Input
280
+ className="!pl-10"
281
+ aria-label={t("links.searchPlaceholder")}
282
+ placeholder={t("links.searchPlaceholder")}
283
+ value={searchInput}
284
+ onChange={(e) => setSearchInput(e.target.value)}
285
+ />
286
+ </div>
287
+ {searchInput && (
288
+ <Button variant="ghost" size="sm" onClick={() => setSearchInput("")}>
289
+ {t("links.emptyFilteredAction")}
290
+ </Button>
291
+ )}
292
+ </div>
293
+
294
+ <div className="flex items-center gap-2">
295
+ <Button variant="outline" size="sm" onClick={handleExportCsv} disabled={exporting}>
296
+ <Download className="h-3.5 w-3.5" />
297
+ {t("links.exportCsv")}
298
+ </Button>
299
+ <TabBar
300
+ size="sm"
301
+ value={archived ? "archived" : "active"}
302
+ onValueChange={(v) =>
303
+ setSearchParams((prev) => buildLinksFilterQuery({ q, archived: v === "archived" }, prev), { replace: true })
304
+ }
305
+ items={[
306
+ { value: "active", label: t("links.active") },
307
+ { value: "archived", label: t("links.archived") },
308
+ ]}
309
+ />
310
+ </div>
311
+ </div>
312
+
313
+ {error && links.length === 0 ? (
314
+ <TableError errorText={error.detail} onRetry={() => loadMore(true)} />
315
+ ) : loading && links.length === 0 ? (
316
+ <PageCard className="mt-0 overflow-hidden p-0">
317
+ <TableSkeleton columnsCount={5} rowsCount={8} ariaLabel={t("links.loading")} />
318
+ </PageCard>
319
+ ) : links.length === 0 ? (
320
+ q ? (
321
+ <PageCard className="mt-0 flex flex-col items-center gap-3 px-4 py-12 text-center">
322
+ <p className="text-sm text-muted-foreground">
323
+ {t("links.emptyFilteredReason")} <span className="font-mono text-foreground">{`“${q}”`}</span>
324
+ </p>
325
+ <Button
326
+ variant="ghost"
327
+ className="text-xs py-1.5"
328
+ onClick={() => setSearchParams((prev) => buildLinksFilterQuery({ q: "", archived: false }, prev), { replace: true })}
329
+ >
330
+ {t("links.emptyFilteredAction")}
331
+ </Button>
332
+ </PageCard>
333
+ ) : (
334
+ <Empty
335
+ reason={t("links.emptyNoLinksReason")}
336
+ detail={
337
+ linkHostOptions.length > 0 ? (
338
+ <>
339
+ {t("links.emptyNoLinksDetailPre")} <span className="font-mono">{`“${linkHostOptions.join(", ")}”`}</span>
340
+ </>
341
+ ) : (
342
+ <>
343
+ {t("links.emptyNoHostDetailPre")} <span className="font-mono">{`“${window.location.origin}”`}</span>
344
+ </>
345
+ )
346
+ }
347
+ action={
348
+ <Button variant="primary" className="mt-1 text-xs py-1.5" onClick={() => setCreateOpen(true)}>
349
+ {t("links.newLink")}
350
+ </Button>
351
+ }
352
+ >
353
+ <Link2 className="h-8 w-8 text-muted-foreground mb-1" />
354
+ </Empty>
355
+ )
356
+ ) : (
357
+ <>
358
+ <PageCard className="mt-0 overflow-hidden p-0">
359
+ <div className="overflow-x-auto max-h-[700px] overflow-y-auto" onScroll={handleScroll}>
360
+ <Table>
361
+ <THead className="border-b border-border bg-well">
362
+ <TR>
363
+ <TH className="min-w-[200px]">{t("links.pageTitle")}</TH>
364
+ <TH className="min-w-[240px]">{t("links.targetDestination")}</TH>
365
+ <TH className="w-24 text-center">{t("links.totalClicks")}</TH>
366
+ <TH className="w-24 text-center">{t("links.active")}</TH>
367
+ <TH className="text-right w-44" />
368
+ </TR>
369
+ </THead>
370
+ <TBody className="divide-y divide-border">
371
+ {links.map((l) => (
372
+ <LinkTableRow
373
+ key={l.id}
374
+ link={l}
375
+ isCopied={copiedId === l.id}
376
+ canDeleteLink={canDeleteLink}
377
+ onCopy={copy}
378
+ onAnalytics={setAnalyticsLink}
379
+ onQr={setQrLink}
380
+ onEdit={setEditingLink}
381
+ onToggleArchive={toggleArchive}
382
+ onDelete={handleDelete}
383
+ linkURL={linkURL}
384
+ />
385
+ ))}
386
+ {loading && (
387
+ <TR className="h-14" role="status" aria-busy="true" aria-label={t("links.loading")}>
388
+ <TD>
389
+ <div className="space-y-1.5">
390
+ <Skeleton className="h-4 w-36" />
391
+ <Skeleton className="h-3 w-24" />
392
+ </div>
393
+ </TD>
394
+ <TD>
395
+ <Skeleton className="h-3.5 w-48" />
396
+ </TD>
397
+ <TD className="text-center">
398
+ <Skeleton className="mx-auto h-5 w-10 rounded-full" />
399
+ </TD>
400
+ <TD className="text-center">
401
+ <Skeleton className="mx-auto h-5 w-16 rounded-full" />
402
+ </TD>
403
+ <TD className="text-right">
404
+ <Skeleton className="ml-auto h-4 w-28" />
405
+ </TD>
406
+ </TR>
407
+ )}
408
+ </TBody>
409
+ </Table>
410
+ </div>
411
+ </PageCard>
412
+ {error && (
413
+ <Alert
414
+ variant="danger"
415
+ icon={<AlertCircle className="h-4 w-4" />}
416
+ actions={
417
+ <Button variant="outline" size="sm" onClick={() => loadMore()}>
418
+ {t("proTable.retry")}
419
+ </Button>
420
+ }
421
+ >
422
+ {t("proTable.errorTitle")}
423
+ {error.detail ? ` (${error.detail})` : ""}
424
+ </Alert>
425
+ )}
426
+ </>
427
+ )}
428
+ </div>
429
+ )}
430
+
431
+ {tab === "anomalies" && (
432
+ <div className="space-y-6" data-testid="anomalies-projection-view">
433
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
434
+ <StatCard
435
+ label={t("links.anomalyTraffic", "Traffic Anomalies")}
436
+ value={0}
437
+ delta={t("links.anomalyHealthySpikes", "Healthy · No spikes")}
438
+ positive
439
+ icon={<Activity className="h-4 w-4 text-success-fg" />}
440
+ index={0}
441
+ />
442
+
443
+ <StatCard
444
+ label={t("links.anomalyBot", "Bot Filtering")}
445
+ value={t("links.anomalyActive", "Active")}
446
+ delta={t("links.anomalyRateLimitActive", "Rate limiting active")}
447
+ icon={<ShieldCheck className="h-4 w-4 text-accent-fg" />}
448
+ index={1}
449
+ />
450
+
451
+ <StatCard
452
+ label={t("links.anomalyLatency", "Redirect Latency")}
453
+ value={t("links.anomalyLatencyValue", "< 35ms")}
454
+ delta={t("links.anomalyP99Latency", "p99 edge redirect")}
455
+ positive
456
+ icon={<Activity className="h-4 w-4 text-info-fg" />}
457
+ index={2}
458
+ />
459
+
460
+ <StatCard
461
+ label={t("links.anomalyLoops", "Redirect Loops")}
462
+ value={0}
463
+ delta={t("links.anomalyLoopClear", "Loop detector clear")}
464
+ icon={<AlertTriangle className="h-4 w-4 text-warning-fg" />}
465
+ index={3}
466
+ />
467
+ </div>
468
+
469
+ <Panel
470
+ title={t("links.tabAnomalies", "Anomaly Monitoring")}
471
+ description={t("links.anomalyDesc", "Real-time monitors track 404 floods, redirect loops, and abnormal traffic spikes.")}
472
+ action={<StatusBadge tone="success" className="text-xs">{t("links.anomalyOperational", "Operational")}</StatusBadge>}
473
+ >
474
+
475
+ <div className="py-8 text-center space-y-2">
476
+ <ShieldCheck className="h-10 w-10 text-success-fg mx-auto opacity-80" />
477
+ <h4 className="text-sm font-medium text-foreground">{t("links.anomalyClean", "No anomalies detected across short links in the last 24 hours.")}</h4>
478
+ <p className="text-xs text-muted-foreground max-w-md mx-auto">
479
+ {t("links.anomalyDesc", "Real-time monitors track 404 floods, redirect loops, and abnormal traffic spikes.")}
480
+ </p>
481
+ </div>
482
+ </Panel>
483
+ </div>
484
+ )}
485
+
486
+ {tab === "reserved" && (
487
+ <div className="space-y-6" data-testid="reserved-projection-view">
488
+ <PageCard className="space-y-4">
489
+ <Field
490
+ label={t("links.customReservedLabel", "Custom Reserved Words")}
491
+ hint={t("links.customReservedHint", "Enter one reserved word per line. Short links cannot use these words.")}
492
+ >
493
+ <Textarea
494
+ className="font-mono text-xs"
495
+ rows={4}
496
+ value={reservedSlugs}
497
+ onChange={(e) => setReservedSlugs(e.target.value)}
498
+ placeholder={"preview\ninternal\nstatus"}
499
+ disabled={!isInstanceAdmin || savingReserved}
500
+ aria-label={t("links.customReservedLabel", "Custom Reserved Words")}
501
+ />
502
+ </Field>
503
+ {isInstanceAdmin && (
504
+ <div className="flex justify-end">
505
+ <Button
506
+ variant="primary"
507
+ className="text-xs"
508
+ onClick={handleSaveReserved}
509
+ disabled={savingReserved}
510
+ >
511
+ {savingReserved ? t("links.saving", "Saving…") : t("links.saveReserved", "Save reserved words")}
512
+ </Button>
513
+ </div>
514
+ )}
515
+ </PageCard>
516
+
517
+ <Panel
518
+ title={t("links.reservedTitle", "System Reserved Words")}
519
+ description={t("links.reservedDesc", "Reserved words prevent short links from colliding with system routes and administrative endpoints.")}
520
+ >
521
+ <div className="flex flex-wrap gap-2 pt-2">
522
+ {allReservedSlugs.map((slug) => (
523
+ <span
524
+ key={slug}
525
+ className="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-mono bg-well border border-border text-foreground"
526
+ >
527
+ /{slug}
528
+ </span>
529
+ ))}
530
+ </div>
531
+ </Panel>
532
+ </div>
533
+ )}
534
+
535
+ <LinkModals
536
+ createOpen={createOpen}
537
+ editingLink={editingLink}
538
+ analyticsLink={analyticsLink}
539
+ qrLink={qrLink}
540
+ linkHostOptions={linkHostOptions}
541
+ copiedId={copiedId}
542
+ onCloseCreate={() => setCreateOpen(false)}
543
+ onCloseEdit={() => setEditingLink(null)}
544
+ onCloseAnalytics={() => setAnalyticsLink(null)}
545
+ onCloseQr={() => setQrLink(null)}
546
+ onRefreshLinks={() => loadMore(true)}
547
+ onCopyQrLink={copy}
548
+ linkURL={linkURL}
549
+ />
550
+ </PageShell>
551
+ );
552
+ }
@@ -0,0 +1,129 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, it, expect, vi, beforeEach } from "vitest";
3
+ import { cleanup, render, screen, waitFor, fireEvent } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { registerUIPlugin, resetRegistry, I18nProvider } from "@octarq/plugin-sdk";
6
+ import linksPlugin from "../index";
7
+ import LinksPage from "./index";
8
+ import { Link } from "../api";
9
+
10
+ const mockLinksWithPassword: Link[] = [
11
+ {
12
+ id: 1,
13
+ host: "link.acme.com",
14
+ slug: "pass-protected",
15
+ title: "Protected Link",
16
+ tags: "secret",
17
+ target: "https://acme.com/secret",
18
+ note: "",
19
+ expiresAt: null,
20
+ expiredUrl: "",
21
+ clickLimit: 0,
22
+ archived: false,
23
+ enabled: true,
24
+ clicks: 5,
25
+ hasPassword: true,
26
+ routingRules: [],
27
+ createdAt: "2026-06-01T00:00:00Z",
28
+ },
29
+ ];
30
+
31
+ function jsonResponse(body: unknown, status = 200) {
32
+ return {
33
+ ok: status >= 200 && status < 300,
34
+ status,
35
+ json: async () => body,
36
+ headers: { get: (name: string) => (name === "content-type" ? "application/json" : null) },
37
+ };
38
+ }
39
+
40
+ describe("Link password redaction and edit preservation", () => {
41
+ let updatedPayload: any = null;
42
+
43
+ beforeEach(() => {
44
+ cleanup();
45
+ resetRegistry();
46
+ registerUIPlugin(linksPlugin);
47
+ updatedPayload = null;
48
+
49
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
50
+ const method = (init?.method ?? "GET").toUpperCase();
51
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
52
+ const urlObj = new URL(rawUrl, "http://localhost");
53
+ const path = urlObj.pathname;
54
+ if (method === "GET" && path === "/api/links") return jsonResponse(mockLinksWithPassword);
55
+ if (method === "GET" && path === "/api/domains") return jsonResponse([]);
56
+ if (method === "GET" && path === "/api/links/ai/status") return jsonResponse({ configured: false, provider: "" });
57
+ if (method === "GET" && path === "/api/links/capabilities") return jsonResponse({ geoReady: false, mode: "unavailable" });
58
+ if (method === "PUT" && path === "/api/links/1") {
59
+ updatedPayload = JSON.parse((init?.body as string) || "{}");
60
+ return jsonResponse({ ...mockLinksWithPassword[0], ...updatedPayload });
61
+ }
62
+ throw new Error(`unexpected request in test: ${method} ${rawUrl}`);
63
+ });
64
+ vi.stubGlobal("fetch", fetchMock);
65
+ });
66
+
67
+ it("hides plaintext password in table, uses type=password with blank value on edit, and omits password when left blank", async () => {
68
+ render(
69
+ <MemoryRouter initialEntries={["/links"]}>
70
+ <I18nProvider>
71
+ <LinksPage />
72
+ </I18nProvider>
73
+ </MemoryRouter>
74
+ );
75
+
76
+ await waitFor(() => {
77
+ const lockBadge = screen.getByTitle("Access protection password");
78
+ expect(lockBadge).toBeDefined();
79
+ expect(lockBadge.textContent?.trim()).toBe("");
80
+ });
81
+
82
+ const editBtn = screen.getByTitle("Edit link");
83
+ fireEvent.click(editBtn);
84
+
85
+ await waitFor(() => {
86
+ expect(screen.getByText("Edit link — Protected Link")).toBeDefined();
87
+ });
88
+
89
+ expect(screen.getByText("Key set. Fill to overwrite, blank to keep")).toBeDefined();
90
+ const passwordInput = screen.getByPlaceholderText("e.g. 123456") as HTMLInputElement;
91
+ expect(passwordInput.type).toBe("password");
92
+ expect(passwordInput.value).toBe("");
93
+
94
+ fireEvent.click(screen.getByText("Save link"));
95
+
96
+ await waitFor(() => {
97
+ expect(updatedPayload).not.toBeNull();
98
+ });
99
+ expect("password" in updatedPayload).toBe(false);
100
+ });
101
+
102
+ it("sends new password when filled on edit", async () => {
103
+ render(
104
+ <MemoryRouter initialEntries={["/links"]}>
105
+ <I18nProvider>
106
+ <LinksPage />
107
+ </I18nProvider>
108
+ </MemoryRouter>
109
+ );
110
+
111
+ await waitFor(() => {
112
+ expect(screen.getByTitle("Edit link")).toBeDefined();
113
+ });
114
+
115
+ fireEvent.click(screen.getByTitle("Edit link"));
116
+ await waitFor(() => {
117
+ expect(screen.getByText("Edit link — Protected Link")).toBeDefined();
118
+ });
119
+
120
+ const passwordInput = screen.getByPlaceholderText("e.g. 123456") as HTMLInputElement;
121
+ fireEvent.change(passwordInput, { target: { value: "NewSecret456" } });
122
+ fireEvent.click(screen.getByText("Save link"));
123
+
124
+ await waitFor(() => {
125
+ expect(updatedPayload).not.toBeNull();
126
+ });
127
+ expect(updatedPayload.password).toBe("NewSecret456");
128
+ });
129
+ });