mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
feat: add native in-app announcements with persistent dismissal (#13403)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Self-hosted boards need a way to show occasional product announcements. > - An app release should not be required to publish or withdraw a card. > - Native card controls keep publishing consistent; the hero can use a static image or isolated HTML/CSS animation. > - This pull request renders a validated JSON feed with native components. > - It stores dismissals per account on each instance, so a closed card stays closed across companies and browsers. > - Named staging feeds let authors test content before production publication. ## Linked Issues or Issue Description **Subsystem affected** Board application shell, announcement delivery, and user preferences. **Problem or motivation** Operators need a small, optional announcement card. Users need reliable dismissal state. Authors need to test remote content without changing the production feed. **Proposed solution** Add one non-modal AnnouncementWell. Fetch validated JSON and content-addressed media through the instance server. Keep card controls native, with optional sandboxed HTML/CSS animation in the hero. Use stable announcement IDs for dismissal, an explicit empty manifest and quiet 404 handling. Provide a staged publishing helper and isolated test-drive guide. **Alternatives considered** Hosting the entire card as a page would move navigation and dismissal into remote content. This change limits HTML to a scriptless, isolated visual hero and keeps controls native. Browser-only storage would lose dismissals across browsers, so the instance stores account preferences. **Roadmap alignment** ROADMAP.md has no overlapping announcement feature. A GitHub title search found no related announcement pull requests. This work implements a maintainer-requested feature. ## What Changed - Add shared feed types, strict validation of every object, supported routes, expiration and version checks. - Add a board-only current-feed API, constrained media proxy, and idempotent dismissal API. Store the first dismissal and its company audit entry in one transaction. - Cache upstream data for one hour. Use conditional requests, request deduplication, response limits, public destination checks, and a three-second deadline. Treat a remote 404 as an empty feed with a fifteen-minute retry cooldown. - Keep announcement visibility stable when focus moves to browser chrome or another app pane; only tab visibility starts a return check. - Add a responsive native announcement card. Respect onboarding, dialogs and toast placement. Sync pending dismissals across tabs and retry after reconnect or return. - Add idempotent migrations for dismissals and validated publication IDs, design-guide examples, static and animated Storybook examples, and focused tests. The publication registry supports offline retries without accepting caller-invented IDs. - Add HTML/CSS animated heroes with static posters, automatic playback, reduced-motion handling, strict DOMPurify validation, an empty iframe sandbox and CSP that blocks scripts/network resources. - Add validated staging publication, content-addressed assets, an empty production manifest, preview fixtures, and authoring/operator documentation. ## Verification - The preceding implementation passed 98 targeted shared/server/publisher/route/OpenAPI/UI tests and 127 tests including the master rebase. The playback-control removal passes all 21 announcement UI tests, covering the rendered sandbox, fallback, reduced motion, dismissal and slow/stale state lookups. The preceding shared/server tests cover HTML validation and response sandbox headers. - The playback-control removal passes UI typecheck, production UI build, Storybook build and token gates locally. Browser verification confirms the animated card has only its dismiss button and two links, with no page errors. The full canonical CI matrix passed on current head `00e416431edb610861599d50490270bbd0f3c6b6`: 32 successful checks and two optional Storybook deployment checks skipped. This run needed no retries. Greptile reviewed this same head at 5/5 with no outstanding findings. - The local canonical general-server run passed 12,063 tests before reporting embedded-PostgreSQL startup failures in an unrelated fixture. All 31 tests in that fixture passed across isolated retries. The UI group passed 6,219 tests and other workspace groups passed 3,201; two CLI database-startup failures also passed individually. Serialized server suites were verified by the full CI matrix rather than repeating them locally. No source changes were needed for these environment failures. - The real S3/CloudFront staging manifest and both media asset headers were verified. Production remains empty/unpublished. The guide distinguishes the preview host's disabled edge cache from production cache requirements. - In the isolated test-drive, the animation visibly moves without playback controls. A 390×844 browser viewport keeps the card above navigation. Reduced motion makes no animation request. Both themes render correctly and browser page errors are empty. Browser fault injection verified that scripts cannot execute and CSS cannot make network requests; a missing animation leaves its poster and controls. - Refresh leaves the animated card visible. Closing it persists after reload and the API returns null. Earlier live checks verified dismissal across browsers, company-relative CTA navigation, modal deferral/restoration, and new-ID eligibility after restarting the same database. - The deployed empty feed and a real remote 404 return HTTP 200 with null from the board API, with a usable dashboard and no announcement popup or browser warnings. - Authoring documentation covers staging, animated HTML constraints, test-drive, withdrawal, ID reuse and cache-refresh steps. ## Risks - Animation supports self-contained visual HTML/CSS and inline SVG, without JavaScript or external resources. A static image is required. Older builds that do not recognize the optional animation field quietly hide that unsupported feed. - The default feed makes an outbound request from an instance when a board is used. Operators can disable it. Requests contain no account IDs, company data, cookies or interaction events. - Feed publication and withdrawal can take about 65 minutes to reach returning users because of CDN and instance caches. Expiration also removes visible cards locally. - Dismissals follow an account within one instance. No-login instances share the existing local-board identity. Separate installations do not share state. - Both tables are additive. A unique key prevents duplicate dismissals; the transaction prevents duplicate first-dismissal audit entries. The publication registry retains only validated IDs. AGENTS.md and the implementation spec document the required exception to company scope for these instance-level records. - Publication was limited to separate public staging prefixes on the existing preview host. Production remains empty/unpublished. No AWS policies or infrastructure were changed. ## Model Used OpenAI GPT-6 through Codex. The exact runtime model ID and context-window size are not exposed in this session. Capabilities used: reasoning, code editing, shell execution, tests, browser interaction, and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
f1d57863d2
commit
728f7185f6
53 files changed
+97886
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateAnnouncementAnimation } from "../services/announcement-animation.js";
|
||||
|
||||
describe("announcement animation documents", () => {
|
||||
it("preserves CSS keyframes and visual HTML/SVG", () => {
|
||||
const html = "<html><head><style>@keyframes pulse{to{opacity:.5}}.dot{animation:pulse 2s infinite}</style></head><body><div class='dot'><svg viewBox='0 0 10 10'><circle cx='5' cy='5' r='3'/></svg></div></body></html>";
|
||||
expect(validateAnnouncementAnimation(Buffer.from(html))).toContain("@keyframes pulse");
|
||||
expect(validateAnnouncementAnimation(Buffer.from(html))).toContain('viewBox="0 0 10 10"');
|
||||
});
|
||||
it.each([
|
||||
"<script>fetch('/api/companies')</script>", "<div onclick='alert(1)'>Click</div>",
|
||||
"<a href='https://evil.test'>Navigate</a>", "<form action='/api/test'><input></form>",
|
||||
"<meta http-equiv='refresh' content='0;url=https://evil.test'>", "<base href='https://evil.test'>",
|
||||
"<iframe src='https://evil.test'></iframe>", "<img src='https://evil.test/pixel'>", "<link rel='stylesheet' href='https://evil.test'>",
|
||||
"<svg><foreignObject><p>Other namespace</p></foreignObject></svg>",
|
||||
"<svg><a xlink:href='https://evil.test'><text>Go</text></a></svg>",
|
||||
"<svg><animate attributeName='href' values='https://evil.test'/></svg>",
|
||||
"<object data='https://evil.test'></object>", "<button>Click</button>",
|
||||
])("rejects active or resource-loading markup: %s", (html) => {
|
||||
expect(() => validateAnnouncementAnimation(Buffer.from(html))).toThrow();
|
||||
});
|
||||
it("rejects empty, oversized and invalid UTF-8 files", () => {
|
||||
for (const bytes of [Buffer.alloc(0), Buffer.alloc(128 * 1024 + 1), Buffer.from([0xff])]) {
|
||||
expect(() => validateAnnouncementAnimation(bytes)).toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { announcementFeedService, ANNOUNCEMENT_CACHE_MS, ANNOUNCEMENT_FAILURE_MS } from "../services/announcement-feed.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
const item = { id: "new-projects", eyebrow: "New", title: "Projects", description: "Organize your work.", primaryAction: { kind: "route", label: "Open", path: "/projects" } };
|
||||
const json = (announcement: unknown = item, etag = '"v1"') => new Response(JSON.stringify({ schemaVersion: 1, announcement }), { headers: { "Content-Type": "application/json", ETag: etag } });
|
||||
afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
describe("announcement feed", () => {
|
||||
it("treats a 404 as quiet empty content, drops stale ETags, and recovers after cooldown", async () => {
|
||||
let now = 0;
|
||||
const warn = vi.spyOn(logger, "warn");
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json())
|
||||
.mockImplementationOnce(async () => new Response("Not found", { status: 404 }))
|
||||
.mockImplementationOnce(async () => json({ ...item, id: "restored" }));
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch });
|
||||
expect(await service.current()).toEqual(item);
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
now += ANNOUNCEMENT_FAILURE_MS - 1;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
now++;
|
||||
expect((await service.current())?.id).toBe("restored");
|
||||
expect(fetch.mock.calls[2][1].headers).not.toHaveProperty("If-None-Match");
|
||||
});
|
||||
|
||||
it("deduplicates requests, caches for an hour, then revalidates with ETag", async () => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json()).mockResolvedValueOnce(new Response(null, { status: 304 }));
|
||||
const service = announcementFeedService({ version: "2026.913.0", now: () => now, fetch });
|
||||
expect(await Promise.all([service.current(), service.current()])).toEqual([item, item]);
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now = ANNOUNCEMENT_CACHE_MS - 1;
|
||||
await service.current();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now++;
|
||||
expect(await service.current()).toEqual(item);
|
||||
expect(fetch.mock.calls[1][1]).toMatchObject({ headers: { "If-None-Match": '"v1"' }, credentials: "omit" });
|
||||
expect(Object.keys(fetch.mock.calls[0][1].headers)).toEqual(["Accept"]);
|
||||
});
|
||||
it("withdraws, updates same-ID copy and discovers new IDs after refresh", async () => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json()).mockImplementationOnce(async () => json({ ...item, title: "Corrected" }, '"v2"')).mockImplementationOnce(async () => json(null)).mockImplementationOnce(async () => json({ ...item, id: "next" }));
|
||||
const service = announcementFeedService({ version: "2026.913.0", now: () => now, fetch });
|
||||
expect((await service.current())?.id).toBe(item.id);
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect((await service.current())?.title).toBe("Corrected");
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect(await service.current()).toBeNull();
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect((await service.current())?.id).toBe("next");
|
||||
});
|
||||
it.each([
|
||||
() => new Response("bad json", { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response(JSON.stringify({ schemaVersion: 9, announcement: item }), { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response("x".repeat(65537), { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response("", { status: 302, headers: { Location: "http://127.0.0.1" } }),
|
||||
() => new Response("<html>error</html>", { status: 503 }),
|
||||
])("suppresses invalid/unavailable feeds and observes failure cooldown", async (response) => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => response()).mockImplementationOnce(async () => json());
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch });
|
||||
expect(await service.current()).toBeNull();
|
||||
now = ANNOUNCEMENT_FAILURE_MS - 1;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now++;
|
||||
expect(await service.current()).toEqual(item);
|
||||
});
|
||||
it("bounds a hung fetch to three seconds", async () => {
|
||||
vi.useFakeTimers();
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch: () => new Promise(() => {}) });
|
||||
const result = service.current();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(await result).toBeNull();
|
||||
});
|
||||
it("does not fetch when disabled or an operator URL is invalid", async () => {
|
||||
const fetch = vi.fn();
|
||||
for (const options of [{ enabled: false }, { feedUrl: "http://localhost/feed" }, { feedUrl: "https://user:secret@example.com/feed" }]) {
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch, ...options });
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
}
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
it("expires a cached announcement and filters version-incompatible content", async () => {
|
||||
let now = 0;
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch: async () => json({ ...item, expiresAt: "1970-01-01T00:00:01Z" }) });
|
||||
expect(await service.current()).not.toBeNull();
|
||||
now = 1000;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await announcementFeedService({ version: "1.0.0", fetch: async () => json({ ...item, minimumPaperclipVersion: "2.0.0" }) }).current()).toBeNull();
|
||||
});
|
||||
it("proxies only the current content-addressed image and caches bytes", async () => {
|
||||
const bytes = Buffer.from("test-image");
|
||||
const path = `assets/${createHash("sha256").update(bytes).digest("hex")}.png`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path, alt: "" } })).mockImplementationOnce(async () => new Response(bytes, { headers: { "Content-Type": "image/png" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.image("other")).toBeNull();
|
||||
const images = await Promise.all([service.image(item.id), service.image(item.id)]);
|
||||
expect(images[0]?.bytes).toEqual(bytes);
|
||||
expect(images[1]).toEqual(images[0]);
|
||||
await service.image(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetch.mock.calls[1][0])).toBe(`https://pages.paperclip.ing/announcements/v1/${path}`);
|
||||
});
|
||||
it("rejects image digest mismatches and cools down image retries", async () => {
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "" } })).mockImplementation(async () => new Response("wrong", { headers: { "Content-Type": "image/png" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("deduplicates and caches validated animations on the configured host", async () => {
|
||||
const bytes = Buffer.from("<div style='animation:pulse 2s infinite'>Team</div>");
|
||||
const path = `assets/${createHash("sha256").update(bytes).digest("hex")}.html`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }))
|
||||
.mockImplementationOnce(async () => new Response(bytes, { headers: { "Content-Type": "text/html; charset=utf-8" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", feedUrl: "https://mirror.example/preview/current.json", fetch });
|
||||
expect(await service.animation("wrong-id")).toBeNull();
|
||||
const result = await Promise.all([service.animation(item.id), service.animation(item.id)]);
|
||||
expect(result[0]?.bytes.toString()).toContain("Team");
|
||||
expect(result[1]).toEqual(result[0]);
|
||||
await service.animation(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetch.mock.calls[1][0])).toBe(`https://mirror.example/preview/${path}`);
|
||||
expect(fetch.mock.calls[1][1]).toMatchObject({ credentials: "omit", redirect: "error", headers: { Accept: "text/html" } });
|
||||
});
|
||||
it.each([
|
||||
["<script>alert(1)</script>", "text/html", 200],
|
||||
["<div>ok</div>", "text/plain", 200],
|
||||
["not found", "text/html", 404],
|
||||
["x".repeat(128 * 1024 + 1), "text/html", 200],
|
||||
])("falls back on rejected animation assets and cools down retries", async (html, contentType, status) => {
|
||||
const path = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }))
|
||||
.mockImplementation(async () => new Response(html, { status, headers: { "Content-Type": contentType } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
expect((await service.current())?.id).toBe(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, mkdir, writeFile, symlink, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { prepareAnnouncementPublish, announcementUploadArgs, parseAnnouncementPublishArgs, announcementPublishPrefix } from "../../../scripts/publish-announcements.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
async function fixture() { const dir = await mkdtemp(path.join(os.tmpdir(), "announcement-publish-")); dirs.push(dir); return dir; }
|
||||
afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
|
||||
describe("announcement publishing", () => {
|
||||
it("keeps named staging feeds separate from production and defaults to dry-run", async () => {
|
||||
const dir = await fixture();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null }));
|
||||
const result = await prepareAnnouncementPublish(dir, "preview-projects");
|
||||
expect(result.files.map((file) => file.key)).toEqual(["announcements/staging/preview-projects/v1/current.json"]);
|
||||
expect(parseAnnouncementPublishArgs(["--staging", "preview-projects"])).toEqual({
|
||||
sourceDirectory: "announcements/examples/staging", staging: "preview-projects", publish: false,
|
||||
});
|
||||
expect(parseAnnouncementPublishArgs([dir, "--staging", "preview-projects", "--publish"]).publish).toBe(true);
|
||||
expect(announcementPublishPrefix()).toBe("announcements/v1");
|
||||
expect((await prepareAnnouncementPublish(dir, "preview-projects", "storybook/branches/codex-announcements")).files[0].key)
|
||||
.toBe("storybook/branches/codex-announcements/announcements/staging/preview-projects/v1/current.json");
|
||||
for (const prefix of ["../outside", "/leading", "trailing/", "bad//path", "", "https://example.com"]) {
|
||||
expect(() => announcementPublishPrefix("preview-projects", prefix)).toThrow();
|
||||
}
|
||||
for (const name of ["../v1", "", "/production", "preview/nested"]) {
|
||||
expect(() => announcementPublishPrefix(name)).toThrow();
|
||||
}
|
||||
for (const args of [["--staging"], ["--publish", "--dry-run"], ["one", "two"], ["--unknown"]]) {
|
||||
expect(() => parseAnnouncementPublishArgs(args)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("uploads content-addressed assets before the five-minute manifest", async () => {
|
||||
const dir = await fixture();
|
||||
const bytes = Buffer.from("test-image");
|
||||
const imagePath = `assets/${createHash("sha256").update(bytes).digest("hex")}.png`;
|
||||
await mkdir(path.join(dir, "assets"));
|
||||
await writeFile(path.join(dir, imagePath), bytes);
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: { id: "test", title: "Test", eyebrow: "New", description: "Example", image: { path: imagePath, alt: "" }, primaryAction: { kind: "route", label: "Open", path: "/projects" } } }));
|
||||
const { files } = await prepareAnnouncementPublish(dir);
|
||||
expect(files.map((file) => file.key)).toEqual([`announcements/v1/${imagePath}`, "announcements/v1/current.json"]);
|
||||
expect(files[0].cacheControl).toContain("immutable");
|
||||
expect(announcementUploadArgs("bucket", files[1])).toContain("public,max-age=300");
|
||||
await writeFile(path.join(dir, imagePath), "changed");
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow("SHA-256");
|
||||
});
|
||||
it("validates HTML animation fixtures and uploads both assets before the manifest", async () => {
|
||||
const result = await prepareAnnouncementPublish(path.resolve(import.meta.dirname, "../../../announcements/examples/animated"), "animated-preview");
|
||||
expect(result.files.map((file) => file.contentType)).toEqual(["image/png", "text/html", "application/json"]);
|
||||
const dir = await fixture();
|
||||
await mkdir(path.join(dir, "assets"));
|
||||
const html = "<meta http-equiv='refresh' content='0;url=https://evil.test'>";
|
||||
const asset = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const image = result.files[0];
|
||||
const imagePath = result.manifest.announcement!.image!.path;
|
||||
await writeFile(path.join(dir, imagePath), await import("node:fs/promises").then((fs) => fs.readFile(image.file)));
|
||||
await writeFile(path.join(dir, asset), html);
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ ...result.manifest, announcement: { ...result.manifest.announcement, animation: { path: asset, alt: "Unsafe" } } }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow("only visual HTML/CSS");
|
||||
});
|
||||
it("supports withdrawal and rejects symlinks and unsupported schemas", async () => {
|
||||
const dir = await fixture();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null }));
|
||||
expect((await prepareAnnouncementPublish(dir)).files).toHaveLength(1);
|
||||
const link = path.join(dir, "link"); await symlink(dir, link);
|
||||
await expect(prepareAnnouncementPublish(link)).rejects.toThrow("real directory");
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 2, announcement: null }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null, announcements: [] }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import express from "express";
|
||||
import { createHash } from "node:crypto";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { activityLog, announcementDismissals, announcementPublications, companies, createDb, startEmbeddedPostgresTestDatabase, type EmbeddedPostgresTestDatabase } from "@paperclipai/db";
|
||||
import { announcementRoutes } from "../routes/announcements.js";
|
||||
import { announcementService } from "../services/announcements.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
|
||||
const companyId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherCompanyId = "22222222-2222-4222-8222-222222222222";
|
||||
const item = { id: "new-projects", eyebrow: "New", title: "Projects", description: "Organize your work.", primaryAction: { kind: "route", label: "Open", path: "/projects" } };
|
||||
describe("announcement routes and durable dismissals", () => {
|
||||
let database: EmbeddedPostgresTestDatabase;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
function app(userId = "alice", actorOverride?: Record<string, unknown>, announcement: unknown = item, feedStatus = 200, animationHtml?: string) {
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
server.use((req, _res, next) => {
|
||||
req.actor = (actorOverride ?? { type: "board", userId, source: "session", companyIds: [companyId, otherCompanyId], memberships: [{ companyId, membershipRole: "viewer", status: "active" }] }) as never;
|
||||
next();
|
||||
});
|
||||
server.use("/api", announcementRoutes(db, { version: "2026.913.0", fetch: async (url) => animationHtml && url.pathname.endsWith(".html") ? new Response(animationHtml, { headers: { "Content-Type": "text/html" } }) : new Response(JSON.stringify({ schemaVersion: 1, announcement }), { status: feedStatus, headers: { "Content-Type": "application/json" } }) }));
|
||||
server.use(errorHandler);
|
||||
return server;
|
||||
}
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-announcements-");
|
||||
db = createDb(database.connectionString);
|
||||
await db.insert(companies).values([{ id: companyId, name: "Test", issuePrefix: "ANN" }, { id: otherCompanyId, name: "Other", issuePrefix: "ANB" }]);
|
||||
}, 90_000);
|
||||
beforeEach(async () => { await db.delete(announcementDismissals); await db.delete(announcementPublications); await db.delete(activityLog); });
|
||||
afterAll(async () => { await database?.cleanup(); }, 30_000);
|
||||
it.each([200, 404])("returns a successful empty response for no remote announcement (HTTP %s)", async (status) => {
|
||||
const response = await request(app("alice", undefined, null, status)).get("/api/announcements/current");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toBeNull();
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
});
|
||||
it("serves animation documents with a sandbox and network-denying CSP", async () => {
|
||||
const html = "<div>Team</div>";
|
||||
const path = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const server = app("alice", undefined, { ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }, 200, html);
|
||||
const response = await request(server).get(`/api/announcements/${item.id}/animation`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
expect(response.headers["content-security-policy"]).toContain("sandbox; default-src 'none'");
|
||||
expect(response.headers["referrer-policy"]).toBe("no-referrer");
|
||||
expect(response.headers["x-content-type-options"]).toBe("nosniff");
|
||||
expect(response.type).toBe("text/html");
|
||||
expect((await request(server).get("/api/announcements/wrong-id/animation")).status).toBe(404);
|
||||
});
|
||||
it("persists across app/service restarts, browsers and companies, isolated by user", async () => {
|
||||
const first = app();
|
||||
const response = await request(first).get("/api/announcements/current");
|
||||
expect(response.body.id).toBe(item.id);
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
expect((await request(first).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect((await request(app()).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(app("bob")).get("/api/announcements/current")).body.id).toBe(item.id);
|
||||
await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId: otherCompanyId });
|
||||
expect(await db.select().from(activityLog)).toHaveLength(1);
|
||||
});
|
||||
it("accepts viewers and concurrent duplicate dismissals with one audit", async () => {
|
||||
const server = app();
|
||||
await request(server).get("/api/announcements/current");
|
||||
const responses = await Promise.all(Array.from({ length: 5 }, () => request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })));
|
||||
expect(responses.map((res) => res.status)).toEqual([204, 204, 204, 204, 204]);
|
||||
expect(await db.select().from(announcementDismissals)).toHaveLength(1);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "announcement.dismissed"))).toHaveLength(1);
|
||||
});
|
||||
it("rolls back the dismissal if its audit cannot commit", async () => {
|
||||
await announcementService(db).registerPublication(item.id);
|
||||
await expect(announcementService(db).dismiss("alice", item.id, "33333333-3333-4333-8333-333333333333")).rejects.toThrow();
|
||||
expect(await announcementService(db).isDismissed("alice", item.id)).toBe(false);
|
||||
});
|
||||
it("never resurrects a dismissed ID after copy changes or rollback; a new ID appears", async () => {
|
||||
await announcementService(db).registerPublication(item.id);
|
||||
await announcementService(db).dismiss("alice", item.id, companyId);
|
||||
expect((await request(app("alice", undefined, { ...item, title: "Fixed copy" })).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(app("alice", undefined, { ...item, id: "next" })).get("/api/announcements/current")).body.id).toBe("next");
|
||||
expect((await request(app()).get("/api/announcements/current")).body).toBeNull();
|
||||
});
|
||||
it("uses the local-board identity without an auth user row", async () => {
|
||||
const server = app("local-board", { type: "board", userId: "local-board", source: "local_implicit" });
|
||||
await request(server).get("/api/announcements/current");
|
||||
expect((await request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect(await announcementService(db).isDismissed("local-board", item.id)).toBe(true);
|
||||
});
|
||||
it("rejects invented IDs without storing dismissals or audit entries", async () => {
|
||||
const server = app();
|
||||
await request(server).get("/api/announcements/current");
|
||||
for (const id of ["invented-one", "invented-two", "invented-three"]) {
|
||||
expect((await request(server).post(`/api/announcements/${id}/dismiss`).send({ companyId })).status).toBe(404);
|
||||
}
|
||||
expect(await db.select().from(announcementDismissals)).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog)).toHaveLength(0);
|
||||
expect(await db.select().from(announcementPublications)).toEqual([{ announcementId: item.id }]);
|
||||
});
|
||||
it("accepts offline retries for validated IDs after withdrawal and restart", async () => {
|
||||
await request(app()).get("/api/announcements/current");
|
||||
const restarted = app("alice", undefined, null, 404);
|
||||
expect((await request(restarted).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(restarted).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect(await announcementService(db).isDismissed("alice", item.id)).toBe(true);
|
||||
expect(await db.select().from(activityLog)).toHaveLength(1);
|
||||
});
|
||||
it("rejects anonymous/agent callers and inaccessible audit companies", async () => {
|
||||
for (const actor of [{ type: "none" }, { type: "agent", companyId, userId: "alice" }]) {
|
||||
const server = app("alice", actor);
|
||||
const expected = actor.type === "none" ? 401 : 403;
|
||||
for (const url of ["current", `${item.id}/image`, `${item.id}/animation`]) expect((await request(server).get(`/api/announcements/${url}`)).status).toBe(expected);
|
||||
expect((await request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(expected);
|
||||
}
|
||||
expect((await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId: "33333333-3333-4333-8333-333333333333" })).status).toBe(404);
|
||||
expect((await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId, userId: "bob" })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"activity.ts": "/api",
|
||||
"adapters.ts": "/api",
|
||||
"agents.ts": "/api",
|
||||
"announcements.ts": "/api",
|
||||
"ai-connections.ts": "/api",
|
||||
"attention.ts": "/api",
|
||||
"approvals.ts": "/api",
|
||||
@@ -223,6 +224,26 @@ function loadSpecRoutes() {
|
||||
}
|
||||
|
||||
describe("openapi routes", () => {
|
||||
it("documents personal board-only announcements and private responses", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const current = spec.paths["/api/announcements/current"].get;
|
||||
const image = spec.paths["/api/announcements/{id}/image"].get;
|
||||
const animation = spec.paths["/api/announcements/{id}/animation"].get;
|
||||
const dismiss = spec.paths["/api/announcements/{id}/dismiss"].post;
|
||||
for (const operation of [current, image, animation, dismiss]) {
|
||||
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
const success = operation.responses["200"] ?? operation.responses["204"];
|
||||
expect(success.headers["Cache-Control"].schema.enum).toEqual(["private, no-store"]);
|
||||
}
|
||||
expect(current.responses["200"].content["application/json"].schema.nullable).toBe(true);
|
||||
expect(Object.keys(image.responses["200"].content)).toEqual(["image/png", "image/jpeg", "image/webp"]);
|
||||
expect(dismiss.requestBody.content["application/json"].schema).toMatchObject({
|
||||
required: ["companyId"], additionalProperties: false,
|
||||
});
|
||||
expect(dismiss.description).toContain("viewers may dismiss their own");
|
||||
});
|
||||
|
||||
it("documents exact failed-run selection and durable accepted retry responses", async () => {
|
||||
const res = await request(createApp()).get("/api/openapi.json");
|
||||
const wake = res.body.paths["/api/agents/{id}/wakeup"].post;
|
||||
|
||||
@@ -91,6 +91,8 @@ import type { DecisionServiceOptions } from "./services/decisions.js";
|
||||
import { userProfileRoutes } from "./routes/user-profiles.js";
|
||||
import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js";
|
||||
import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
|
||||
import { announcementRoutes } from "./routes/announcements.js";
|
||||
import { serverVersion } from "./version.js";
|
||||
import { resourceMembershipRoutes } from "./routes/resource-memberships.js";
|
||||
import { inboxDismissalRoutes } from "./routes/inbox-dismissals.js";
|
||||
import { instanceSettingsRoutes } from "./routes/instance-settings.js";
|
||||
@@ -474,6 +476,7 @@ export async function createApp(
|
||||
chatWebhookPublicBaseUrl?: string;
|
||||
authReady: boolean;
|
||||
companyDeletionEnabled: boolean;
|
||||
announcements?: { enabled: boolean; feedUrl: string };
|
||||
instanceId?: string;
|
||||
hostVersion?: string;
|
||||
localPluginDir?: string;
|
||||
@@ -776,6 +779,7 @@ export async function createApp(
|
||||
api.use(userProfileRoutes(db));
|
||||
api.use(sidebarBadgeRoutes(db));
|
||||
api.use(sidebarPreferenceRoutes(db));
|
||||
api.use(announcementRoutes(db, { ...opts.announcements, version: opts.hostVersion ?? serverVersion }));
|
||||
api.use(resourceMembershipRoutes(db));
|
||||
api.use(inboxDismissalRoutes(db));
|
||||
api.use(instanceSettingsRoutes(db));
|
||||
|
||||
@@ -95,6 +95,8 @@ export interface Config {
|
||||
heartbeatSchedulerIntervalMs: number;
|
||||
companyDeletionEnabled: boolean;
|
||||
telemetryEnabled: boolean;
|
||||
announcementsEnabled: boolean;
|
||||
announcementsFeedUrl: string;
|
||||
}
|
||||
|
||||
function detectTailnetBindHost(): string | undefined {
|
||||
@@ -364,5 +366,7 @@ export function loadConfig(): Config {
|
||||
heartbeatSchedulerIntervalMs: Math.max(10000, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 30000),
|
||||
companyDeletionEnabled,
|
||||
telemetryEnabled: fileConfig?.telemetry?.enabled ?? true,
|
||||
announcementsEnabled: process.env.PAPERCLIP_ANNOUNCEMENTS_ENABLED !== "false",
|
||||
announcementsFeedUrl: process.env.PAPERCLIP_ANNOUNCEMENTS_FEED_URL?.trim() || "https://pages.paperclip.ing/announcements/v1/current.json",
|
||||
};
|
||||
}
|
||||
@@ -911,6 +911,7 @@ async function startServerWithDatabaseTeardown(
|
||||
chatWebhookPublicBaseUrl: config.chatWebhookPublicBaseUrl,
|
||||
authReady,
|
||||
companyDeletionEnabled: config.companyDeletionEnabled,
|
||||
announcements: { enabled: config.announcementsEnabled, feedUrl: config.announcementsFeedUrl },
|
||||
pluginMigrationDb: pluginMigrationDb as any,
|
||||
betterAuthHandler,
|
||||
resolveSession,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { companies, type Db } from "@paperclipai/db";
|
||||
import { ANNOUNCEMENT_ANIMATION_CSP, announcementIdSchema, dismissAnnouncementSchema } from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, notFound } from "../errors.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { assertAuthenticated, assertBoard, hasCompanyAccess } from "./authz.js";
|
||||
import { announcementService } from "../services/announcements.js";
|
||||
import { announcementFeedService, type AnnouncementFeedOptions } from "../services/announcement-feed.js";
|
||||
|
||||
export function announcementRoutes(db: Db, options: AnnouncementFeedOptions) {
|
||||
const router = Router();
|
||||
const feed = announcementFeedService(options);
|
||||
const service = announcementService(db);
|
||||
router.use("/announcements", (req, res, next) => {
|
||||
assertAuthenticated(req);
|
||||
assertBoard(req);
|
||||
if (!req.actor.userId) throw forbidden("Board user context required");
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
next();
|
||||
});
|
||||
router.get("/announcements/current", async (req, res) => {
|
||||
const announcement = await feed.current();
|
||||
if (announcement) await service.registerPublication(announcement.id);
|
||||
res.json(announcement && !await service.isDismissed(req.actor.userId!, announcement.id) ? announcement : null);
|
||||
});
|
||||
router.get("/announcements/:id/image", async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const image = await feed.image(id.data);
|
||||
if (!image) throw notFound("Announcement image unavailable");
|
||||
res.setHeader("Content-Type", image.contentType);
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.send(image.bytes);
|
||||
});
|
||||
router.get("/announcements/:id/animation", async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const animation = await feed.animation(id.data);
|
||||
if (!animation) throw notFound("Announcement animation unavailable");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("Content-Security-Policy", `sandbox; ${ANNOUNCEMENT_ANIMATION_CSP}`);
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.send(animation.bytes);
|
||||
});
|
||||
router.post("/announcements/:id/dismiss", validate(dismissAnnouncementSchema), async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const { companyId } = req.body;
|
||||
// This writes the caller's personal preference. Viewers may dismiss it;
|
||||
// company read membership supplies audit context, not write authority.
|
||||
if (!hasCompanyAccess(req, companyId)) throw notFound("Company not found");
|
||||
if (!await db.query.companies.findFirst({ where: eq(companies.id, companyId), columns: { id: true } })) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
if (!await service.dismiss(req.actor.userId!, id.data, companyId)) throw notFound("Announcement not found");
|
||||
res.status(204).end();
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -112,6 +112,10 @@ import {
|
||||
resolveBudgetIncidentSchema,
|
||||
// Sidebar
|
||||
upsertSidebarOrderPreferenceSchema,
|
||||
// Announcements
|
||||
announcementIdSchema,
|
||||
announcementSchema,
|
||||
dismissAnnouncementSchema,
|
||||
// Execution workspaces
|
||||
reconcileExecutionWorkspaceBranchSchema,
|
||||
updateExecutionWorkspaceSchema,
|
||||
@@ -1279,6 +1283,7 @@ const PUBLIC_OPERATIONS = new Set([
|
||||
]);
|
||||
|
||||
const BOARD_ONLY_PREFIXES = [
|
||||
"/api/announcements/",
|
||||
"/api/auth/",
|
||||
"/api/admin/",
|
||||
"/api/plugins",
|
||||
@@ -5782,6 +5787,87 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
|
||||
});
|
||||
|
||||
// ─── Announcements ───────────────────────────────────────────────────────────
|
||||
|
||||
const announcementResponseHeaders = {
|
||||
"Cache-Control": { schema: { type: "string", enum: ["private, no-store"] } },
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/current",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current user's eligible announcement",
|
||||
description: "Returns null for dismissed, disabled, unavailable, expired or incompatible content. Dismissals follow the board user across companies within this instance; no-login installations use local-board.",
|
||||
responses: {
|
||||
200: { ...r.ok(announcementSchema.nullable()), headers: announcementResponseHeaders },
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
500: r.serverError,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/{id}/image",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current announcement's validated image",
|
||||
description: "Proxies only the content-addressed raster asset in the eligible manifest. Arbitrary URLs and asset paths are not accepted.",
|
||||
request: { params: z.object({ id: announcementIdSchema }) },
|
||||
responses: {
|
||||
200: {
|
||||
description: "Validated announcement image",
|
||||
headers: announcementResponseHeaders,
|
||||
content: {
|
||||
"image/png": { schema: { type: "string", format: "binary" } },
|
||||
"image/jpeg": { schema: { type: "string", format: "binary" } },
|
||||
"image/webp": { schema: { type: "string", format: "binary" } },
|
||||
},
|
||||
},
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/{id}/animation",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current announcement's isolated HTML/CSS animation",
|
||||
description: "Board-only, validated content-addressed HTML. Scripts, links, forms and embedded resources are rejected; CSP sandbox and resource restrictions also apply to direct visits. Missing or invalid assets return 404 and the card uses its static image.",
|
||||
request: { params: z.object({ id: announcementIdSchema }) },
|
||||
responses: {
|
||||
200: {
|
||||
description: "Validated visual HTML/CSS document",
|
||||
headers: { ...announcementResponseHeaders, "Content-Security-Policy": { schema: { type: "string" } } },
|
||||
content: { "text/html": { schema: { type: "string" } } },
|
||||
},
|
||||
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/announcements/{id}/dismiss",
|
||||
tags: ["announcements"],
|
||||
summary: "Dismiss an announcement for the current user",
|
||||
description: "Idempotently saves a personal preference. The supplied company is validated audit context; viewers may dismiss their own announcement. The first dismissal and its audit entry commit together. IDs from a previously validated feed remain valid for offline retries; unknown IDs return 404 without creating records.",
|
||||
request: {
|
||||
params: z.object({ id: announcementIdSchema }),
|
||||
body: jsonBody(dismissAnnouncementSchema),
|
||||
},
|
||||
responses: {
|
||||
204: { ...r.noContent, headers: announcementResponseHeaders },
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
500: r.serverError,
|
||||
},
|
||||
});
|
||||
|
||||
// ─── Inbox dismissals ────────────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import createDOMPurify from "dompurify";
|
||||
import { JSDOM } from "jsdom";
|
||||
import { ANNOUNCEMENT_ANIMATION_MAX_BYTES } from "@paperclipai/shared";
|
||||
|
||||
// A visual HTML/CSS document, never an application. JSDOM does not execute
|
||||
// scripts or load resources. DOMPurify handles HTML parsing/normalization;
|
||||
// CSP on delivery also blocks all network requests, including CSS URLs.
|
||||
export function validateAnnouncementAnimation(bytes: Uint8Array): string {
|
||||
if (!bytes.length || bytes.byteLength > ANNOUNCEMENT_ANIMATION_MAX_BYTES) {
|
||||
throw new Error("Invalid or oversized announcement animation");
|
||||
}
|
||||
const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
const dom = new JSDOM("");
|
||||
try {
|
||||
const purifier = createDOMPurify(dom.window as unknown as Parameters<typeof createDOMPurify>[0]);
|
||||
const html = purifier.sanitize(source, {
|
||||
WHOLE_DOCUMENT: true,
|
||||
ALLOWED_TAGS: ["html", "head", "body", "style", "div", "span", "p", "br", "strong", "em", "b", "i",
|
||||
"svg", "g", "path", "circle", "ellipse", "rect", "line", "polyline", "polygon", "text", "tspan", "title", "desc"],
|
||||
ALLOWED_ATTR: ["class", "id", "style", "viewBox", "xmlns", "width", "height", "x", "y", "x1", "x2", "y1", "y2",
|
||||
"cx", "cy", "r", "rx", "ry", "d", "points", "fill", "stroke", "stroke-width", "stroke-linecap",
|
||||
"stroke-linejoin", "stroke-dasharray", "stroke-dashoffset", "opacity", "transform", "text-anchor"],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
ALLOW_ARIA_ATTR: false,
|
||||
});
|
||||
if (purifier.removed.length) {
|
||||
throw new Error("Animation must contain only visual HTML/CSS or inline SVG; scripts, navigation, resources and interactive elements are not supported");
|
||||
}
|
||||
return html;
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
ANNOUNCEMENT_IMAGE_MAX_BYTES, ANNOUNCEMENT_MANIFEST_MAX_BYTES, ANNOUNCEMENT_ANIMATION_MAX_BYTES,
|
||||
DEFAULT_ANNOUNCEMENT_FEED_URL, announcementManifestSchema, isAnnouncementEligible,
|
||||
type AnnouncementManifest,
|
||||
} from "@paperclipai/shared";
|
||||
import { guardedRemoteHttpFetch } from "./remote-http-fetch.js";
|
||||
import { validateAnnouncementAnimation } from "./announcement-animation.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
export const ANNOUNCEMENT_CACHE_MS = 60 * 60 * 1000;
|
||||
export const ANNOUNCEMENT_FAILURE_MS = 15 * 60 * 1000;
|
||||
const TIMEOUT_MS = 3000;
|
||||
type AnnouncementAsset = { path: string; bytes: Buffer; contentType: string };
|
||||
function assetSlot() {
|
||||
return {
|
||||
cache: null as AnnouncementAsset | null,
|
||||
pending: null as { path: string; promise: Promise<AnnouncementAsset | null> } | null,
|
||||
failure: null as { path: string; retryAt: number } | null,
|
||||
};
|
||||
}
|
||||
export interface AnnouncementFeedOptions {
|
||||
enabled?: boolean;
|
||||
feedUrl?: string;
|
||||
version: string;
|
||||
now?: () => number;
|
||||
fetch?: (url: URL, init: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
export async function readAnnouncementBytes(response: Response, maximum: number): Promise<Buffer> {
|
||||
if (Number(response.headers.get("content-length")) > maximum) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement response is too large");
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return Buffer.alloc(0);
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.byteLength;
|
||||
if (length > maximum) throw new Error("Announcement response is too large");
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks, length);
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {});
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
export function announcementFeedService(options: AnnouncementFeedOptions) {
|
||||
const now = options.now ?? Date.now;
|
||||
const fetchRemote = options.fetch ?? ((url, init) => guardedRemoteHttpFetch(url, init, {
|
||||
error: (message) => new Error(message), dnsTimeoutMs: TIMEOUT_MS,
|
||||
connectTimeoutMs: TIMEOUT_MS, responseTimeoutMs: TIMEOUT_MS,
|
||||
}));
|
||||
let manifest: AnnouncementManifest | null = null;
|
||||
let etag: string | null = null;
|
||||
let nextCheck = 0;
|
||||
let available = false;
|
||||
let pending: Promise<void> | null = null;
|
||||
// One bounded cache slot per media kind, shared across board users.
|
||||
const assets = {
|
||||
image: assetSlot(),
|
||||
animation: assetSlot(),
|
||||
};
|
||||
|
||||
function endpoint() {
|
||||
const url = new URL(options.feedUrl ?? DEFAULT_ANNOUNCEMENT_FEED_URL);
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.hash || url.search) {
|
||||
throw new Error("Announcement feed must be an HTTPS URL without credentials, query, or fragment");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
async function request<T>(url: URL, headers: Record<string, string>, consume: (response: Response) => Promise<T>): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error("Announcement request timed out"));
|
||||
}, TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([
|
||||
fetchRemote(url, { method: "GET", headers, signal: controller.signal, redirect: "error", credentials: "omit" })
|
||||
.then(consume),
|
||||
deadline,
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer!);
|
||||
controller.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const result = await request(endpoint(), {
|
||||
Accept: "application/json", ...(etag ? { "If-None-Match": etag } : {}),
|
||||
}, async (response) => {
|
||||
if (response.status === 304 && manifest) return { manifest, etag, ttl: ANNOUNCEMENT_CACHE_MS };
|
||||
if (response.status === 404) {
|
||||
await response.body?.cancel();
|
||||
// An unpublished/removed feed is an expected empty state. Forget the
|
||||
// previous ETag so recovery cannot resurrect a stale cached card.
|
||||
return { manifest: { schemaVersion: 1, announcement: null } as AnnouncementManifest, etag: null, ttl: ANNOUNCEMENT_FAILURE_MS };
|
||||
}
|
||||
if (!response.ok || response.status >= 300) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement feed unavailable");
|
||||
}
|
||||
if (response.headers.get("content-type")?.split(";")[0]?.trim() !== "application/json") {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement feed is not JSON");
|
||||
}
|
||||
const bytes = await readAnnouncementBytes(response, ANNOUNCEMENT_MANIFEST_MAX_BYTES);
|
||||
return { manifest: announcementManifestSchema.parse(JSON.parse(bytes.toString("utf8"))), etag: response.headers.get("etag"), ttl: ANNOUNCEMENT_CACHE_MS };
|
||||
});
|
||||
manifest = result.manifest;
|
||||
etag = result.etag;
|
||||
available = true;
|
||||
nextCheck = now() + result.ttl;
|
||||
} catch {
|
||||
available = false;
|
||||
nextCheck = now() + ANNOUNCEMENT_FAILURE_MS;
|
||||
// Do not log remote content or operator URLs (which can carry secrets).
|
||||
logger.warn("Announcement feed unavailable; retrying on demand after cooldown");
|
||||
}
|
||||
}
|
||||
|
||||
async function current() {
|
||||
if (options.enabled === false) return null;
|
||||
if (pending) await pending;
|
||||
else if (now() >= nextCheck) {
|
||||
pending = refresh().finally(() => { pending = null; });
|
||||
await pending;
|
||||
}
|
||||
const announcement = available ? manifest?.announcement : null;
|
||||
return announcement && isAnnouncementEligible(announcement, options.version, now()) ? announcement : null;
|
||||
}
|
||||
|
||||
async function asset(id: string, kind: "image" | "animation") {
|
||||
const announcement = await current();
|
||||
const media = announcement?.[kind];
|
||||
if (announcement?.id !== id || !media) return null;
|
||||
const { path } = media;
|
||||
const slot = assets[kind];
|
||||
if (slot.cache?.path === path) return slot.cache;
|
||||
if (slot.pending?.path === path) return slot.pending.promise;
|
||||
if (slot.failure?.path === path && now() < slot.failure.retryAt) return null;
|
||||
const expected = kind === "animation" ? "text/html" : path.endsWith(".png") ? "image/png" : path.endsWith(".jpg") ? "image/jpeg" : "image/webp";
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const result = await request(new URL(path, endpoint()), { Accept: expected }, async (response) => {
|
||||
const contentType = response.headers.get("content-type")?.split(";")[0]?.trim();
|
||||
if (!response.ok || contentType !== expected) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Invalid announcement asset response");
|
||||
}
|
||||
const bytes = await readAnnouncementBytes(response, kind === "animation" ? ANNOUNCEMENT_ANIMATION_MAX_BYTES : ANNOUNCEMENT_IMAGE_MAX_BYTES);
|
||||
const hash = createHash("sha256").update(bytes).digest("hex");
|
||||
if (!path.startsWith(`assets/${hash}.`)) throw new Error("Announcement asset digest mismatch");
|
||||
return { path, bytes: kind === "animation" ? Buffer.from(validateAnnouncementAnimation(bytes)) : bytes, contentType };
|
||||
});
|
||||
slot.cache = result;
|
||||
slot.failure = null;
|
||||
return result;
|
||||
} catch {
|
||||
slot.failure = { path, retryAt: now() + ANNOUNCEMENT_FAILURE_MS };
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
const entry = { path, promise };
|
||||
slot.pending = entry;
|
||||
try { return await promise; }
|
||||
finally { if (slot.pending === entry) slot.pending = null; }
|
||||
}
|
||||
|
||||
return { current, image: (id: string) => asset(id, "image"), animation: (id: string) => asset(id, "animation") };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { announcementDismissals, announcementPublications, type Db } from "@paperclipai/db";
|
||||
import { persistActivity, publishActivity } from "./activity-log.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
export function announcementService(db: Db) {
|
||||
return {
|
||||
async registerPublication(announcementId: string) {
|
||||
await db.insert(announcementPublications).values({ announcementId }).onConflictDoNothing();
|
||||
},
|
||||
async isDismissed(userId: string, announcementId: string) {
|
||||
const row = await db.query.announcementDismissals.findFirst({
|
||||
where: and(eq(announcementDismissals.userId, userId), eq(announcementDismissals.announcementId, announcementId)),
|
||||
});
|
||||
return Boolean(row);
|
||||
},
|
||||
async dismiss(userId: string, announcementId: string, companyId: string) {
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const known = await tx.query.announcementPublications.findFirst({
|
||||
where: eq(announcementPublications.announcementId, announcementId),
|
||||
});
|
||||
if (!known) {
|
||||
// Preserve idempotency for dismissals written before the registry was
|
||||
// added, but never create a new row or audit for an unknown ID.
|
||||
const existing = await tx.query.announcementDismissals.findFirst({
|
||||
where: and(eq(announcementDismissals.userId, userId), eq(announcementDismissals.announcementId, announcementId)),
|
||||
});
|
||||
return { known: Boolean(existing), publication: null };
|
||||
}
|
||||
const [inserted] = await tx.insert(announcementDismissals).values({ userId, announcementId })
|
||||
.onConflictDoNothing().returning();
|
||||
if (!inserted) return { known: true, publication: null };
|
||||
const activity = await persistActivity(tx as unknown as Db, {
|
||||
companyId, actorType: "user", actorId: userId,
|
||||
action: "announcement.dismissed", entityType: "announcement", entityId: announcementId,
|
||||
});
|
||||
return { known: true, publication: activity.publication };
|
||||
});
|
||||
if (result.publication) {
|
||||
try { publishActivity(result.publication); }
|
||||
catch { logger.warn("Could not publish committed announcement dismissal activity"); }
|
||||
}
|
||||
return result.known;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user