Start every Rule private, with a rotating link and files that follow its readers.
New Rules stay off lists until the person who holds the pen turns on a share link, or the team features one. Uploaded files are readable only by those readers, stripped of location metadata, and deleted with the Rule, draft, or account.
This commit is contained in:
1 parent
642551064c
commit
5cbda35e32
50 files changed
+2429
-219
No files matched your search
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractUploadIdsFromUnknown } from "../../lib/server/uploads/extractUploadIds";
|
||||
|
||||
const ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
|
||||
describe("extractUploadIdsFromUnknown", () => {
|
||||
it("collects unique upload ids from nested JSON", () => {
|
||||
expect(
|
||||
extractUploadIdsFromUnknown({
|
||||
logo: `/api/uploads/${ID}`,
|
||||
nested: { also: `/api/uploads/${ID}` },
|
||||
other: "/api/uploads/not-a-uuid",
|
||||
}),
|
||||
).toEqual([ID]);
|
||||
});
|
||||
|
||||
it("returns an empty list when nothing matches", () => {
|
||||
expect(extractUploadIdsFromUnknown({ text: "no files" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,34 +3,26 @@ import {
|
||||
LISTED_PUBLISHED_RULE_WHERE,
|
||||
isListedPublishedRule,
|
||||
} from "../../lib/publishedRuleAccess";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
describe("isListedPublishedRule", () => {
|
||||
it("lists owned rules", () => {
|
||||
it("lists public and featured Rules only", () => {
|
||||
expect(
|
||||
isListedPublishedRule({ userId: "user-1", claimTokenHash: null }),
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("lists ownerless rows that are not waiting on a guest claim", () => {
|
||||
expect(isListedPublishedRule({ userId: null, claimTokenHash: null })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps guest-claim rows unlisted", () => {
|
||||
expect(
|
||||
isListedPublishedRule({
|
||||
userId: null,
|
||||
claimTokenHash: "claim-hash",
|
||||
}),
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.private }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("LISTED_PUBLISHED_RULE_WHERE", () => {
|
||||
it("matches owned rows or rows with no claim token", () => {
|
||||
it("matches public and featured rows", () => {
|
||||
expect(LISTED_PUBLISHED_RULE_WHERE).toEqual({
|
||||
OR: [{ userId: { not: null } }, { claimTokenHash: null }],
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const logAdminRuleReadMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
@@ -17,58 +20,178 @@ vi.mock("../../lib/server/db", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
browserHoldsClaimForHash: (...args: unknown[]) =>
|
||||
browserHoldsClaimForHashMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/adminRuleReadLog", () => ({
|
||||
logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
getPublicPublishedRuleById,
|
||||
getReadablePublishedRule,
|
||||
listListedPublishedRules,
|
||||
listListedPublishedRulesForSitemap,
|
||||
} from "../../lib/server/publishedRules";
|
||||
import { LISTED_PUBLISHED_RULE_WHERE } from "../../lib/publishedRuleAccess";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "owned-1",
|
||||
title: "Owned",
|
||||
summary: "Hi",
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
findUniqueMock.mockReset();
|
||||
findManyMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("getPublicPublishedRuleById", () => {
|
||||
it("returns isListed false for guest-claim rows without exposing claim tokens", async () => {
|
||||
describe("getReadablePublishedRule", () => {
|
||||
it("returns listed public-and-featured Rules to anonymous readers", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: "guest-1",
|
||||
title: "Guest rule",
|
||||
summary: null,
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: null,
|
||||
claimTokenHash: "secret-hash",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
);
|
||||
|
||||
const rule = await getPublicPublishedRuleById("guest-1");
|
||||
expect(rule).toMatchObject({
|
||||
id: "guest-1",
|
||||
title: "Guest rule",
|
||||
isListed: false,
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(rule).not.toHaveProperty("userId");
|
||||
expect(rule).not.toHaveProperty("claimTokenHash");
|
||||
});
|
||||
|
||||
it("returns isListed true for owned rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
expect(resolved?.rule).toMatchObject({
|
||||
id: "owned-1",
|
||||
title: "Owned",
|
||||
summary: "Hi",
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
isListed: true,
|
||||
});
|
||||
expect(resolved?.rule).not.toHaveProperty("userId");
|
||||
expect(resolved?.rule).not.toHaveProperty("claimTokenHash");
|
||||
});
|
||||
|
||||
const rule = await getPublicPublishedRuleById("owned-1");
|
||||
expect(rule?.isListed).toBe(true);
|
||||
it("hides private Rules from anonymous readers", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
expect(
|
||||
await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("lets the publishing browser read a private Rule with the guest claim", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ userId: null, claimTokenHash: "claim-hash" }),
|
||||
);
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(browserHoldsClaimForHashMock).toHaveBeenCalledWith("claim-hash");
|
||||
});
|
||||
|
||||
it("lets the owner read a private Rule by id", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: { id: "user-1", email: "owner@example.org" } as never,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(resolved?.viewerIsOwner).toBe(true);
|
||||
expect(resolved?.rule.isListed).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a shared-by-link Rule as public at /rules/{id}", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("lets anonymous readers use the rotating slug", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "k7f2-9qxm",
|
||||
user: null,
|
||||
viaShareSlug: true,
|
||||
requestPath: "/r/k7f2-9qxm",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(resolved?.rule.isListed).toBe(false);
|
||||
expect(findUniqueMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { shareSlug: "k7f2-9qxm" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs named-admin reads of private Rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: { id: "admin-1", email: "admin@example.org" } as never,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.viewerIsOwner).toBe(false);
|
||||
expect(logAdminRuleReadMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ruleId: "owned-1",
|
||||
adminEmail: "admin@example.org",
|
||||
path: "/rules/owned-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -100,4 +223,15 @@ describe("listListedPublishedRulesForSitemap", () => {
|
||||
expect(await listListedPublishedRulesForSitemap()).toEqual([]);
|
||||
expect(findManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("queries only public and featured Rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findManyMock.mockResolvedValueOnce([]);
|
||||
await listListedPublishedRulesForSitemap();
|
||||
expect(findManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: LISTED_PUBLISHED_RULE_WHERE,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
const findUniqueMock = vi.fn();
|
||||
const updateMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const allocateShareSlugMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||
update: (...args: unknown[]) => updateMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/shareSlug", () => ({
|
||||
allocateShareSlug: (...args: unknown[]) => allocateShareSlugMock(...args),
|
||||
}));
|
||||
|
||||
import { patchOwnedRuleShare } from "../../lib/server/ruleShare";
|
||||
|
||||
const owner = { id: "user-1", email: "owner@example.org" } as never;
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "rule-1",
|
||||
title: "Juniper Street Food Share",
|
||||
userId: "user-1",
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
findUniqueMock.mockReset();
|
||||
updateMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
allocateShareSlugMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
updateMock.mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe("patchOwnedRuleShare", () => {
|
||||
it("allocates a new slug when turning a private Rule on", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("k7f2-9qxm");
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(allocateShareSlugMock).toHaveBeenCalledTimes(1);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("requires community agreement the first time a link turns on", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
});
|
||||
expect(result).toEqual({ ok: false, reason: "community_agreed" });
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forbids the owner from setting public and featured", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
expect(result).toEqual({ ok: false, reason: "forbidden" });
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets a named admin set public and featured", async () => {
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
const admin = { id: "admin-1", email: "ops@example.org" } as never;
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
user: { email: "owner@example.org" },
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: admin,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
shareSlug: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("allocates a new slug after a link is turned off and on again", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "abcd-efgh",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("abcd-efgh");
|
||||
|
||||
const first = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
expect(first.ok).toBe(true);
|
||||
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "abcd-efgh",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(row());
|
||||
const off = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "private",
|
||||
});
|
||||
expect(off.ok).toBe(true);
|
||||
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "wxyz-1234",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("wxyz-1234");
|
||||
const second = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
expect(second.ok).toBe(true);
|
||||
expect(allocateShareSlugMock).toHaveBeenCalledTimes(2);
|
||||
expect(updateMock).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "wxyz-1234",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the slug when the link is turned off", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(row());
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
emailInitials,
|
||||
visibleShareReaders,
|
||||
type SharePerson,
|
||||
} from "../../lib/ruleShareTypes";
|
||||
|
||||
const readers: SharePerson[] = [
|
||||
{ email: "rosa@example.org", initials: "R", role: "reader" },
|
||||
{ email: "a@example.org", initials: "A", role: "reader" },
|
||||
{ email: "b@example.org", initials: "B", role: "reader" },
|
||||
];
|
||||
|
||||
describe("visibleShareReaders", () => {
|
||||
it("shows every reader when there is at most one", () => {
|
||||
expect(visibleShareReaders([])).toEqual({ shown: [], overflowCount: 0 });
|
||||
expect(visibleShareReaders(readers.slice(0, 1))).toEqual({
|
||||
shown: readers.slice(0, 1),
|
||||
overflowCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the first reader and counts the rest", () => {
|
||||
expect(visibleShareReaders(readers)).toEqual({
|
||||
shown: readers.slice(0, 1),
|
||||
overflowCount: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("emailInitials", () => {
|
||||
it("uses the first character of the local part", () => {
|
||||
expect(emailInitials("rosa@example.org")).toBe("R");
|
||||
expect(emailInitials("")).toBe("?");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
RULE_VISIBILITY,
|
||||
canReadPublishedRule,
|
||||
isListedPublishedRule,
|
||||
isPrivilegedAdminRead,
|
||||
type PublishedRuleReadAccess,
|
||||
} from "../../lib/ruleVisibility";
|
||||
|
||||
function access(
|
||||
overrides: Partial<PublishedRuleReadAccess> = {},
|
||||
): PublishedRuleReadAccess {
|
||||
return {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
viaShareSlug: false,
|
||||
userId: null,
|
||||
ownerUserId: "owner-1",
|
||||
viewerEmail: null,
|
||||
invitedEmails: [],
|
||||
invitedUserIds: [],
|
||||
isAdmin: false,
|
||||
holdsGuestClaim: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isListedPublishedRule", () => {
|
||||
it("lists only public and featured Rules", () => {
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.private }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canReadPublishedRule", () => {
|
||||
it("lets the owner, invited people, guest claim, and named admins read a private Rule", () => {
|
||||
expect(canReadPublishedRule(access())).toBe(false);
|
||||
expect(canReadPublishedRule(access({ userId: "owner-1" }))).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({ viewerEmail: "rosa@example.org", invitedEmails: ["rosa@example.org"] }),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(access({ userId: "u-2", invitedUserIds: ["u-2"] })),
|
||||
).toBe(true);
|
||||
expect(canReadPublishedRule(access({ holdsGuestClaim: true }))).toBe(true);
|
||||
expect(canReadPublishedRule(access({ isAdmin: true }))).toBe(true);
|
||||
});
|
||||
|
||||
it("lets anyone with the rotating slug read a shared-by-link Rule", () => {
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: true,
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: false,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("lets anyone read a public and featured Rule", () => {
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrivilegedAdminRead", () => {
|
||||
it("is true only when a named admin would otherwise be denied", () => {
|
||||
expect(isPrivilegedAdminRead(access({ isAdmin: true }))).toBe(true);
|
||||
expect(
|
||||
isPrivilegedAdminRead(access({ isAdmin: true, userId: "owner-1" })),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPrivilegedAdminRead(
|
||||
access({
|
||||
isAdmin: true,
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPrivilegedAdminRead(
|
||||
access({
|
||||
isAdmin: true,
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: true,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
||||
deleteUploadsForRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { DELETE } from "../../app/api/rules/[id]/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
|
||||
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/linkUploads", () => ({
|
||||
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { PATCH } from "../../app/api/rules/[id]/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
|
||||
@@ -4,6 +4,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const logAdminRuleReadMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
@@ -21,17 +24,54 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
browserHoldsClaimForHash: (...args: unknown[]) =>
|
||||
browserHoldsClaimForHashMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/adminRuleReadLog", () => ({
|
||||
logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/rules/[id]/route";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
function makeContext(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
findUniqueMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("GET /api/rules/[id]", () => {
|
||||
@@ -86,80 +126,39 @@ describe("GET /api/rules/[id]", () => {
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 with { rule, viewerIsOwner: false } when a published rule exists and the viewer is anonymous", async () => {
|
||||
it("returns 404 for a private Rule when the viewer is anonymous", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
};
|
||||
findUniqueMock.mockResolvedValueOnce(row);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 for a public and featured Rule when the viewer is anonymous", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
rule: {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
isListed: boolean;
|
||||
};
|
||||
rule: { id: string; isListed: boolean };
|
||||
viewerIsOwner: boolean;
|
||||
};
|
||||
expect(body.rule.id).toBe("rule-1");
|
||||
expect(body.rule.title).toBe("Mutual Aid Mondays");
|
||||
expect(body.rule.summary).toBe("A grassroots community in Denver.");
|
||||
expect(body.rule.isListed).toBe(true);
|
||||
expect(body.viewerIsOwner).toBe(false);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("marks guest-claim rules as unlisted without exposing the claim token", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: "guest-1",
|
||||
title: "Unlisted",
|
||||
summary: null,
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: null,
|
||||
claimTokenHash: "secret-hash",
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/guest-1"),
|
||||
makeContext("guest-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
rule: { isListed: boolean; claimTokenHash?: unknown; userId?: unknown };
|
||||
};
|
||||
expect(body.rule.isListed).toBe(false);
|
||||
expect(body.rule).not.toHaveProperty("claimTokenHash");
|
||||
expect(body.rule).not.toHaveProperty("userId");
|
||||
});
|
||||
|
||||
it("returns viewerIsOwner true when the signed-in user owns the rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
};
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row)
|
||||
.mockResolvedValueOnce({ userId: "user-1" });
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
@@ -167,23 +166,70 @@ describe("GET /api/rules/[id]", () => {
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { viewerIsOwner: boolean };
|
||||
expect(body.viewerIsOwner).toBe(true);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(2);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns viewerIsOwner false when the signed-in user does not own the rule", async () => {
|
||||
it("returns 404 for a shared-by-link Rule at the internal id", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
};
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row)
|
||||
.mockResolvedValueOnce({ userId: "other" });
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 when the browser holds the guest claim", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ userId: null, claimTokenHash: "claim-hash" }),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("logs named-admin reads of a private Rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({
|
||||
id: "admin-1",
|
||||
email: "ops@example.org",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(logAdminRuleReadMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ruleId: "rule-1",
|
||||
adminEmail: "ops@example.org",
|
||||
path: "/api/rules/rule-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 200 for an invited reader of a private Rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({
|
||||
id: "reader-1",
|
||||
email: "rosa@example.org",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
stakeholders: [{ email: "rosa@example.org", userId: "reader-1" }],
|
||||
}),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
|
||||
@@ -44,6 +44,10 @@ vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
issueGuestRuleClaimCookieMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/linkUploads", () => ({
|
||||
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
$transaction: (fn: (tx: unknown) => Promise<unknown>) =>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const getOwnedRuleShareSettingsMock = vi.fn();
|
||||
const patchOwnedRuleShareMock = vi.fn();
|
||||
const getPublicOriginMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/publicOrigin", () => ({
|
||||
getPublicOrigin: (...args: unknown[]) => getPublicOriginMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleShare", () => ({
|
||||
getOwnedRuleShareSettings: (...args: unknown[]) =>
|
||||
getOwnedRuleShareSettingsMock(...args),
|
||||
patchOwnedRuleShare: (...args: unknown[]) => patchOwnedRuleShareMock(...args),
|
||||
}));
|
||||
|
||||
import { GET, PATCH } from "../../app/api/rules/[id]/share/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
getOwnedRuleShareSettingsMock.mockReset();
|
||||
patchOwnedRuleShareMock.mockReset();
|
||||
getPublicOriginMock.mockReset();
|
||||
getPublicOriginMock.mockReturnValue("https://communityrule.info");
|
||||
});
|
||||
|
||||
describe("GET /api/rules/[id]/share", () => {
|
||||
it("returns 401 when not signed in", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns share settings for the owner", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
getOwnedRuleShareSettingsMock.mockResolvedValueOnce({
|
||||
visibility: "private",
|
||||
shareUrl: "https://communityrule.info/rules/rule-1",
|
||||
title: "Juniper",
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { share: { visibility: string } };
|
||||
expect(body.share.visibility).toBe("private");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH /api/rules/[id]/share", () => {
|
||||
it("returns 400 when community agreement is missing", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
patchOwnedRuleShareMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
reason: "community_agreed",
|
||||
});
|
||||
const res = await PATCH(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ visibility: "shared_by_link" }),
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,14 @@ vi.mock("../../lib/server/uploads/uploadRoot", async () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { saveCreateFlowUpload } from "../../lib/server/uploads/saveCreateFlowUpload";
|
||||
|
||||
const PNG_1X1 = Buffer.from(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
import {
|
||||
buildShareRuleUrl,
|
||||
formatShareUrlDisplay,
|
||||
isShareSlug,
|
||||
shareCopyUrl,
|
||||
shareRulePath,
|
||||
} from "../../lib/sharePaths";
|
||||
|
||||
describe("sharePaths", () => {
|
||||
it("accepts the rotating slug shape", () => {
|
||||
expect(isShareSlug("k7f2-9qxm")).toBe(true);
|
||||
expect(isShareSlug("K7F2-9QXM")).toBe(false);
|
||||
expect(isShareSlug("not-a-slug")).toBe(false);
|
||||
});
|
||||
|
||||
it("builds /r/{slug} URLs and the display host+path", () => {
|
||||
expect(shareRulePath("k7f2-9qxm")).toBe("/r/k7f2-9qxm");
|
||||
expect(buildShareRuleUrl("https://communityrule.info", "k7f2-9qxm")).toBe(
|
||||
"https://communityrule.info/r/k7f2-9qxm",
|
||||
);
|
||||
expect(
|
||||
formatShareUrlDisplay("https://communityrule.info", "k7f2-9qxm"),
|
||||
).toBe("communityrule.info/r/k7f2-9qxm");
|
||||
});
|
||||
|
||||
it("copies the slug URL once a link is on, otherwise the internal Rule URL", () => {
|
||||
expect(
|
||||
shareCopyUrl({
|
||||
origin: "https://communityrule.info",
|
||||
ruleId: "rule-1",
|
||||
shareSlug: "k7f2-9qxm",
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
}),
|
||||
).toBe("https://communityrule.info/r/k7f2-9qxm");
|
||||
expect(
|
||||
shareCopyUrl({
|
||||
origin: "https://communityrule.info",
|
||||
ruleId: "rule-1",
|
||||
shareSlug: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
}),
|
||||
).toBe("https://communityrule.info/rules/rule-1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { isShareSlug } from "../../lib/sharePaths";
|
||||
import { generateShareSlug } from "../../lib/server/shareSlug";
|
||||
|
||||
describe("generateShareSlug", () => {
|
||||
it("returns the rotating slug shape", () => {
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
expect(isShareSlug(generateShareSlug())).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -227,7 +227,7 @@ describe("buildRobots", () => {
|
||||
});
|
||||
|
||||
describe("robotsForPublishedRule", () => {
|
||||
it("leaves listed rules indexable and noindexes unlisted guest-claim pages", () => {
|
||||
it("leaves public-and-featured Rules indexable and noindexes private and shared-by-link pages", () => {
|
||||
expect(robotsForPublishedRule(true)).toBeUndefined();
|
||||
expect(robotsForPublishedRule(false)).toEqual(NO_INDEX_ROBOTS);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { stripImageMetadata } from "../../lib/server/uploads/stripImageMetadata";
|
||||
|
||||
describe("stripImageMetadata", () => {
|
||||
it("drops JPEG APP1 EXIF", () => {
|
||||
const jpeg = Buffer.from([
|
||||
0xff, 0xd8, 0xff, 0xe1, 0x00, 0x06, 0x45, 0x78, 0x69, 0x66, 0xff, 0xda,
|
||||
0x00, 0x01,
|
||||
]);
|
||||
const out = stripImageMetadata(jpeg, "image/jpeg");
|
||||
expect(out[0]).toBe(0xff);
|
||||
expect(out[1]).toBe(0xd8);
|
||||
expect(out.includes(0x45)).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves non-image bytes unchanged", () => {
|
||||
const pdf = Buffer.from("%PDF-1.4");
|
||||
expect(stripImageMetadata(pdf, "application/pdf")).toBe(pdf);
|
||||
});
|
||||
});
|
||||
@@ -5,18 +5,61 @@ import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const getUploadRootFromEnvMock = vi.fn();
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const getReadablePublishedRuleMock = vi.fn();
|
||||
const browserHoldsUploadGrantMock = vi.fn();
|
||||
let uploadRoot: string | null = null;
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadRoot", () => ({
|
||||
getUploadRootFromEnv: () => getUploadRootFromEnvMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/publishedRules", () => ({
|
||||
getReadablePublishedRule: (...args: unknown[]) =>
|
||||
getReadablePublishedRuleMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadGrantCookie", () => ({
|
||||
browserHoldsUploadGrant: (...args: unknown[]) =>
|
||||
browserHoldsUploadGrantMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/uploads/[id]/route";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
const FEATURED_ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const PRIVATE_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||
|
||||
beforeEach(async () => {
|
||||
uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-test-"));
|
||||
getUploadRootFromEnvMock.mockReset();
|
||||
getUploadRootFromEnvMock.mockImplementation(() => uploadRoot);
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
getReadablePublishedRuleMock.mockReset();
|
||||
browserHoldsUploadGrantMock.mockReset();
|
||||
browserHoldsUploadGrantMock.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -34,6 +77,7 @@ describe("GET /api/uploads/[id]", () => {
|
||||
});
|
||||
|
||||
it("returns 404 when the upload is not found", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(null);
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
"https://x.test/api/uploads/550e8400-e29b-41d4-a716-446655440000",
|
||||
@@ -47,16 +91,93 @@ describe("GET /api/uploads/[id]", () => {
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns the file bytes with content type", async () => {
|
||||
const id = "550e8400-e29b-41d4-a716-446655440000";
|
||||
await writeFile(path.join(uploadRoot!, `${id}.png`), "png-bytes");
|
||||
it("returns featured file bytes with a short public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${FEATURED_ID}.png`), "png-bytes");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: FEATURED_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-1",
|
||||
rule: { visibility: RULE_VISIBILITY.public_and_featured },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
rule: { isListed: true },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${id}`),
|
||||
{ params: Promise.resolve({ id }) },
|
||||
new NextRequest(`https://x.test/api/uploads/${FEATURED_ID}`),
|
||||
{ params: Promise.resolve({ id: FEATURED_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Content-Type")).toBe("image/png");
|
||||
expect(res.headers.get("Cache-Control")).toContain("immutable");
|
||||
expect(res.headers.get("Cache-Control")).toBe("public, max-age=3600");
|
||||
expect(await res.text()).toBe("png-bytes");
|
||||
});
|
||||
|
||||
it("returns 404 for a private file the viewer cannot read", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-private",
|
||||
rule: { visibility: RULE_VISIBILITY.private },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce(null);
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get("Cache-Control")).toBeNull();
|
||||
});
|
||||
|
||||
it("serves a shared-by-link file to an anonymous viewer without a public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "shared");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-shared",
|
||||
rule: { visibility: RULE_VISIBILITY.shared_by_link },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
rule: { isListed: false },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(getReadablePublishedRuleMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ viaShareSlug: true }),
|
||||
);
|
||||
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
|
||||
});
|
||||
|
||||
it("serves a private file to a permitted reader without a public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "private");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: "user-1",
|
||||
draftId: null,
|
||||
ruleId: "rule-private",
|
||||
rule: { visibility: RULE_VISIBILITY.private },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
rule: { isListed: false },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
|
||||
expect(await res.text()).toBe("private");
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
clearSessionCookie: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
||||
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { DELETE } from "../../app/api/user/me/route";
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
Reference in new issue
Block a user