@octarq/plugin-links 0.1.0 → 0.2.1

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.
package/api.ts CHANGED
@@ -1,88 +1,5 @@
1
- // Links feature API surface — the slice of the JSON API owned by the links
2
- // plugin. Fully self-contained without relative host leaks.
3
- import type { StatKV } from "@octarq/plugin-sdk";
1
+ import { getAppLang, pluginURL, req, type StatKV } from "@octarq/plugin-sdk";
4
2
 
5
- export class ApiError extends Error {
6
- status: number;
7
- body?: any;
8
- requestId?: string;
9
- constructor(status: number, message: string, body?: any, requestId?: string) {
10
- super(message);
11
- this.status = status;
12
- this.body = body;
13
- this.requestId = requestId;
14
- }
15
- }
16
-
17
- export function getAppLang(): string {
18
- try {
19
- const saved = localStorage.getItem("lang");
20
- if (saved) return saved;
21
- } catch {
22
- /* ignore */
23
- }
24
- return typeof navigator !== "undefined" ? navigator.language || "en" : "en";
25
- }
26
-
27
- interface ErrorEnvelope {
28
- message?: string;
29
- error?: string;
30
- detail?: string;
31
- details?: Array<string | { location?: string; message?: string }>;
32
- }
33
-
34
- export async function req<T>(method: string, path: string, body?: unknown, lang?: string): Promise<T> {
35
- const currentLang = lang || getAppLang();
36
- const headers: Record<string, string> = {
37
- "Accept-Language": currentLang,
38
- };
39
- if (body) {
40
- headers["Content-Type"] = "application/json";
41
- }
42
- const res = await fetch(path, {
43
- method,
44
- headers,
45
- body: body ? JSON.stringify(body) : undefined,
46
- });
47
- if (!res.ok) {
48
- let msg = res.statusText;
49
- let parsed: ErrorEnvelope | null = null;
50
- try {
51
- parsed = (await res.json()) as ErrorEnvelope;
52
- if (parsed?.message) {
53
- msg = parsed.message;
54
- if (parsed.details && Array.isArray(parsed.details) && parsed.details.length > 0) {
55
- const detailMsgs = parsed.details
56
- .map((d) => {
57
- if (typeof d === "string") return d;
58
- if (d?.message) {
59
- const loc = d.location ? `${d.location.replace(/^body\./, "")}: ` : "";
60
- return `${loc}${d.message}`;
61
- }
62
- return "";
63
- })
64
- .filter(Boolean)
65
- .join("; ");
66
- if (detailMsgs) msg = `${msg} (${detailMsgs})`;
67
- }
68
- } else if (parsed?.error) {
69
- msg = parsed.error;
70
- } else if (parsed?.detail) {
71
- msg = parsed.detail;
72
- }
73
- } catch {
74
- // Non-JSON error body: fall through to statusText.
75
- }
76
- const requestId = res.headers.get("x-request-id") || undefined;
77
- throw new ApiError(res.status, msg || `HTTP ${res.status}`, parsed, requestId);
78
- }
79
- if (res.status === 204) return undefined as unknown as T;
80
- const contentType = res.headers.get("content-type");
81
- if (contentType && contentType.includes("application/json")) {
82
- return (await res.json()) as T;
83
- }
84
- return (await res.text()) as unknown as T;
85
- }
86
3
 
87
4
  export type { StatKV };
88
5
 
