create-freeholder 0.2.0-beta.5 → 0.2.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/template/.changeset/blog-playground-content.md +4 -0
- package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
- package/dist/template/.changeset/managed-preview-assistant.md +4 -0
- package/dist/template/.changeset/public-beta-6.md +4 -0
- package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
- package/dist/template/MASTER.md +81 -8
- package/dist/template/README.md +1 -1
- package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
- package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
- package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
- package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
- package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
- package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
- package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
- package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
- package/dist/template/app/(admin)/assistant-actions.ts +13 -6
- package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
- package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
- package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
- package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
- package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
- package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
- package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
- package/dist/template/db/migrations/meta/_journal.json +14 -0
- package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
- package/dist/template/deploy/docker-selfhost/.env.example +1 -1
- package/dist/template/deploy/docker-selfhost/README.md +3 -2
- package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +1 -1
- package/dist/template/deploy/docker-selfhost/infra/compose.yml +1 -1
- package/dist/template/deploy/f-criteria-matrix.md +74 -0
- package/dist/template/deploy/linux/README.md +1 -1
- package/dist/template/deploy/linux/install.sh +1 -1
- package/dist/template/deploy/managed-preview-assistant.md +99 -0
- package/dist/template/eslint.config.mjs +3 -1
- package/dist/template/locales/ar.json +85 -6
- package/dist/template/locales/en.json +83 -4
- package/dist/template/locales/es.json +83 -4
- package/dist/template/locales/fr.json +85 -6
- package/dist/template/next.config.ts +2 -0
- package/dist/template/package.json +1 -1
- package/dist/template/packages/cli/package.json +1 -1
- package/dist/template/packages/create-freeholder/package.json +1 -1
- package/dist/template/packages/freeholder-app/package.json +1 -1
- package/dist/template/packages/mobile-app/package.json +1 -1
- package/dist/template/packages/plugin-kit/package.json +1 -1
- package/dist/template/packages/sdk/package.json +1 -1
- package/dist/template/packages/sdk/src/generated.ts +177 -9
- package/dist/template/packages/sdk/src/version.ts +1 -1
- package/dist/template/packages/templates/package.json +1 -1
- package/dist/template/proxy.ts +18 -1
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
- package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
- package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
- package/dist/template/scripts/license-headers.mjs +3 -0
- package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
- package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
- package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
- package/dist/template/src/adapters/ai/types.ts +5 -0
- package/dist/template/src/adapters/paradise/assistant.ts +37 -0
- package/dist/template/src/adapters/paradise/http.ts +4 -3
- package/dist/template/src/core/contract/json-schema.ts +8 -0
- package/dist/template/src/core/demo/playground-inserts.ts +29 -0
- package/dist/template/src/core/demo/playground-policy.ts +9 -0
- package/dist/template/src/core/env.ts +2 -0
- package/dist/template/src/core/http/csp.ts +10 -2
- package/dist/template/src/core/http/csrf-client.ts +10 -0
- package/dist/template/src/core/import/service.ts +217 -12
- package/dist/template/src/core/import/wordpress.ts +80 -15
- package/dist/template/src/core/notifications/service.ts +1 -0
- package/dist/template/src/core/retention/registry.ts +2 -0
- package/dist/template/src/core/search/registry.ts +2 -0
- package/dist/template/src/core/seo/feeds.ts +2 -0
- package/dist/template/src/core/seo/jsonld.ts +46 -2
- package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
- package/dist/template/src/core/seo/meta.ts +10 -7
- package/dist/template/src/core/seo/service.ts +14 -1
- package/dist/template/src/core/update/release-declaration.json +1 -1
- package/dist/template/src/modules/assistant/contract.ts +1 -1
- package/dist/template/src/modules/assistant/limits.ts +3 -0
- package/dist/template/src/modules/assistant/preview.ts +124 -0
- package/dist/template/src/modules/assistant/provider.ts +7 -0
- package/dist/template/src/modules/assistant/service.ts +21 -5
- package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
- package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
- package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
- package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
- package/dist/template/src/modules/cms/blog-comments.ts +111 -0
- package/dist/template/src/modules/cms/blog-schema.ts +146 -0
- package/dist/template/src/modules/cms/blog-service.ts +999 -0
- package/dist/template/src/modules/cms/blog.tsx +245 -25
- package/dist/template/src/modules/cms/manifest.ts +7 -1
- package/dist/template/src/modules/cms/read.ts +18 -0
- package/dist/template/src/modules/cms/service.ts +22 -4
- package/dist/template/src/modules/cms/tables.ts +2 -0
- package/dist/template/src/modules/seed/launch.ts +31 -3
- package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
- package/dist/template/tests/core/analytics-consent.test.ts +1 -1
- package/dist/template/tests/core/blog-playground.test.ts +106 -0
- package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
- package/dist/template/tests/core/csp.test.ts +1 -1
- package/dist/template/tests/core/internal-services.test.ts +4 -0
- package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
- package/dist/template/tests/core/locale-routing.test.ts +1 -1
- package/dist/template/tests/core/playground-cache.test.ts +1 -1
- package/dist/template/tests/core/playground.test.ts +3 -3
- package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
- package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
- package/dist/template/tests/core/private-preview.test.ts +1 -1
- package/dist/template/tests/core/proxy-locale.test.ts +1 -1
- package/dist/template/tests/core/sdk-schema.test.ts +20 -0
- package/dist/template/tests/core/seo.test.ts +1 -1
- package/dist/template/tests/core/site-chat-client.test.ts +50 -0
- package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
- package/dist/template/tests/core/wordpress-import.test.ts +25 -12
- package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
- package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
- package/dist/template-manifest.json +349 -139
- package/package.json +1 -1
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { count, eq } from "drizzle-orm";
|
|
5
|
+
import { db } from "@/core/db";
|
|
6
|
+
import { validateSession } from "@/core/auth/sessions";
|
|
7
|
+
import { resetEnvForTests } from "@/core/env";
|
|
8
|
+
import { enterPlayground, initializePlayground, markPlaygroundBaseline } from "@/core/demo/playground";
|
|
9
|
+
import { createRole } from "@/core/roles/service";
|
|
10
|
+
import { publishPage } from "@/modules/cms/service";
|
|
11
|
+
import { pages } from "@/modules/cms/schema";
|
|
12
|
+
import { blogAuthors, blogTerms } from "@/modules/cms/blog-schema";
|
|
13
|
+
import { createPost, saveAuthor, saveTerm, deleteAuthor, deleteTerm, setPostMeta, postMetaAt, updateBlogSettings } from "@/modules/cms/blog-service";
|
|
14
|
+
import { listReaderComments, moderateReaderComment, submitReaderComment } from "@/modules/cms/blog-comments";
|
|
15
|
+
import { ANONYMOUS, closeDb, hasDatabase, truncateSpine } from "../helpers/spine";
|
|
16
|
+
|
|
17
|
+
const browser = vi.hoisted(() => ({ token: "" }));
|
|
18
|
+
vi.mock("next/headers", () => ({
|
|
19
|
+
cookies: async () => ({ get: (name: string) => name === "freeholder_session" && browser.token ? { value: browser.token } : undefined }),
|
|
20
|
+
headers: async () => new Headers(),
|
|
21
|
+
}));
|
|
22
|
+
vi.mock("next/navigation", () => ({
|
|
23
|
+
redirect: (url: string) => { throw Object.assign(new Error("NEXT_REDIRECT"), { url }); },
|
|
24
|
+
}));
|
|
25
|
+
vi.mock("next/cache", () => ({ revalidatePath: () => undefined }));
|
|
26
|
+
const { createBlogPostAction } = await import("../../app/(admin)/admin/blog/actions");
|
|
27
|
+
|
|
28
|
+
describe.runIf(hasDatabase)("editable blog in the disposable playground", () => {
|
|
29
|
+
beforeEach(async () => {
|
|
30
|
+
await truncateSpine();
|
|
31
|
+
vi.stubEnv("FREEHOLDER_PLAYGROUND", "1");
|
|
32
|
+
resetEnvForTests();
|
|
33
|
+
await initializePlayground();
|
|
34
|
+
await markPlaygroundBaseline();
|
|
35
|
+
});
|
|
36
|
+
afterEach(() => { vi.unstubAllEnvs(); resetEnvForTests(); });
|
|
37
|
+
afterAll(closeDb);
|
|
38
|
+
|
|
39
|
+
async function visitor() {
|
|
40
|
+
const issued = await enterPlayground.call({}, ANONYMOUS);
|
|
41
|
+
browser.token = issued.token;
|
|
42
|
+
const session = await db().transaction(tx => validateSession(tx, issued.token));
|
|
43
|
+
if (!session) throw new Error("No playground session");
|
|
44
|
+
return { kind: "user" as const, userId: session.userId, role: session.role, grants: session.grants };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
it("lets the actual visitor create, publish and moderate a blog without gaining authority", async () => {
|
|
48
|
+
const actor = await visitor();
|
|
49
|
+
const author = await saveAuthor.call({ name: "Demo writer", email: "writer@example.test" }, actor);
|
|
50
|
+
const category = await saveTerm.call({ taxonomy: "category", name: "Demo category" }, actor);
|
|
51
|
+
const tag = await saveTerm.call({ taxonomy: "tag", name: "Demo tag" }, actor);
|
|
52
|
+
const form = new FormData();
|
|
53
|
+
form.set("title", "Demo post"); form.set("slug", "demo-post");
|
|
54
|
+
const redirected: unknown = await createBlogPostAction(form).catch((error: unknown) => error);
|
|
55
|
+
if (!(redirected instanceof Error) || !("url" in redirected)) throw new Error("Expected the editor redirect");
|
|
56
|
+
expect(redirected.url).toMatch(/^\/admin\/pages\/[0-9a-f-]+$/);
|
|
57
|
+
const [post] = await db().select().from(pages).where(eq(pages.slug, "blog/demo-post"));
|
|
58
|
+
if (!post) throw new Error("Blog action did not create its draft");
|
|
59
|
+
await setPostMeta.call({ pageId: post.id, isPost: true, authorId: author.id, categoryIds: [category.id], tagIds: [tag.id] }, actor);
|
|
60
|
+
await saveAuthor.call({ id: author.id, name: "Updated demo writer" }, actor);
|
|
61
|
+
await saveTerm.call({ id: category.id, taxonomy: "category", name: "Updated category" }, actor);
|
|
62
|
+
await updateBlogSettings.call({ postsPerPage: 8, commentsEnabled: true }, actor);
|
|
63
|
+
await publishPage.call({ id: post.id, published: true }, actor);
|
|
64
|
+
const metadata = await postMetaAt.call({ slug: "blog/demo-post" }, ANONYMOUS);
|
|
65
|
+
expect(metadata?.author?.name).toBe("Updated demo writer");
|
|
66
|
+
expect(JSON.stringify(metadata)).not.toContain("writer@example.test");
|
|
67
|
+
const comment = await submitReaderComment.call({ pageId: post.id, name: "Demo reader", email: "reader@example.test", body: "An ordinary comment" }, ANONYMOUS);
|
|
68
|
+
expect(await listReaderComments.call({ pageId: post.id }, ANONYMOUS)).toEqual([]);
|
|
69
|
+
await moderateReaderComment.call({ id: comment.id, status: "approved" }, actor);
|
|
70
|
+
const visible = await listReaderComments.call({ pageId: post.id }, ANONYMOUS);
|
|
71
|
+
expect(visible).toHaveLength(1);
|
|
72
|
+
expect(JSON.stringify(visible)).not.toContain("reader@example.test");
|
|
73
|
+
await deleteTerm.call({ id: tag.id }, actor);
|
|
74
|
+
await deleteAuthor.call({ id: author.id }, actor);
|
|
75
|
+
await expect(createRole.call({ name: "Escalation", grants: [{ module: "*", access: "manage" }] }, actor)).rejects.toMatchObject({ code: "permission" });
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("bounds blog rows and rolls an over-budget inline tag batch back atomically", async () => {
|
|
79
|
+
const actor = await visitor();
|
|
80
|
+
const post = await createPost.call({ title: "Bounded post", slug: "bounded" }, actor);
|
|
81
|
+
await db().insert(pages).values(Array.from({ length: 49 }, (_, i) => ({ slug: `filler-${i}`, title: `Filler ${i}` })));
|
|
82
|
+
await db().insert(blogAuthors).values(Array.from({ length: 50 }, (_, i) => ({ slug: `writer-${i}`, path: `author/writer-${i}`, name: `Writer ${i}` })));
|
|
83
|
+
await db().insert(blogTerms).values(Array.from({ length: 99 }, (_, i) => ({ taxonomy: "tag" as const, slug: `tag-${i}`, path: `tag/tag-${i}`, name: `Tag ${i}` })));
|
|
84
|
+
await expect(createPost.call({ title: "Over budget", slug: "overflow" }, actor)).rejects.toMatchObject({ code: "rate_limited" });
|
|
85
|
+
await expect(saveAuthor.call({ name: "Over budget" }, actor)).rejects.toMatchObject({ code: "rate_limited" });
|
|
86
|
+
await expect(setPostMeta.call({ pageId: post.id, tagNames: ["First new", "Second new"] }, actor)).rejects.toMatchObject({ code: "rate_limited" });
|
|
87
|
+
expect((await db().select({ total: count() }).from(blogTerms))[0]?.total).toBe(99);
|
|
88
|
+
await setPostMeta.call({ pageId: post.id, tagNames: ["Exactly one"] }, actor);
|
|
89
|
+
expect((await db().select({ total: count() }).from(blogTerms))[0]?.total).toBe(100);
|
|
90
|
+
await expect(saveTerm.call({ taxonomy: "category", name: "Over budget" }, actor)).rejects.toMatchObject({ code: "rate_limited" });
|
|
91
|
+
await expect(setPostMeta.call({ pageId: post.id, tagNames: ["Another new"] }, actor)).rejects.toMatchObject({ code: "rate_limited" });
|
|
92
|
+
expect((await db().select({ total: count() }).from(pages))[0]?.total).toBe(50);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("lets only one concurrent creator take the last taxonomy slot", async () => {
|
|
96
|
+
const actor = await visitor();
|
|
97
|
+
await db().insert(blogTerms).values(Array.from({ length: 99 }, (_, i) => ({ taxonomy: "tag" as const, slug: `tag-${i}`, path: `tag/tag-${i}`, name: `Tag ${i}` })));
|
|
98
|
+
const outcomes = await Promise.allSettled([
|
|
99
|
+
saveTerm.call({ taxonomy: "tag", name: "Concurrent one" }, actor),
|
|
100
|
+
saveTerm.call({ taxonomy: "tag", name: "Concurrent two" }, actor),
|
|
101
|
+
]);
|
|
102
|
+
expect(outcomes.filter(result => result.status === "fulfilled")).toHaveLength(1);
|
|
103
|
+
expect(outcomes.find(result => result.status === "rejected")).toMatchObject({ reason: { code: "rate_limited" } });
|
|
104
|
+
expect((await db().select({ total: count() }).from(blogTerms))[0]?.total).toBe(100);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { afterAll, beforeEach, describe, expect, it } from "vitest";
|
|
4
|
+
import { eq } from "drizzle-orm";
|
|
5
|
+
import { db } from "@/core/db";
|
|
6
|
+
import { users } from "@/core/auth/schema";
|
|
7
|
+
import { contacts } from "@/core/contacts/schema";
|
|
8
|
+
import { createContact, mergeContacts, undoContactMerge } from "@/core/contacts/service";
|
|
9
|
+
import { contactPrivacySources } from "@/core/privacy/service";
|
|
10
|
+
import { notifications } from "@/core/notifications/schema";
|
|
11
|
+
import { registerPublishVeto } from "@/core/privacy/publish-veto";
|
|
12
|
+
import { resolveRedirect } from "@/core/seo/service";
|
|
13
|
+
import { createPage, publishPage, updatePage, resolvePage } from "@/modules/cms/service";
|
|
14
|
+
import { saveAuthor, saveTerm, setPostMeta, postMetaAt, resolveBlogArchive, updateBlogSettings, publicBlogCategories } from "@/modules/cms/blog-service";
|
|
15
|
+
import { listBlogPosts } from "@/modules/cms/blog";
|
|
16
|
+
import { blogReaderComments as comments } from "@/modules/cms/blog-comments-schema";
|
|
17
|
+
import { submitReaderComment, listReaderComments, moderateReaderComment, listReaderCommentsForOwner } from "@/modules/cms/blog-comments";
|
|
18
|
+
import { ANONYMOUS, closeDb, hasDatabase, OWNER, truncateSpine } from "../helpers/spine";
|
|
19
|
+
|
|
20
|
+
async function post(slug = "2025/03/original-address") {
|
|
21
|
+
const page = await createPage.call({ title: "A post", slug, blocks: [{ id: "heading", type: "heading", props: { text: "A post", level: 1 } }] }, OWNER);
|
|
22
|
+
await setPostMeta.call({ pageId: page.id, isPost: true }, OWNER);
|
|
23
|
+
await publishPage.call({ id: page.id, published: true }, OWNER);
|
|
24
|
+
return page;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe.runIf(hasDatabase)("blog structure and moderated reader comments", () => {
|
|
28
|
+
beforeEach(async () => {
|
|
29
|
+
await truncateSpine();
|
|
30
|
+
await db().insert(users).values({ id: OWNER.userId, email: "owner@example.test", role: "owner" });
|
|
31
|
+
});
|
|
32
|
+
afterAll(closeDb);
|
|
33
|
+
|
|
34
|
+
it("keeps arbitrary post permalinks, category descendants and private author details out of public output", async () => {
|
|
35
|
+
const page = await post();
|
|
36
|
+
const author = await saveAuthor.call({ name: "Reader Writer", email: "private@example.test", bio: "An author" }, OWNER);
|
|
37
|
+
const parent = await saveTerm.call({ taxonomy: "category", name: "Parent" }, OWNER);
|
|
38
|
+
const child = await saveTerm.call({ taxonomy: "category", name: "Child", parentId: parent.id }, OWNER);
|
|
39
|
+
await setPostMeta.call({ pageId: page.id, isPost: true, authorId: author.id, categoryIds: [child.id], tagNames: ["One", "One"] }, OWNER);
|
|
40
|
+
const meta = await postMetaAt.call({ slug: page.slug }, ANONYMOUS);
|
|
41
|
+
expect(meta?.author).toEqual({ name: "Reader Writer", path: author.path, bio: "An author" });
|
|
42
|
+
expect(JSON.stringify(meta)).not.toContain("private@example.test");
|
|
43
|
+
const listing = await listBlogPosts.call({ category: parent.slug }, ANONYMOUS);
|
|
44
|
+
expect(listing.posts.map(entry => entry.slug)).toEqual([page.slug]);
|
|
45
|
+
expect(await resolveBlogArchive.call({ path: parent.path }, ANONYMOUS)).toMatchObject({ posts: 1 });
|
|
46
|
+
const moved = await saveTerm.call({ id: parent.id, taxonomy: "category", name: "Renamed", slug: "renamed" }, OWNER);
|
|
47
|
+
expect(await resolveRedirect.call({ path: child.path }, ANONYMOUS)).toEqual({ toPath: `${moved.path}/child`, status: "301" });
|
|
48
|
+
await expect(saveTerm.call({ id: parent.id, taxonomy: "category", name: "Bad", parentId: child.id }, OWNER)).rejects.toMatchObject({ code: "validation" });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("holds new comments, sends one owner notification, publishes escaped plain text only after approval, and supports replies", async () => {
|
|
52
|
+
const page = await post();
|
|
53
|
+
const submitted = await submitReaderComment.call({ pageId: page.id, name: "Public name", email: "private@example.test", body: "<script>plain text</script>" }, ANONYMOUS);
|
|
54
|
+
expect(await listReaderComments.call({ pageId: page.id }, ANONYMOUS)).toEqual([]);
|
|
55
|
+
const queue = await listReaderCommentsForOwner.call({}, OWNER);
|
|
56
|
+
expect(queue).toHaveLength(1);
|
|
57
|
+
expect(queue[0]).toMatchObject({ id: submitted.id, status: "pending" });
|
|
58
|
+
const messages = await db().select().from(notifications);
|
|
59
|
+
expect(messages).toHaveLength(1);
|
|
60
|
+
expect(messages[0]?.topic).toBe("cms.comment_pending");
|
|
61
|
+
await moderateReaderComment.call({ id: submitted.id, status: "approved" }, OWNER);
|
|
62
|
+
const visible = await listReaderComments.call({ pageId: page.id }, ANONYMOUS);
|
|
63
|
+
expect(visible).toHaveLength(1);
|
|
64
|
+
expect(Object.keys(visible[0]!)).toEqual(["id", "parentId", "authorName", "body", "createdAt"]);
|
|
65
|
+
const people = await db().select().from(contacts);
|
|
66
|
+
expect(people).toHaveLength(1);
|
|
67
|
+
expect(people[0]?.email).toBe("private@example.test");
|
|
68
|
+
await submitReaderComment.call({ pageId: page.id, parentId: submitted.id, name: "Reply", email: "reply@example.test", body: "A reply" }, ANONYMOUS);
|
|
69
|
+
const other = await post("another-post");
|
|
70
|
+
await expect(submitReaderComment.call({ pageId: other.id, parentId: submitted.id, name: "No", email: "reply@example.test", body: "Wrong parent" }, ANONYMOUS)).rejects.toMatchObject({ code: "validation" });
|
|
71
|
+
await moderateReaderComment.call({ id: submitted.id, status: "spam" }, OWNER);
|
|
72
|
+
expect(await listReaderComments.call({ pageId: page.id }, ANONYMOUS)).toEqual([]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("respects honeypots, unpublished posts, site and post switches", async () => {
|
|
76
|
+
const page = await post();
|
|
77
|
+
const input = { pageId: page.id, name: "Reader", email: "reader@example.test", body: "A comment" };
|
|
78
|
+
await submitReaderComment.call({ ...input, website: "spam" }, ANONYMOUS);
|
|
79
|
+
expect(await db().select().from(comments)).toEqual([]);
|
|
80
|
+
expect(await db().select().from(contacts)).toEqual([]);
|
|
81
|
+
await updateBlogSettings.call({ commentsEnabled: false }, OWNER);
|
|
82
|
+
await expect(submitReaderComment.call(input, ANONYMOUS)).rejects.toMatchObject({ code: "validation" });
|
|
83
|
+
await updateBlogSettings.call({ commentsEnabled: true }, OWNER);
|
|
84
|
+
await setPostMeta.call({ pageId: page.id, isPost: true, commentsEnabled: false }, OWNER);
|
|
85
|
+
await expect(submitReaderComment.call(input, ANONYMOUS)).rejects.toMatchObject({ code: "validation" });
|
|
86
|
+
await publishPage.call({ id: page.id, published: false }, OWNER);
|
|
87
|
+
expect(await listReaderComments.call({ pageId: page.id }, ANONYMOUS)).toEqual([]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("moves and undoes contact references and includes comments in private export and erasure", async () => {
|
|
91
|
+
const page = await post();
|
|
92
|
+
const submitted = await submitReaderComment.call({ pageId: page.id, name: "Reader", email: "reader@example.test", body: "Private export includes this" }, ANONYMOUS);
|
|
93
|
+
const [before] = await db().select().from(comments).where(eq(comments.id, submitted.id));
|
|
94
|
+
const survivor = await createContact.call({ name: "Survivor", email: "survivor@example.test" }, OWNER);
|
|
95
|
+
const merged = await mergeContacts.call({ survivingId: survivor.id, duplicateId: before!.contactId! }, OWNER);
|
|
96
|
+
expect((await db().select().from(comments))[0]?.contactId).toBe(survivor.id);
|
|
97
|
+
await undoContactMerge.call({ operationId: merged.mergeOperationId }, OWNER);
|
|
98
|
+
expect((await db().select().from(comments))[0]?.contactId).toBe(before!.contactId);
|
|
99
|
+
const source = contactPrivacySources().find(item => item.scope === "cms.readerComments")!;
|
|
100
|
+
const exported = await db().transaction(tx => source.exportData(tx, before!.contactId!));
|
|
101
|
+
expect(JSON.stringify(exported)).toContain("Private export includes this");
|
|
102
|
+
await db().transaction(tx => source.erase(tx, before!.contactId!, { requestId: crypto.randomUUID() }));
|
|
103
|
+
expect(await db().select().from(comments)).toEqual([]);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("withdraws comments, bylines and archives when the shared publication policy vetoes a post", async () => {
|
|
107
|
+
const page = await post("revoked-reader-post");
|
|
108
|
+
const category = await saveTerm.call({ taxonomy: "category", name: "Revoked category" }, OWNER);
|
|
109
|
+
await setPostMeta.call({ pageId: page.id, isPost: true, categoryIds: [category.id] }, OWNER);
|
|
110
|
+
const input = { pageId: page.id, name: "Reader", email: "revoked@example.test", body: "A held comment" };
|
|
111
|
+
const submitted = await submitReaderComment.call(input, ANONYMOUS);
|
|
112
|
+
await moderateReaderComment.call({ id: submitted.id, status: "approved" }, OWNER);
|
|
113
|
+
registerPublishVeto({ id: "test.revoked-reader-post", appliesTo: one => one.id === page.id, blocks: () => Promise.resolve(true) });
|
|
114
|
+
expect(await listReaderComments.call({ pageId: page.id }, ANONYMOUS)).toEqual([]);
|
|
115
|
+
expect(await postMetaAt.call({ slug: page.slug }, ANONYMOUS)).toBeNull();
|
|
116
|
+
expect(await resolveBlogArchive.call({ path: category.path }, ANONYMOUS)).toBeNull();
|
|
117
|
+
expect(await publicBlogCategories.call({}, ANONYMOUS)).toEqual([]);
|
|
118
|
+
await expect(submitReaderComment.call(input, ANONYMOUS)).rejects.toMatchObject({ code: "validation" });
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("keeps an original publication date when an owner republishes an edited post", async () => {
|
|
122
|
+
const page = await post("original-date-after-edit");
|
|
123
|
+
const original = "2025-03-14T18:00:00.000Z";
|
|
124
|
+
await publishPage.call({ id: page.id, published: true, publishedAt: original }, OWNER);
|
|
125
|
+
await updatePage.call({ id: page.id, title: "An edited post" }, OWNER);
|
|
126
|
+
const published = await publishPage.call({ id: page.id, published: true }, OWNER);
|
|
127
|
+
expect(published.publishedAt?.toISOString()).toBe(original);
|
|
128
|
+
const meta = await postMetaAt.call({ slug: page.slug }, ANONYMOUS);
|
|
129
|
+
expect(meta?.publishedAt?.toISOString()).toBe(original);
|
|
130
|
+
expect(meta!.modifiedAt!.getTime()).toBeGreaterThan(Date.parse(original));
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("paginates approved history and the moderation queue without dropping older comments", async () => {
|
|
134
|
+
const page = await post("paged-reader-history");
|
|
135
|
+
await db().insert(comments).values([1, 2, 3].map(index => ({ pageId: page.id, authorName: `Reader ${index}`, body: `Comment ${index}`, status: "approved" as const, createdAt: new Date(`2025-01-0${index}T12:00:00Z`) })));
|
|
136
|
+
const first = await listReaderComments.call({ pageId: page.id, limit: 2 }, ANONYMOUS);
|
|
137
|
+
const next = await listReaderComments.call({ pageId: page.id, limit: 2, page: 2 }, ANONYMOUS);
|
|
138
|
+
expect(first.map(comment => comment.body)).toEqual(["Comment 1", "Comment 2"]);
|
|
139
|
+
expect(next.map(comment => comment.body)).toEqual(["Comment 3"]);
|
|
140
|
+
expect((await listReaderCommentsForOwner.call({ limit: 2, page: 2 }, OWNER)).map(comment => comment.body)).toEqual(["Comment 1"]);
|
|
141
|
+
await expect(listReaderCommentsForOwner.call({}, ANONYMOUS)).rejects.toMatchObject({ code: "permission" });
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("cannot use a visible same-slug locale row to authorize a different vetoed post ID", async () => {
|
|
145
|
+
const rows = [];
|
|
146
|
+
for (const locale of ["en", "fr"]) {
|
|
147
|
+
const page = await createPage.call({ slug: "parallel-locale-source", locale, title: `Post ${locale}`, blocks: [{ id: `heading-${locale}`, type: "heading", props: { text: `Post ${locale}`, level: 1 } }] }, OWNER);
|
|
148
|
+
await setPostMeta.call({ pageId: page.id, isPost: true }, OWNER);
|
|
149
|
+
await publishPage.call({ id: page.id, published: true }, OWNER);
|
|
150
|
+
rows.push(page);
|
|
151
|
+
}
|
|
152
|
+
const canonical = await resolvePage.call({ slug: "parallel-locale-source" }, ANONYMOUS);
|
|
153
|
+
const hidden = rows.find(page => page.id !== canonical?.id)!;
|
|
154
|
+
const category = await saveTerm.call({ taxonomy: "category", name: "Hidden parallel category" }, OWNER);
|
|
155
|
+
await setPostMeta.call({ pageId: hidden.id, isPost: true, categoryIds: [category.id] }, OWNER);
|
|
156
|
+
await db().insert(comments).values({ pageId: hidden.id, authorName: "Hidden reader", body: "A vetoed comment", status: "approved" });
|
|
157
|
+
registerPublishVeto({ id: "test.parallel-locale-source", appliesTo: page => page.id === hidden.id, blocks: () => Promise.resolve(true) });
|
|
158
|
+
expect((await resolvePage.call({ slug: hidden.slug }, ANONYMOUS))?.id).toBe(canonical?.id);
|
|
159
|
+
expect(await listReaderComments.call({ pageId: hidden.id }, ANONYMOUS)).toEqual([]);
|
|
160
|
+
expect(await resolveBlogArchive.call({ path: category.path }, ANONYMOUS)).toBeNull();
|
|
161
|
+
expect(await publicBlogCategories.call({}, ANONYMOUS)).toEqual([]);
|
|
162
|
+
expect((await postMetaAt.call({ slug: hidden.slug }, ANONYMOUS))?.pageId).toBe(canonical?.id);
|
|
163
|
+
expect((await listBlogPosts.call({}, ANONYMOUS)).posts.filter(post => post.slug === hidden.slug)).toHaveLength(1);
|
|
164
|
+
await expect(submitReaderComment.call({ pageId: hidden.id, name: "Reader", email: "parallel@example.test", body: "Must stay private" }, ANONYMOUS)).rejects.toMatchObject({ code: "validation" });
|
|
165
|
+
});
|
|
166
|
+
});
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
cspAppliesToPath,
|
|
13
13
|
parseCspOrigins,
|
|
14
14
|
} from "@/core/http/csp";
|
|
15
|
-
import { proxy } from "../../proxy";
|
|
15
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
16
16
|
|
|
17
17
|
function directive(policy: string, name: string): string {
|
|
18
18
|
return policy.split("; ").find((part) => part.startsWith(`${name} `)) ?? "";
|
|
@@ -223,6 +223,10 @@ const CALLER_AUTHORIZED_PHASES = [
|
|
|
223
223
|
// a provider (MASTER.md §11).
|
|
224
224
|
"assistant.applyAnswer",
|
|
225
225
|
"assistant.prepareAnswer",
|
|
226
|
+
// Validated private chat bearer and an already visitor-bound PM session;
|
|
227
|
+
// these phases are only reachable through assistant.previewCall.
|
|
228
|
+
"assistant.previewAccess",
|
|
229
|
+
"assistant.saveCallCaption",
|
|
226
230
|
"assistant.settingsSnapshot",
|
|
227
231
|
// C3.22: the halves of imports.commit around WordPress media downloads.
|
|
228
232
|
"imports.commitApply",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { NextRequest } from "next/server";
|
|
5
|
+
import { legacyRedirect } from "@/core/seo/legacy-proxy";
|
|
6
|
+
import { proxy } from "../../proxy";
|
|
7
|
+
import { resetEnvForTests } from "@/core/env";
|
|
8
|
+
const originalOrigin = process.env.APP_URL;
|
|
9
|
+
afterEach(() => { vi.unstubAllGlobals(); if (originalOrigin === undefined) delete process.env.APP_URL; else process.env.APP_URL = originalOrigin; delete process.env.FREEHOLDER_PREVIEW_KEY; resetEnvForTests(); });
|
|
10
|
+
|
|
11
|
+
describe("legacy redirect HTTP projection", () => {
|
|
12
|
+
it("resolves query IDs at the trusted origin without forwarding cookies or caller headers", async () => {
|
|
13
|
+
process.env.APP_URL = "https://destination.example.test";
|
|
14
|
+
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ toPath: "2025/03/original", status: "301" }));
|
|
15
|
+
vi.stubGlobal("fetch", fetcher);
|
|
16
|
+
const response = await legacyRedirect(new NextRequest("https://untrusted.example/?p=20", { headers: { cookie: "session=private", authorization: "Bearer private" } }));
|
|
17
|
+
expect(response?.status).toBe(301);
|
|
18
|
+
expect(response?.headers.get("location")).toBe("https://destination.example.test/2025/03/original");
|
|
19
|
+
const [input, options] = fetcher.mock.calls[0]!;
|
|
20
|
+
const url = input as URL;
|
|
21
|
+
expect(url.origin).toBe("https://destination.example.test");
|
|
22
|
+
expect(url.searchParams.get("path")).toBe("?p=20");
|
|
23
|
+
expect(options!.headers).toEqual({ accept: "application/json" });
|
|
24
|
+
expect(options!.redirect).toBe("error");
|
|
25
|
+
});
|
|
26
|
+
it("collapses slash and old-path moves into one redirect, preserving the locale and pagination target", async () => {
|
|
27
|
+
process.env.APP_URL = "https://destination.example.test";
|
|
28
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ toPath: "blog/category/new?page=2", status: "301" })));
|
|
29
|
+
const response = await legacyRedirect(new NextRequest("https://destination.example.test/fr/category/old/page/2/"));
|
|
30
|
+
expect(response?.status).toBe(301);
|
|
31
|
+
expect(response?.headers.get("location")).toBe("https://destination.example.test/fr/blog/category/new?page=2");
|
|
32
|
+
});
|
|
33
|
+
it("does not intercept private routes, writes or media, and keeps a page available when the resolver fails", async () => {
|
|
34
|
+
process.env.APP_URL = "https://destination.example.test";
|
|
35
|
+
const fetcher = vi.fn().mockRejectedValue(new Error("offline")); vi.stubGlobal("fetch", fetcher);
|
|
36
|
+
for (const path of ["/admin", "/fr/admin", "/api/v1/cms.resolvePage", "/media/photo.jpg", "/feeds/blog.xml"]) expect(await legacyRedirect(new NextRequest(`https://destination.example.test${path}`))).toBeNull();
|
|
37
|
+
expect(await legacyRedirect(new NextRequest("https://destination.example.test/contact", { method: "POST" }))).toBeNull();
|
|
38
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
39
|
+
expect(await legacyRedirect(new NextRequest("https://destination.example.test/about"))).toBeNull();
|
|
40
|
+
expect((await legacyRedirect(new NextRequest("https://destination.example.test/about/?utm_source=old")))?.headers.get("location")).toBe("https://destination.example.test/about?utm_source=old");
|
|
41
|
+
});
|
|
42
|
+
it("checks private-preview access before a redirect lookup", async () => {
|
|
43
|
+
process.env.FREEHOLDER_PREVIEW_KEY = "p".repeat(40);
|
|
44
|
+
resetEnvForTests();
|
|
45
|
+
const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher);
|
|
46
|
+
const response = await proxy(new NextRequest("https://preview.example.test/old/"));
|
|
47
|
+
expect(response.status).toBe(401);
|
|
48
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
49
|
+
});
|
|
50
|
+
it("copies CSP onto a mutable response rather than mutating native redirect headers", async () => {
|
|
51
|
+
process.env.APP_URL = "https://destination.example.test";
|
|
52
|
+
resetEnvForTests();
|
|
53
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ toPath: "new-address", status: "301" })));
|
|
54
|
+
const response = await proxy(new NextRequest("https://destination.example.test/old-address/"));
|
|
55
|
+
expect(response.status).toBe(301);
|
|
56
|
+
expect(response.headers.get("location")).toBe("https://destination.example.test/new-address");
|
|
57
|
+
expect(response.headers.get("content-security-policy")).toContain("default-src");
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// keep in step. Almost every assertion here is a consequence of that.
|
|
9
9
|
import { afterAll, beforeEach, describe, expect, it } from "vitest";
|
|
10
10
|
import { NextRequest } from "next/server";
|
|
11
|
-
import { proxy } from "../../proxy";
|
|
11
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
12
12
|
import { LOCALE_HEADER } from "@/core/http/headers";
|
|
13
13
|
import { localePath } from "../../app/(public)/[[...slug]]/alternates";
|
|
14
14
|
import {
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
playgroundSharedCacheable,
|
|
14
14
|
} from "@/core/demo/playground-cache";
|
|
15
15
|
import { ANALYTICS_BOOTSTRAP_COOKIE } from "@/modules/analytics/visitor";
|
|
16
|
-
import { proxy } from "../../proxy";
|
|
16
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
17
17
|
|
|
18
18
|
const APP = join(__dirname, "..", "..", "app");
|
|
19
19
|
|
|
@@ -88,10 +88,10 @@ it("treats only the content modules as editable admin screens", () => {
|
|
|
88
88
|
|
|
89
89
|
describe("playground public-site policy (2026-10-22)", () => {
|
|
90
90
|
it("lets the public site's own actions through and keeps credential and provider flows out", () => {
|
|
91
|
-
for (const name of ["forms.submit", "newsletters.subscribe", "events.register", "catalog.addCartItem", "catalog.shopperCheckout", "cms.submitSiteChat", "share.shareVia", "popups.capture", "reviews.submit"]) {
|
|
91
|
+
for (const name of ["forms.submit", "newsletters.subscribe", "events.register", "catalog.addCartItem", "catalog.shopperCheckout", "cms.submitSiteChat", "cms.submitReaderComment", "share.shareVia", "popups.capture", "reviews.submit"]) {
|
|
92
92
|
expect(playgroundAllows(name, "mutation"), name).toBe(true);
|
|
93
93
|
}
|
|
94
|
-
for (const name of ["auth.requestCustomerMagicLink", "portal.requestSignIn", "invoicing.beginCustomerCheckout", "invoicing.claimCustomerCheckout", "assistant.answer", "media.signUploadClaim"]) {
|
|
94
|
+
for (const name of ["auth.requestCustomerMagicLink", "portal.requestSignIn", "invoicing.beginCustomerCheckout", "invoicing.claimCustomerCheckout", "assistant.answer", "assistant.previewCall", "assistant.saveCallCaption", "media.signUploadClaim"]) {
|
|
95
95
|
expect(playgroundAllows(name, "mutation"), name).toBe(false);
|
|
96
96
|
}
|
|
97
97
|
});
|
|
@@ -113,7 +113,7 @@ describe("playground public-site policy (2026-10-22)", () => {
|
|
|
113
113
|
}
|
|
114
114
|
// Public verbs that add a row of their own carry a cap; the community
|
|
115
115
|
// join (a member row per email) was missed once.
|
|
116
|
-
for (const name of ["forms.submit", "events.register", "community.joinBySlug", "catalog.getOrCreateCart", "reviews.submit"]) {
|
|
116
|
+
for (const name of ["forms.submit", "events.register", "community.joinBySlug", "catalog.getOrCreateCart", "reviews.submit", "cms.submitReaderComment"]) {
|
|
117
117
|
expect(PLAYGROUND_ROW_CAPS[name], name).toBeDefined();
|
|
118
118
|
}
|
|
119
119
|
// Every capped public surface is one the policy actually allows.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// @vitest-environment jsdom
|
|
4
|
+
import { act, createElement } from "react";
|
|
5
|
+
import { createRoot, type Root } from "react-dom/client";
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
7
|
+
import { PreviewAssistantCall, type PreviewAssistantLabels } from "@/modules/cms/blocks/PreviewAssistantCall";
|
|
8
|
+
|
|
9
|
+
const labels: PreviewAssistantLabels = {
|
|
10
|
+
label: "AI assistant", captions: "Captions stay in this chat", video: "Start video", voice: "Start voice", leave: "Leave queue", end: "End call",
|
|
11
|
+
waiting: "Waiting", unavailable: "Use text", connecting: "Connecting", captionFailed: "Captions not saved", ended: "Ended", lost: "Connection lost", microphone: "Allow microphone",
|
|
12
|
+
voiceFallback: "Video is unavailable. Continuing by voice.",
|
|
13
|
+
};
|
|
14
|
+
const json = (body: unknown) => new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });
|
|
15
|
+
const config = (modes = ["video", "voice", "text"]) => json({ enabled: true, modes, label: "AI assistant", disclosure: "AI, family-friendly, no endorsement" });
|
|
16
|
+
const tick = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); };
|
|
17
|
+
function deferred<T>() {
|
|
18
|
+
let resolve!: (value: T) => void, reject!: (error: Error) => void;
|
|
19
|
+
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
|
|
20
|
+
return { promise, resolve, reject };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe("preview assistant browser lifecycle", () => {
|
|
24
|
+
let root: Root, container: HTMLDivElement;
|
|
25
|
+
const stops: Array<ReturnType<typeof vi.fn>> = [];
|
|
26
|
+
const requests: Array<Record<string, unknown>> = [];
|
|
27
|
+
let handler: (body: Record<string, unknown>) => Promise<Response>;
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
|
31
|
+
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
|
32
|
+
stops.length = 0; requests.length = 0;
|
|
33
|
+
vi.stubGlobal("AudioContext", class {
|
|
34
|
+
resume() { return Promise.resolve(); }
|
|
35
|
+
close() { return Promise.resolve(); }
|
|
36
|
+
});
|
|
37
|
+
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia: () => {
|
|
38
|
+
const stop = vi.fn(); stops.push(stop);
|
|
39
|
+
return Promise.resolve({ getTracks: () => [{ stop }] });
|
|
40
|
+
} } });
|
|
41
|
+
vi.stubGlobal("fetch", async (_url: unknown, init?: RequestInit) => {
|
|
42
|
+
const body = typeof init?.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : {};
|
|
43
|
+
requests.push(body); return handler(body);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });
|
|
47
|
+
async function mount() { await act(async () => root.render(createElement(PreviewAssistantCall, { ended: false, labels }))); await tick(); }
|
|
48
|
+
async function click(text: string) {
|
|
49
|
+
const button = [...container.querySelectorAll("button")].find(item => item.textContent === text);
|
|
50
|
+
expect(button, text).toBeDefined();
|
|
51
|
+
await act(async () => button!.click()); await tick();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
it("keeps disclosure and text fallback without requesting microphone or age confirmation", async () => {
|
|
55
|
+
handler = async () => config(["text"]); await mount();
|
|
56
|
+
expect(container.textContent).toContain("no endorsement");
|
|
57
|
+
expect(container.querySelectorAll("button")).toHaveLength(0);
|
|
58
|
+
expect(container.querySelectorAll("input")).toHaveLength(0);
|
|
59
|
+
expect(stops).toHaveLength(0);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("a canceled older start cannot stop the next call when its response later fails", async () => {
|
|
63
|
+
const first = deferred<Response>(), second = deferred<Response>(); let starts = 0;
|
|
64
|
+
handler = body => body.action === "config" ? Promise.resolve(config())
|
|
65
|
+
: body.action === "start" ? (++starts === 1 ? first.promise : second.promise)
|
|
66
|
+
: Promise.resolve(json({ status: "ended" }));
|
|
67
|
+
await mount(); await click(labels.voice); expect(stops).toHaveLength(1);
|
|
68
|
+
await click(labels.end); expect(stops[0]).toHaveBeenCalledTimes(1);
|
|
69
|
+
await click(labels.voice); expect(stops).toHaveLength(2);
|
|
70
|
+
await act(async () => first.reject(new Error("old response lost"))); await tick();
|
|
71
|
+
expect(stops[1]).not.toHaveBeenCalled();
|
|
72
|
+
expect(container.textContent).toContain(labels.end);
|
|
73
|
+
expect(container.textContent).toContain(labels.connecting);
|
|
74
|
+
await act(async () => second.resolve(json({ status: "text" }))); await tick();
|
|
75
|
+
expect(stops[1]).toHaveBeenCalledTimes(1);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("leaving a queue stops local media and ends that exact bound ticket", async () => {
|
|
79
|
+
handler = async body => body.action === "config" ? config()
|
|
80
|
+
: body.action === "start" ? json({ status: "queued", session_id: "11111111-1111-4111-8111-111111111111" })
|
|
81
|
+
: json({ status: "expired" });
|
|
82
|
+
await mount(); await click(labels.video); expect(container.textContent).toContain(labels.waiting);
|
|
83
|
+
await click(labels.leave);
|
|
84
|
+
expect(stops[0]).toHaveBeenCalledTimes(1);
|
|
85
|
+
expect(requests.at(-1)).toEqual({ action: "end", sessionId: "11111111-1111-4111-8111-111111111111" });
|
|
86
|
+
expect(container.textContent).toContain(labels.video);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -29,7 +29,7 @@ process.env.STRIPE_WEBHOOK_SECRET = PAYMENTS_SECRET;
|
|
|
29
29
|
process.env.STRIPE_CONNECT_WEBHOOK_SECRET = CONNECT_SECRET;
|
|
30
30
|
const { resetEnvForTests } = await import("@/core/env");
|
|
31
31
|
resetEnvForTests();
|
|
32
|
-
const { proxy } = await import("../../proxy");
|
|
32
|
+
const { requestContextProxy: proxy } = await import("../../proxy");
|
|
33
33
|
const { previewGated } = await import("@/core/preview/private-preview");
|
|
34
34
|
const { POST: payments } = await import("../../app/api/payments/webhooks/stripe/route");
|
|
35
35
|
const { POST: payouts } = await import("../../app/api/payouts/[provider]/webhook/route");
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// routes with the key set and unset.
|
|
9
9
|
import { afterEach, describe, expect, it } from "vitest";
|
|
10
10
|
import { NextRequest } from "next/server";
|
|
11
|
-
import { proxy } from "../../proxy";
|
|
11
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
12
12
|
import { resetEnvForTests } from "@/core/env";
|
|
13
13
|
import {
|
|
14
14
|
PREVIEW_COOKIE,
|
|
@@ -10,7 +10,7 @@ import { readdirSync } from "node:fs";
|
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import { NextRequest } from "next/server";
|
|
12
12
|
import { describe, expect, it } from "vitest";
|
|
13
|
-
import { proxy } from "../../proxy";
|
|
13
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
14
14
|
|
|
15
15
|
const ROOT = join(import.meta.dirname, "..", "..");
|
|
16
16
|
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Copyright (C) 2026 Tony Aly
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
3
|
// JSON Schema → TypeScript for the generated SDK (C3.03).
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { toContractJsonSchema } from "@/core/contract/json-schema";
|
|
4
6
|
import { describe, expect, it } from "vitest";
|
|
5
7
|
import { isPageableSchema, jsonSchemaToTs } from "@/core/contract/sdk";
|
|
6
8
|
|
|
@@ -104,3 +106,21 @@ describe("jsonSchemaToTs (C3.03)", () => {
|
|
|
104
106
|
).toBe(false);
|
|
105
107
|
});
|
|
106
108
|
});
|
|
109
|
+
|
|
110
|
+
// A real managed assistant action union first exposed MCP's object-only
|
|
111
|
+
// fallback. Keep one shared projection, not a hand-authored MCP action list.
|
|
112
|
+
it("retains complete action-object unions for MCP, HTTP and SDK without labeling mixed primitives objects", () => {
|
|
113
|
+
const input = z.discriminatedUnion("action", [
|
|
114
|
+
z.object({ action: z.literal("config"), token: z.string() }).strict(),
|
|
115
|
+
z.object({ action: z.literal("start"), token: z.string(), want: z.enum(["voice", "video"]) }).strict(),
|
|
116
|
+
]);
|
|
117
|
+
const schema = toContractJsonSchema(input, "input") as { type: string; oneOf: Array<{ required: string[]; properties: Record<string, unknown> }> };
|
|
118
|
+
expect(schema.type).toBe("object");
|
|
119
|
+
expect(schema.oneOf).toHaveLength(2);
|
|
120
|
+
expect(schema.oneOf[0]!.required).toEqual(["action", "token"]);
|
|
121
|
+
expect(schema.oneOf[1]!.required).toEqual(["action", "token", "want"]);
|
|
122
|
+
expect(jsonSchemaToTs(schema)).toContain('action: "config"');
|
|
123
|
+
expect(jsonSchemaToTs(schema)).toContain('action: "start"');
|
|
124
|
+
const mixed = toContractJsonSchema(z.union([z.string(), z.object({ id: z.string() })]), "input") as { type?: string };
|
|
125
|
+
expect(mixed.type).toBeUndefined();
|
|
126
|
+
});
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// not break every link to it.
|
|
10
10
|
import { afterAll, beforeEach, describe, expect, it } from "vitest";
|
|
11
11
|
import { NextRequest } from "next/server";
|
|
12
|
-
import { proxy } from "../../proxy";
|
|
12
|
+
import { requestContextProxy as proxy } from "../../proxy";
|
|
13
13
|
import {
|
|
14
14
|
breadcrumbJsonLd,
|
|
15
15
|
humanizeSegment,
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// @vitest-environment jsdom
|
|
4
|
+
import { act, createElement } from "react";
|
|
5
|
+
import { createRoot } from "react-dom/client";
|
|
6
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
7
|
+
import { requireCsrf } from "@/core/http/csrf";
|
|
8
|
+
import { SiteChatClient } from "@/modules/cms/blocks/SiteChatClient";
|
|
9
|
+
|
|
10
|
+
vi.mock("../../app/(public)/inbound-actions", () => ({ postSiteChatAction: vi.fn() }));
|
|
11
|
+
|
|
12
|
+
afterEach(() => { vi.unstubAllGlobals(); document.cookie = "freeholder_csrf=; Max-Age=0; Path=/"; });
|
|
13
|
+
|
|
14
|
+
it("signed-in chat sends double-submit CSRF on message, assistant and End; other block placements offer no media admission", async () => {
|
|
15
|
+
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
|
16
|
+
document.cookie = "freeholder_csrf=fixture-token; Path=/";
|
|
17
|
+
const writes: string[] = [];
|
|
18
|
+
const transcript = { state: "open", escalated: false, messages: [], expiresAt: "2026-12-01T00:00:00Z" };
|
|
19
|
+
vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
|
|
20
|
+
const method = init?.method ?? "GET";
|
|
21
|
+
expect(url).not.toBe("/api/chat/assistant/call");
|
|
22
|
+
if (method !== "GET") {
|
|
23
|
+
const headers = new Headers(init?.headers);
|
|
24
|
+
// The login cookie remains httpOnly. Model the HTTP guard's automatic credential attachment.
|
|
25
|
+
headers.set("cookie", `freeholder_session=fixture-session; ${document.cookie}`);
|
|
26
|
+
requireCsrf(new Request(`https://business.test${url}`, { method, headers }));
|
|
27
|
+
writes.push(`${method} ${url}`);
|
|
28
|
+
}
|
|
29
|
+
return new Response(JSON.stringify(url.endsWith("/assistant") ? { status: "answered" } : transcript), { headers: { "content-type": "application/json" } });
|
|
30
|
+
});
|
|
31
|
+
const labels = {
|
|
32
|
+
call: { label:"AI", captions:"Captions", video:"Video", voice:"Voice", leave:"Leave", end:"End call", waiting:"Waiting", unavailable:"Text", connecting:"Connecting", captionFailed:"Failed", ended:"Ended", lost:"Lost", microphone:"Microphone",voiceFallback:"Voice fallback" },
|
|
33
|
+
loading:"Loading",ended:"Ended",escalated:"Escalated",message:"Message",send:"Send",sending:"Sending",end:"End chat",fromYou:"You",fromBusiness:"Business",fromAssistant:"Assistant",failed:"Failed",
|
|
34
|
+
};
|
|
35
|
+
const container=document.createElement("div");document.body.append(container);const root=createRoot(container);
|
|
36
|
+
try {
|
|
37
|
+
await act(async () => {root.render(createElement(SiteChatClient,{locale:"fr",labels,path:"/fr/services"}));});
|
|
38
|
+
await act(async()=>{await new Promise(resolve=>setTimeout(resolve,0));});
|
|
39
|
+
expect(container.textContent).not.toContain("End call");
|
|
40
|
+
container.querySelector("textarea")!.value="A follow-up";
|
|
41
|
+
// React receives the browser's actual FormData implementation for a submitted HTML form.
|
|
42
|
+
vi.stubGlobal("FormData",window.FormData);
|
|
43
|
+
await act(async()=>{container.querySelector("form")!.dispatchEvent(new Event("submit",{bubbles:true,cancelable:true}));});
|
|
44
|
+
await act(async()=>{await new Promise(resolve=>setTimeout(resolve,0));});
|
|
45
|
+
const end=[...container.querySelectorAll("button")].find(button=>button.textContent==="End chat")!;
|
|
46
|
+
await act(async()=>{end.click();});
|
|
47
|
+
expect(writes).toEqual(["POST /api/chat","POST /api/chat/assistant","DELETE /api/chat"]);
|
|
48
|
+
expect(container.textContent).toContain("Ended");
|
|
49
|
+
} finally {await act(async()=>root.unmount());container.remove();}
|
|
50
|
+
});
|