@@ -117,7 +34,6 @@ export function effectiveLinkHosts(d: Domain | { hosts?: string[]; linkHosts?: H
117
34
 
118
35
  export interface Overview extends Record<string, unknown> {
119
36
  tokens?: number;
120
- includeBot?: boolean;
121
37
  links?: number;
122
38
  activeLinks?: number;
123
39
  domains?: number;
@@ -153,7 +69,6 @@ export interface Link {
153
69
  archived: boolean;
154
70
  enabled: boolean;
155
71
  clicks: number;
156
- password?: string;
157
72
  hasPassword: boolean;
158
73
  routingRules?: any[];
159
74
  createdAt: string;
@@ -182,7 +97,28 @@ export interface LinksCapabilities {
182
97
  mode: "configured" | "unavailable";
183
98
  }
184
99
 
100
+ export const linksAiStatus = () => req<{ configured: boolean; provider: string }>("GET", "/api/links/ai/status");
101
+ export const suggestLinkSlug = (target: string, title?: string) =>
102
+ req<{ slugs: string[] }>("POST", "/api/links/ai/suggest-slug", { target, title });
103
+
104
+ export interface AbuseReport {
105
+ id: number;
106
+ slug: string;
107
+ target: string;
108
+ reason: "spam" | "phishing" | "malware" | "other" | string;
109
+ description: string;
110
+ reporterIp: string;
111
+ status: "open" | "reviewed" | "dismissed" | string;
112
+ createdAt: string;
113
+ }
114
+
115
+ export interface LinksSettingsData {
116
+ reservedSlugs: string;
117
+ }
118
+
185
119
  export const linksApi = {
120
+ getSettings: () => req<LinksSettingsData>("GET", "/api/links/settings"),
121
+ updateSettings: (s: LinksSettingsData) => req<LinksSettingsData>("PUT", "/api/links/settings", s),
186
122
  links: (params: { q?: string; tag?: string; host?: string; archived?: boolean; limit?: number; offset?: number } = {}) => {
187
123
  const sp = new URLSearchParams();
188
124
  if (params.q) sp.set("q", params.q);
@@ -198,6 +134,16 @@ export const linksApi = {
198
134
  updateLink: (id: number, l: Partial<Link> & { password?: string }) =>
199
135
  req<Link>("PUT", `/api/links/${id}`, l),
200
136
  deleteLink: (id: number) => req("DELETE", `/api/links/${id}`),
137
+ exportCsv: async (): Promise<Blob> => {
138
+ const res = await fetch(pluginURL("/api/links/export.csv"), {
139
+ credentials: "same-origin",
140
+ headers: { "Accept-Language": getAppLang() },
141
+ });
142
+ if (!res.ok) {
143
+ throw new Error(`HTTP ${res.status}`);
144
+ }
145
+ return res.blob();
146
+ },
201
147
  linkStats: (id: number, days = 30, metric: "pv" | "uv" = "uv") =>
202
148
  req<LinkStats>("GET", `/api/links/${id}/stats?days=${days}&metric=${metric}`),
203
149
  linkMetadata: (url: string) =>
@@ -214,10 +160,15 @@ export const linksApi = {
214
160
  const qs = sp.toString();
215
161
  return req<Domain[]>("GET", `/api/domains${qs ? `?${qs}` : ""}`);
216
162
  },
217
- overview: (includeBot = false) => req<Overview>("GET", `/api/overview?include_bot=${includeBot}`),
218
- aiAssistStatus: () => req<{ configured: boolean; provider: string }>("GET", "/api/ai/assist/status"),
219
- aiSuggestSlug: (target: string, title?: string) =>
220
- req<{ slugs: string[] }>("POST", "/api/ai/assist/suggest-slug", { target, title }),
163
+ overview: () => req<Overview>("GET", "/api/overview"),
164
+ linksAiStatus,
165
+ suggestLinkSlug,
166
+ abuseReports: (status?: string) => {
167
+ const qs = status ? `?status=${encodeURIComponent(status)}` : "";
168
+ return req<AbuseReport[]>("GET", `/api/links/abuse${qs}`);
169
+ },
170
+ updateAbuseReport: (id: number, status: string) =>
171
+ req<AbuseReport>("PUT", `/api/links/abuse/${id}`, { status }),
221
172
  };
222
173
 
223
174
  export { linksApi as api };
package/filters.test.ts CHANGED
@@ -3,37 +3,29 @@ import { parseLinksFilter, buildLinksFilterQuery } from "./filters";
3
3
 
4
4
  describe("Links url-backed filters pure functions", () => {
5
5
  it("1. parses query params correctly and defaults empty query to defaults", () => {
6
- // Non-empty query
7
6
  const parsed = parseLinksFilter("?q=promo&archived=1");
8
7
  expect(parsed).toEqual({ q: "promo", archived: true });
9
8
 
10
- // Empty query
11
9
  const defaultParsed = parseLinksFilter("");
12
10
  expect(defaultParsed).toEqual({ q: "", archived: false });
13
11
 
14
- // Query with only search term
15
12
  const searchOnly = parseLinksFilter("?q=hello");
16
13
  expect(searchOnly).toEqual({ q: "hello", archived: false });
17
14
 
18
- // Query with archived=0
19
15
  const archivedZero = parseLinksFilter("?archived=0");
20
16
  expect(archivedZero).toEqual({ q: "", archived: false });
21
17
  });
22
18
 
23
19
  it("2. serializes filter values to query without including default values", () => {
24
- // Default values: q is empty, archived is false -> query should be empty
25
20
  const queryDefault = buildLinksFilterQuery({ q: "", archived: false });
26
21
  expect(queryDefault.toString()).toBe("");
27
22
 
28
- // Only search term
29
23
  const querySearch = buildLinksFilterQuery({ q: "promo", archived: false });
30
24
  expect(querySearch.toString()).toBe("q=promo");
31
25
 
32
- // Only archived
33
26
  const queryArchived = buildLinksFilterQuery({ q: "", archived: true });
34
27
  expect(queryArchived.toString()).toBe("archived=1");
35
28
 
36
- // Both
37
29
  const queryBoth = buildLinksFilterQuery({ q: "promo", archived: true });
38
30
  expect(queryBoth.toString()).toBe("q=promo&archived=1");
39
31
  });
@@ -58,7 +50,6 @@ describe("Links url-backed filters pure functions", () => {
58
50
  expect(updated.get("q")).toBe("promo");
59
51
  expect(updated.get("archived")).toBe("1");
60
52
 
61
- // Deleting filters should keep create=1
62
53
  const cleaned = buildLinksFilterQuery({ q: "", archived: false }, updated);
63
54
  expect(cleaned.get("create")).toBe("1");
64
55
  expect(cleaned.get("foo")).toBe("bar");
package/i18n.ts CHANGED
@@ -1,16 +1,14 @@
1
1
  export const linksI18n = {
2
2
  en: {
3
- // Shared-namespace contribution: this plugin's description in the
4
- // plugin manager (core chrome looks up settings.pluginDesc.links).
5
3
  _shared: { settings: { pluginDesc: { links: "Short link creation, custom domain routing, and click analytics." } } },
6
4
  pageTitle: "Links",
7
5
  pageDescription: "Short links with click analytics, redirection, and routing",
8
6
  newLink: "New link",
7
+ exportCsv: "Export CSV",
9
8
  searchPlaceholder: "Search links…",
10
9
  toggleArchivedTitle: "Toggle archived view",
11
10
  archived: "Archived",
12
11
  active: "Active",
13
- // Query/hosts render beside these keys in mono — keep them out of the sentence.
14
12
  emptyFilteredReason: "No links match",
15
13
  emptyFilteredAction: "Clear search",
16
14
  emptyNoLinksReason: "This workspace has no short links yet.",
@@ -146,12 +144,37 @@ export const linksI18n = {
146
144
  reservedDesc: "Reserved words prevent short links from colliding with system routes and administrative endpoints.",
147
145
  reservedInstanceNotice: "Configure custom instance-level reserved slugs in Instance Settings.",
148
146
  reservedInstanceAction: "Configure Instance Settings →",
147
+ abuse: {
148
+ pageTitle: "Abuse reports",
149
+ pageDesc: "Manage reports of spam or malicious links",
150
+ loading: "Loading…",
151
+ emptyState: "No abuse reports. Reported links display here.",
152
+ target: "Target:",
153
+ ip: "IP: {{ip}}",
154
+ noDescription: "No description provided.",
155
+ dismissSafe: "Dismiss (safe)",
156
+ markReviewed: "Mark as reviewed",
157
+ updateFailed: "Could not update report status: {{error}}. Try again.",
158
+ filterOpen: "Open",
159
+ filterReviewed: "Reviewed",
160
+ filterDismissed: "Dismissed",
161
+ filterAll: "All",
162
+ reasonSpam: "Spam",
163
+ reasonPhishing: "Phishing",
164
+ reasonMalware: "Malware",
165
+ reasonOther: "Other",
166
+ },
167
+ customReservedLabel: "Custom Reserved Words",
168
+ customReservedHint: "Enter one reserved word per line. Short links cannot use these words.",
169
+ saveReserved: "Save reserved words",
170
+ settingsSaved: "Settings saved",
149
171
  },
150
172
  zh: {
151
173
  _shared: { settings: { pluginDesc: { links: "短链生成、自定义域名路由与点击数据分析。" } } },
152
174
  pageTitle: "短链",
153
175
  pageDescription: "带点击分析、跳转与路由的短链",
154
176
  newLink: "新建短链",
177
+ exportCsv: "导出 CSV",
155
178
  searchPlaceholder: "搜索短链…",
156
179
  toggleArchivedTitle: "切换归档视图",
157
180
  archived: "已归档",
@@ -291,12 +314,37 @@ export const linksI18n = {
291
314
  reservedDesc: "保留字用于防止短链接路径与系统内置路由产生冲突。",
292
315
  reservedInstanceNotice: "可在实例设置中配置自定义全局保留词。",
293
316
  reservedInstanceAction: "配置实例设置 →",
317
+ abuse: {
318
+ pageTitle: "滥用举报",
319
+ pageDesc: "管理垃圾信息或恶意链接的举报",
320
+ loading: "加载中…",
321
+ emptyState: "暂无滥用举报。被举报的链接在此显示。",
322
+ target: "目标:",
323
+ ip: "IP:{{ip}}",
324
+ noDescription: "未提供描述。",
325
+ dismissSafe: "忽略(安全)",
326
+ markReviewed: "标记为已审核",
327
+ updateFailed: "无法更新举报状态:{{error}}。请重试。",
328
+ filterOpen: "待处理",
329
+ filterReviewed: "已审核",
330
+ filterDismissed: "已忽略",
331
+ filterAll: "全部",
332
+ reasonSpam: "垃圾信息/链接",
333
+ reasonPhishing: "钓鱼链接",
334
+ reasonMalware: "恶意软件",
335
+ reasonOther: "其它",
336
+ },
337
+ customReservedLabel: "自定义保留词",
338
+ customReservedHint: "每行输入一个保留词。短链接不能使用这些词。",
339
+ saveReserved: "保存保留词",
340
+ settingsSaved: "设置已保存",
294
341
  },
295
342
  es: {
296
343
  _shared: { settings: { pluginDesc: { links: "Creación de enlaces cortos, enrutamiento de dominio personalizado y análisis de clics." } } },
297
344
  pageTitle: "Enlaces",
298
345
  pageDescription: "Enlaces cortos con análisis de clics, redirección y enrutamiento",
299
346
  newLink: "Nuevo enlace",
347
+ exportCsv: "Exportar CSV",
300
348
  searchPlaceholder: "Buscar enlaces…",
301
349
  toggleArchivedTitle: "Alternar vista archivada",
302
350
  archived: "Archivado",
@@ -436,12 +484,37 @@ export const linksI18n = {
436
484
  reservedDesc: "Las palabras reservadas evitan colisiones con rutas del sistema.",
437
485
  reservedInstanceNotice: "Configure palabras reservadas personalizadas en Ajustes de Instancia.",
438
486
  reservedInstanceAction: "Configurar Ajustes de Instancia →",
487
+ abuse: {
488
+ pageTitle: "Reportes de abuso",
489
+ pageDesc: "Gestionar reportes de spam o enlaces maliciosos",
490
+ loading: "Cargando…",
491
+ emptyState: "No hay reportes de abuso. Los enlaces reportados se muestran aquí.",
492
+ target: "Objetivo:",
493
+ ip: "IP: {{ip}}",
494
+ noDescription: "No se proporcionó descripción.",
495
+ dismissSafe: "Descartar (seguro)",
496
+ markReviewed: "Marcar como revisado",
497
+ updateFailed: "No se pudo actualizar el estado del reporte: {{error}}. Reintenta.",
498
+ filterOpen: "Abierto",
499
+ filterReviewed: "Revisado",
500
+ filterDismissed: "Descartado",
501
+ filterAll: "Todos",
502
+ reasonSpam: "Spam",
503
+ reasonPhishing: "Phishing",
504
+ reasonMalware: "Malware",
505
+ reasonOther: "Otro",
506
+ },
507
+ customReservedLabel: "Palabras reservadas personalizadas",
508
+ customReservedHint: "Ingresa una palabra reservada por línea. Los enlaces cortos no pueden usar estas palabras.",
509
+ saveReserved: "Guardar palabras reservadas",
510
+ settingsSaved: "Ajustes guardados",
439
511
  },
440
512
  pt: {
441
513
  _shared: { settings: { pluginDesc: { links: "Criação de links curtos, roteamento de domínio personalizado e análise de cliques." } } },
442
514
  pageTitle: "Links",
443
515
  pageDescription: "Links curtos com análise de cliques, redirecionamento e roteamento",
444
516
  newLink: "Novo link",
517
+ exportCsv: "Exportar CSV",
445
518
  searchPlaceholder: "Pesquisar links…",
446
519
  toggleArchivedTitle: "Alternar visualização arquivada",
447
520
  archived: "Arquivado",
@@ -581,12 +654,37 @@ export const linksI18n = {
581
654
  reservedDesc: "Palavras reservadas evitam colisões com rotas do sistema.",
582
655
  reservedInstanceNotice: "Configure palavras reservadas personalizadas nas Configurações da Instância.",
583
656
  reservedInstanceAction: "Configurar Instância →",
657
+ abuse: {
658
+ pageTitle: "Relatórios de abuso",
659
+ pageDesc: "Gerencie relatórios de spam ou links maliciosos",
660
+ loading: "Carregando…",
661
+ emptyState: "Nenhum relatório de abuso. Os links reportados são exibidos aqui.",
662
+ target: "Alvo:",
663
+ ip: "IP: {{ip}}",
664
+ noDescription: "Nenhuma descrição fornecida.",
665
+ dismissSafe: "Ignorar (seguro)",
666
+ markReviewed: "Marcar como revisado",
667
+ updateFailed: "Não foi possível atualizar o status do relatório: {{error}}. Tente novamente.",
668
+ filterOpen: "Abertos",
669
+ filterReviewed: "Revisados",
670
+ filterDismissed: "Ignorados",
671
+ filterAll: "Todos",
672
+ reasonSpam: "Spam",
673
+ reasonPhishing: "Phishing",
674
+ reasonMalware: "Malware",
675
+ reasonOther: "Outro",
676
+ },
677
+ customReservedLabel: "Palavras reservadas personalizadas",
678
+ customReservedHint: "Digite uma palavra reservada por linha. Links curtos não podem usar essas palavras.",
679
+ saveReserved: "Salvar palavras reservadas",
680
+ settingsSaved: "Configurações salvas",
584
681
  },
585
682
  ja: {
586
683
  _shared: { settings: { pluginDesc: { links: "短縮リンクの作成、カスタムドメインルーティング、クリック分析。" } } },
587
684
  pageTitle: "短縮リンク",
588
685
  pageDescription: "クリック分析、リダイレクト、ルーティング機能を備えた短縮リンク",
589
686
  newLink: "新規リンク",
687
+ exportCsv: "CSV エクスポート",
590
688
  searchPlaceholder: "リンクを検索…",
591
689
  toggleArchivedTitle: "アーカイブ表示の切り替え",
592
690
  archived: "アーカイブ済み",
@@ -726,5 +824,29 @@ export const linksI18n = {
726
824
  reservedDesc: "予約語は短縮リンクとシステムエンドポイントの競合を防ぎます。",
727
825
  reservedInstanceNotice: "インスタンス設定でカスタム予約語を設定できます。",
728
826
  reservedInstanceAction: "インスタンス設定へ →",
827
+ abuse: {
828
+ pageTitle: "不正利用報告",
829
+ pageDesc: "スパムや悪意のあるリンクの報告を管理します",
830
+ loading: "読み込み中…",
831
+ emptyState: "不正利用の報告はありません。報告されたリンクがここに表示されます。",
832
+ target: "対象:",
833
+ ip: "IP: {{ip}}",
834
+ noDescription: "説明が提供されていません。",
835
+ dismissSafe: "安全として無視",
836
+ markReviewed: "確認済みとしてマーク",
837
+ updateFailed: "報告のステータスを更新できませんでした: {{error}}。再試行してください。",
838
+ filterOpen: "オープン",
839
+ filterReviewed: "確認済み",
840
+ filterDismissed: "無視",
841
+ filterAll: "すべて",
842
+ reasonSpam: "スパム",
843
+ reasonPhishing: "フィッシング",
844
+ reasonMalware: "マルウェア",
845
+ reasonOther: "その他",
846
+ },
847
+ customReservedLabel: "カスタム予約語",
848
+ customReservedHint: "1行に1つの予約語を入力してください。短縮リンクにこれらの単語は使用できません。",
849
+ saveReserved: "予約語を保存",
850
+ settingsSaved: "設定を保存しました",
729
851
  },
730
852
  };
package/index.ts CHANGED
@@ -4,7 +4,10 @@ import { linksI18n } from "./i18n";
4
4
 
5
5
  const links: UIPlugin = {
6
6
  name: "links",
7
- routes: [{ path: "/links", Component: lazy(() => import("./pages")) }],
7
+ routes: [
8
+ { path: "/links", Component: lazy(() => import("./pages")) },
9
+ { path: "/links/abuse", Component: lazy(() => import("./pages/Abuse")) },
10
+ ],
8
11
  widgets: [
9
12
  { slot: "home-overview", order: 10, Component: lazy(() => import("./widgets/LinksStatCardWidget")) },
10
13
  { slot: "home-setup-steps", order: 20, Component: lazy(() => import("./widgets/LinksSetupStepWidget")) },
@@ -1,15 +1,5 @@
1
1
  import { describe, it, expect } from "vitest";
2
2
 
3
- // Scope guard for the reserved-slug settings page. The config is one-per-
4
- // deployment (GET/PUT /api/instance-settings, instance-admin gated), so its
5
- // editor belongs in the /instance console — announced by the Go half's
6
- // InstanceMenus() and registered as a UIPlugin.instanceRoutes entry. If it
7
- // ever gets dragged back into the tenant Links shell (the old "settings" tab)
8
- // or the console route stops pointing at /link-settings, this file goes red.
9
- //
10
- // Read the real sources rather than restating them here: a list in this file
11
- // would drift from the pages it claims to guard. Same approach as
12
- // shell/navHardcoding.test.ts.
13
3
  const SOURCES = import.meta.glob("./{index.ts,pages/index.tsx}", {
14
4
  query: "?raw",
15
5
  import: "default",
@@ -29,10 +19,7 @@ describe("links instance scope", () => {
29
19
  it("keeps instance-scope settings out of the tenant Links page", () => {
30
20
  const page = sourceFor(TENANT_PAGE);
31
21
 
32
- // The instance-scope editor (LinkSettings / InstanceLinkSettings) must not
33
- // be referenced from the tenant page — import or otherwise.
34
22
  expect(page).not.toMatch(/\bLinkSettings\b/);
35
- // Nor any "settings" tab: no tab state, no tab-switch buttons, no branch.
36
23
  expect(page).not.toMatch(/tab\s*===\s*'settings'/);
37
24
  expect(page).not.toMatch(/setTab\s*\(\s*'settings'/);
38
25
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octarq/plugin-links",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Short links and click analytics plugin for Octarq",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -9,7 +9,7 @@
9
9
  ".": "./index.ts"
10
10
  },
11
11
  "peerDependencies": {
12
- "@octarq/plugin-sdk": "^0.21.0",
12
+ "@octarq/plugin-sdk": "^0.25.0",
13
13
  "react": "^18.3.1",
14
14
  "react-dom": "^18.3.1",
15
15
  "react-router-dom": "^6.28.0 || ^7.0.0"
@@ -18,7 +18,7 @@
18
18
  "lucide-react": "^1.21.0"
19
19
  },
20
20
  "devDependencies": {
21
- "@octarq/plugin-sdk": "^0.21.0",
21
+ "@octarq/plugin-sdk": "^0.25.0",
22
22
  "@types/react": "^18.3.1",
23
23
  "@types/react-dom": "^18.3.1",
24
24
  "react": "^18.3.1",
@@ -0,0 +1,103 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, it, expect, vi, beforeEach } from "vitest";
3
+ import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { registerUIPlugin, resetRegistry, I18nProvider, RoleProvider } from "@octarq/plugin-sdk";
6
+ import linksPlugin from "../index";
7
+ import AbusePage from "./Abuse";
8
+ import { api } from "../api";
9
+
10
+ vi.mock("../api", () => ({
11
+ api: {
12
+ abuseReports: vi.fn(),
13
+ updateAbuseReport: vi.fn(),
14
+ },
15
+ linksApi: {
16
+ abuseReports: vi.fn(),
17
+ updateAbuseReport: vi.fn(),
18
+ },
19
+ }));
20
+
21
+ function renderPage() {
22
+ return render(
23
+ <RoleProvider value={{ role: "admin", isInstanceAdmin: true }}>
24
+ <I18nProvider>
25
+ <MemoryRouter>
26
+ <AbusePage />
27
+ </MemoryRouter>
28
+ </I18nProvider>
29
+ </RoleProvider>
30
+ );
31
+ }
32
+
33
+ describe("AbusePage", () => {
34
+ beforeEach(() => {
35
+ cleanup();
36
+ resetRegistry();
37
+ registerUIPlugin(linksPlugin);
38
+ vi.clearAllMocks();
39
+ });
40
+
41
+ it("renders empty state when there are no abuse reports", async () => {
42
+ (api.abuseReports as any).mockResolvedValue([]);
43
+ renderPage();
44
+
45
+ await waitFor(() => {
46
+ expect(screen.getByText("No abuse reports. Reported links display here.")).toBeDefined();
47
+ });
48
+ });
49
+
50
+ it("renders report card and details when reports exist", async () => {
51
+ (api.abuseReports as any).mockResolvedValue([
52
+ {
53
+ id: 10,
54
+ slug: "phish-link",
55
+ target: "https://phishing.example.com",
56
+ reason: "phishing",
57
+ description: "Malicious credential harvesting link",
58
+ reporterIp: "203.0.113.*",
59
+ status: "open",
60
+ createdAt: "2026-11-24T12:00:00Z",
61
+ },
62
+ ]);
63
+
64
+ renderPage();
65
+
66
+ await waitFor(() => {
67
+ expect(screen.getByText("/phish-link")).toBeDefined();
68
+ expect(screen.getByText("https://phishing.example.com")).toBeDefined();
69
+ expect(screen.getByText("Malicious credential harvesting link")).toBeDefined();
70
+ expect(screen.getByText("IP: 203.0.113.*")).toBeDefined();
71
+ expect(screen.getByText("Dismiss (safe)")).toBeDefined();
72
+ expect(screen.getByText("Mark as reviewed")).toBeDefined();
73
+ });
74
+ });
75
+
76
+ it("calls updateAbuseReport on dismiss and review button clicks", async () => {
77
+ (api.abuseReports as any).mockResolvedValue([
78
+ {
79
+ id: 10,
80
+ slug: "phish-link",
81
+ target: "https://phishing.example.com",
82
+ reason: "phishing",
83
+ description: "Test description",
84
+ reporterIp: "10.0.0.*",
85
+ status: "open",
86
+ createdAt: "2026-11-24T12:00:00Z",
87
+ },
88
+ ]);
89
+ (api.updateAbuseReport as any).mockResolvedValue({ id: 10, status: "reviewed" });
90
+
91
+ renderPage();
92
+
93
+ await waitFor(() => {
94
+ expect(screen.getByText("Mark as reviewed")).toBeDefined();
95
+ });
96
+
97
+ fireEvent.click(screen.getByText("Mark as reviewed"));
98
+
99
+ await waitFor(() => {
100
+ expect(api.updateAbuseReport).toHaveBeenCalledWith(10, "reviewed");
101
+ });
102
+ });
103
+ });