create-freeholder 0.2.0-beta.4 → 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.
Files changed (158) hide show
  1. package/dist/template/.changeset/blog-playground-content.md +4 -0
  2. package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
  3. package/dist/template/.changeset/managed-preview-assistant.md +4 -0
  4. package/dist/template/.changeset/native-linux-install.md +6 -0
  5. package/dist/template/.changeset/public-beta-5.md +4 -0
  6. package/dist/template/.changeset/public-beta-6.md +4 -0
  7. package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
  8. package/dist/template/.github/workflows/release-tarballs.yml +117 -0
  9. package/dist/template/AGENTS.md +15 -2
  10. package/dist/template/Dockerfile +3 -0
  11. package/dist/template/MASTER.md +114 -11
  12. package/dist/template/README.md +1 -1
  13. package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
  14. package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
  15. package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
  16. package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
  17. package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
  18. package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
  19. package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
  20. package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
  21. package/dist/template/app/(admin)/assistant-actions.ts +13 -6
  22. package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
  23. package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
  24. package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
  25. package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
  26. package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
  27. package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
  28. package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
  29. package/dist/template/db/migrations/meta/_journal.json +14 -0
  30. package/dist/template/deploy/README.md +26 -9
  31. package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
  32. package/dist/template/deploy/docker-selfhost/.env.example +11 -1
  33. package/dist/template/deploy/docker-selfhost/README.md +79 -50
  34. package/dist/template/deploy/docker-selfhost/infra/backup.sh +81 -0
  35. package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +37 -1
  36. package/dist/template/deploy/docker-selfhost/infra/compose.yml +37 -1
  37. package/dist/template/deploy/docker-selfhost/migrate.md +8 -5
  38. package/dist/template/deploy/docker-selfhost/recipe.yaml +9 -10
  39. package/dist/template/deploy/docker-selfhost/selfhost.sh +206 -0
  40. package/dist/template/deploy/docker-selfhost/verify.md +11 -4
  41. package/dist/template/deploy/f-criteria-matrix.md +89 -0
  42. package/dist/template/deploy/linux/.env.example +28 -0
  43. package/dist/template/deploy/linux/README.md +181 -0
  44. package/dist/template/deploy/linux/freeholder +655 -0
  45. package/dist/template/deploy/linux/install.sh +173 -0
  46. package/dist/template/deploy/linux/migrate.md +17 -0
  47. package/dist/template/deploy/linux/recipe.yaml +50 -0
  48. package/dist/template/deploy/linux/share/Caddyfile.template +19 -0
  49. package/dist/template/deploy/linux/share/systemd/freeholder-backup.service +13 -0
  50. package/dist/template/deploy/linux/share/systemd/freeholder-backup.timer +12 -0
  51. package/dist/template/deploy/linux/share/systemd/freeholder.service +41 -0
  52. package/dist/template/deploy/linux/verify.md +22 -0
  53. package/dist/template/deploy/managed-preview-assistant.md +99 -0
  54. package/dist/template/eslint.config.mjs +3 -1
  55. package/dist/template/gitignore.template +1 -0
  56. package/dist/template/locales/ar.json +85 -6
  57. package/dist/template/locales/en.json +83 -4
  58. package/dist/template/locales/es.json +83 -4
  59. package/dist/template/locales/fr.json +85 -6
  60. package/dist/template/next.config.ts +2 -0
  61. package/dist/template/package.json +3 -2
  62. package/dist/template/packages/cli/package.json +1 -1
  63. package/dist/template/packages/create-freeholder/package.json +1 -1
  64. package/dist/template/packages/freeholder-app/package.json +1 -1
  65. package/dist/template/packages/mobile-app/package.json +1 -1
  66. package/dist/template/packages/plugin-kit/package.json +1 -1
  67. package/dist/template/packages/sdk/package.json +1 -1
  68. package/dist/template/packages/sdk/src/generated.ts +177 -9
  69. package/dist/template/packages/sdk/src/version.ts +1 -1
  70. package/dist/template/packages/templates/package.json +1 -1
  71. package/dist/template/proxy.ts +18 -1
  72. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
  73. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
  74. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
  75. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
  76. package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
  77. package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
  78. package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
  79. package/dist/template/scripts/build-release.d.mts +4 -0
  80. package/dist/template/scripts/build-release.mjs +171 -0
  81. package/dist/template/scripts/launch-prepare.mjs +6 -3
  82. package/dist/template/scripts/license-headers.mjs +3 -0
  83. package/dist/template/scripts/recipe-matrix.sh +22 -7
  84. package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
  85. package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
  86. package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
  87. package/dist/template/src/adapters/ai/types.ts +5 -0
  88. package/dist/template/src/adapters/paradise/assistant.ts +37 -0
  89. package/dist/template/src/adapters/paradise/http.ts +4 -3
  90. package/dist/template/src/adapters/storage/local-mode.ts +54 -0
  91. package/dist/template/src/adapters/storage/local.ts +53 -26
  92. package/dist/template/src/core/contract/json-schema.ts +8 -0
  93. package/dist/template/src/core/demo/playground-inserts.ts +29 -0
  94. package/dist/template/src/core/demo/playground-policy.ts +9 -0
  95. package/dist/template/src/core/doctor/index.ts +19 -10
  96. package/dist/template/src/core/env.ts +8 -1
  97. package/dist/template/src/core/http/csp.ts +10 -2
  98. package/dist/template/src/core/http/csrf-client.ts +10 -0
  99. package/dist/template/src/core/import/service.ts +217 -12
  100. package/dist/template/src/core/import/wordpress.ts +80 -15
  101. package/dist/template/src/core/notifications/service.ts +1 -0
  102. package/dist/template/src/core/retention/registry.ts +2 -0
  103. package/dist/template/src/core/search/registry.ts +2 -0
  104. package/dist/template/src/core/seo/feeds.ts +2 -0
  105. package/dist/template/src/core/seo/jsonld.ts +46 -2
  106. package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
  107. package/dist/template/src/core/seo/meta.ts +10 -7
  108. package/dist/template/src/core/seo/service.ts +14 -1
  109. package/dist/template/src/core/update/preflight.ts +3 -2
  110. package/dist/template/src/core/update/release-declaration.json +1 -1
  111. package/dist/template/src/core/update/service.ts +7 -17
  112. package/dist/template/src/modules/assistant/contract.ts +1 -1
  113. package/dist/template/src/modules/assistant/limits.ts +3 -0
  114. package/dist/template/src/modules/assistant/preview.ts +124 -0
  115. package/dist/template/src/modules/assistant/provider.ts +7 -0
  116. package/dist/template/src/modules/assistant/service.ts +21 -5
  117. package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
  118. package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
  119. package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
  120. package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
  121. package/dist/template/src/modules/cms/blog-comments.ts +111 -0
  122. package/dist/template/src/modules/cms/blog-schema.ts +146 -0
  123. package/dist/template/src/modules/cms/blog-service.ts +999 -0
  124. package/dist/template/src/modules/cms/blog.tsx +245 -25
  125. package/dist/template/src/modules/cms/manifest.ts +7 -1
  126. package/dist/template/src/modules/cms/read.ts +18 -0
  127. package/dist/template/src/modules/cms/service.ts +22 -4
  128. package/dist/template/src/modules/cms/tables.ts +2 -0
  129. package/dist/template/src/modules/seed/launch.ts +31 -3
  130. package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
  131. package/dist/template/tests/core/agent-launch.test.ts +7 -2
  132. package/dist/template/tests/core/analytics-consent.test.ts +1 -1
  133. package/dist/template/tests/core/blog-playground.test.ts +106 -0
  134. package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
  135. package/dist/template/tests/core/client-readiness-security.test.ts +3 -1
  136. package/dist/template/tests/core/csp.test.ts +1 -1
  137. package/dist/template/tests/core/deploy-recipe.test.ts +54 -4
  138. package/dist/template/tests/core/internal-services.test.ts +4 -0
  139. package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
  140. package/dist/template/tests/core/linux-install.test.ts +169 -0
  141. package/dist/template/tests/core/local-storage-mode.test.ts +29 -0
  142. package/dist/template/tests/core/locale-routing.test.ts +1 -1
  143. package/dist/template/tests/core/playground-cache.test.ts +1 -1
  144. package/dist/template/tests/core/playground.test.ts +3 -3
  145. package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
  146. package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
  147. package/dist/template/tests/core/private-preview.test.ts +1 -1
  148. package/dist/template/tests/core/proxy-locale.test.ts +1 -1
  149. package/dist/template/tests/core/sdk-schema.test.ts +20 -0
  150. package/dist/template/tests/core/seo.test.ts +1 -1
  151. package/dist/template/tests/core/site-chat-client.test.ts +50 -0
  152. package/dist/template/tests/core/storage.test.ts +38 -2
  153. package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
  154. package/dist/template/tests/core/wordpress-import.test.ts +25 -12
  155. package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
  156. package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
  157. package/dist/template-manifest.json +490 -175
  158. 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
+ });
@@ -127,7 +127,9 @@ it('concurrent loyalty redemptions cannot spend the same points twice', async ()
127
127
 
128
128
  it('self-host compose honors the image pin used by rollback', () => {
129
129
  const compose = parse(readFileSync('deploy/docker-selfhost/infra/compose.yml', 'utf8')) as { services: { app: { image: string } } };
130
- expect(compose.services.app.image).toBe('${FREEHOLDER_IMAGE:-ghcr.io/campdenman/freeholder:edge}');
130
+ // C3.44: the default is the checkout's release, never `edge`.
131
+ const { version } = JSON.parse(readFileSync('package.json', 'utf8')) as { version: string };
132
+ expect(compose.services.app.image).toBe(`\${FREEHOLDER_IMAGE:-ghcr.io/campdenman/freeholder:${version}}`);
131
133
  });
132
134
 
133
135
  it('cannot claim a fingerprint is a recoverable snapshot', async () => {
@@ -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} `)) ?? "";
@@ -66,12 +66,16 @@ describe("the compose stack does not contradict the storage mandate", () => {
66
66
  compose = undefined;
67
67
  }
68
68
 
69
- it.runIf(compose !== undefined)(`${recipe}: no media volume`, () => {
70
- // §18: media lives in object storage, never on instance disk. A bind
71
- // mount for uploads would quietly reintroduce exactly what the mandate
72
- // forbids, and it would look reasonable in review.
69
+ it.runIf(compose !== undefined)(`${recipe}: media is never inside the replaceable app`, () => {
70
+ // §18: media must not live where a rebuild throws it away. A mount
71
+ // under /app would mix uploads into the release; the only supported
72
+ // local-disk location is the docker-selfhost volume at
73
+ // /var/lib/freeholder/media (C3.44), declared with LOCAL_STORAGE_ROOT.
73
74
  expect(compose!).not.toMatch(/media.*:\s*\/app\/(public\/)?media/i);
74
75
  expect(compose!).not.toMatch(/uploads:/i);
76
+ if (recipe !== "docker-selfhost") {
77
+ expect(compose!).not.toMatch(/LOCAL_STORAGE_ROOT|\/var\/lib\/freeholder\/media/);
78
+ }
75
79
  });
76
80
 
77
81
  it.runIf(compose !== undefined)(
@@ -210,6 +214,52 @@ describe("a trusted client address only where a proxy overwrites it (C11.10)", (
210
214
  });
211
215
  });
212
216
 
217
+ describe("docker-selfhost keeps media on a volume that is backed up (C3.44)", () => {
218
+ type Service = { image?: string; volumes?: string[]; environment?: Record<string, string>; command?: string[] };
219
+ for (const file of ["compose.yml", "compose.https.yml"]) {
220
+ it(`${file}: app media volume, LOCAL_STORAGE_ROOT and a backup service that reads it`, () => {
221
+ const compose = parse(readFileSync(join(DEPLOY, "docker-selfhost/infra", file), "utf8")) as { services: Record<string, Service>; volumes: Record<string, unknown> };
222
+ const { app, backup } = compose.services;
223
+ expect(app!.volumes).toContain("media:/var/lib/freeholder/media");
224
+ expect(app!.environment!.LOCAL_STORAGE_ROOT).toBe("/var/lib/freeholder/media");
225
+ // FREEHOLDER_STORAGE comes from .env: an `environment:` value would
226
+ // override the owner's choice of S3.
227
+ expect(app!.environment!.FREEHOLDER_STORAGE).toBeUndefined();
228
+ expect(backup!.image).toBe("postgres:16-alpine");
229
+ expect(backup!.volumes).toEqual(expect.arrayContaining(["./backup.sh:/usr/local/bin/freeholder-backup:ro", "media:/srv/media", "backups:/backups"]));
230
+ expect(backup!.command).toEqual(["sh", "/usr/local/bin/freeholder-backup", "schedule"]);
231
+ expect(Object.keys(compose.volumes)).toEqual(expect.arrayContaining(["pgdata", "media", "backups"]));
232
+ });
233
+ }
234
+
235
+ it("the image creates the mount point owned by the app user, so a new volume is writable", () => {
236
+ const dockerfile = readFileSync("Dockerfile", "utf8");
237
+ const runtime = dockerfile.slice(dockerfile.lastIndexOf("AS runtime"));
238
+ expect(runtime).toMatch(/mkdir -p \/var\/lib\/freeholder\/media && chown -R freeholder:freeholder \/var\/lib\/freeholder/);
239
+ expect(runtime.indexOf("/var/lib/freeholder/media")).toBeLessThan(runtime.indexOf("USER freeholder"));
240
+ });
241
+
242
+ it("the backup is a custom-format dump plus media with checksums, restored into a scratch database", () => {
243
+ const script = readFileSync(join(DEPLOY, "docker-selfhost/infra/backup.sh"), "utf8");
244
+ expect(script).toContain("pg_dump --format=custom --no-owner --no-privileges");
245
+ expect(script).toContain("media.tar.gz");
246
+ expect(script).toContain("sha256sum ./* > SHA256SUMS");
247
+ expect(script).toMatch(/pg_restore [^\n]*-d freeholder_restore/);
248
+ expect(script).not.toMatch(/^\s*[^#\r\n]*--clean/m);
249
+ });
250
+
251
+ it("prepare needs only openssl, and pins the release image rather than edge", () => {
252
+ const selfhost = readFileSync(join(DEPLOY, "docker-selfhost/selfhost.sh"), "utf8");
253
+ expect(selfhost).toContain("openssl rand -hex 32");
254
+ const commands = selfhost.split("\n").filter((line) => !line.trim().startsWith("#"));
255
+ expect(commands.filter((line) => /\b(pnpm|npm|npx|node)\s/.test(line))).toEqual([]);
256
+ expect(selfhost).toContain('FREEHOLDER_IMAGE "ghcr.io/campdenman/freeholder:$(release_version)"');
257
+ for (const file of ["compose.yml", "compose.https.yml"]) {
258
+ expect(readFileSync(join(DEPLOY, "docker-selfhost/infra", file), "utf8")).not.toContain(":edge}");
259
+ }
260
+ });
261
+ });
262
+
213
263
  describe("the droplet backup is a verifiable restore artifact", () => {
214
264
  const backup = readFileSync(
215
265
  join(DEPLOY, "digitalocean-droplet", "infra", "backup.sh"),
@@ -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
+ });
@@ -0,0 +1,169 @@
1
+ // Copyright (C) 2026 Tony Aly
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // C3.44: the no-Docker Linux install. These files are shell and systemd, not
4
+ // imported by anything, so the properties an owner relies on are pinned here.
5
+ // The installer itself runs end to end in .github/workflows/release-tarballs.yml.
6
+ import { execFileSync } from "node:child_process";
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { describe, expect, it } from "vitest";
10
+ import { parse } from "yaml";
11
+ import { releaseArch, releaseName } from "../../scripts/build-release.mjs";
12
+
13
+ const LINUX = join("deploy", "linux");
14
+ const read = (path: string) => readFileSync(path, "utf8");
15
+ const version = (JSON.parse(read("package.json")) as { version: string }).version;
16
+
17
+ describe("the release version is the one every manual install names", () => {
18
+ // Release preparation bumps package.json; this makes it bump the documented
19
+ // install too, so a downloaded install.sh installs its own release and the
20
+ // Docker recipe defaults to it rather than to `edge`.
21
+ it("install.sh, the Compose defaults and the copyable blocks agree with package.json", () => {
22
+ expect(read(join(LINUX, "install.sh"))).toContain(`FREEHOLDER_VERSION_DEFAULT="${version}"`);
23
+ for (const file of ["compose.yml", "compose.https.yml"]) {
24
+ expect(read(join("deploy/docker-selfhost/infra", file))).toContain(`ghcr.io/campdenman/freeholder:${version}}`);
25
+ }
26
+ const download = `https://github.com/CampDenman/freeholder/releases/download/v${version}/install.sh`;
27
+ expect(read("GETTING_STARTED.md")).toContain(download);
28
+ expect(read(join(LINUX, "README.md"))).toContain(download);
29
+ expect(read("deploy/docker-selfhost/README.md")).toContain(`--branch v${version} `);
30
+ });
31
+ });
32
+
33
+ describe("install.sh", () => {
34
+ const script = read(join(LINUX, "install.sh"));
35
+
36
+ it("is POSIX sh that dash parses, and stops at the first error", () => {
37
+ expect(script.startsWith("#!/bin/sh\n")).toBe(true);
38
+ expect(script).toMatch(/^set -eu$/m);
39
+ execFileSync("sh", ["-n", join(LINUX, "install.sh")]);
40
+ execFileSync("sh", ["-n", join(LINUX, "freeholder")]);
41
+ });
42
+
43
+ it("verifies the tarball's SHA-256 before unpacking anything", () => {
44
+ const verify = script.indexOf('[ "$expected" = "$actual" ]');
45
+ expect(verify).toBeGreaterThan(0);
46
+ expect(script.indexOf("tar -xzf")).toBeGreaterThan(verify);
47
+ expect(script).toContain("checksum mismatch");
48
+ });
49
+
50
+ it("installs PostgreSQL 15+ and Caddy from distribution or official repositories only", () => {
51
+ expect(script).toContain("/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh");
52
+ expect(script).toContain("https://dl.cloudsmith.io/public/caddy/stable/gpg.key");
53
+ expect(script).not.toMatch(/curl[^\n]*\|\s*(sh|bash)\b/);
54
+ });
55
+
56
+ it("unpacks into a versioned, root-owned release with a current symlink", () => {
57
+ expect(script).toContain('release="/opt/freeholder/releases/${version}"');
58
+ expect(script).toContain('chown -R root:root "$release.partial"');
59
+ expect(script).toContain("mv -T /opt/freeholder/current.new /opt/freeholder/current");
60
+ });
61
+ });
62
+
63
+ describe("the freeholder operator command", () => {
64
+ const command = read(join(LINUX, "freeholder"));
65
+
66
+ it("generates secrets with openssl and keeps them private", () => {
67
+ expect(command).toContain("openssl rand -hex 32");
68
+ for (const name of ["BOOTSTRAP_SECRET", "SESSION_SECRET", "CREDENTIAL_KEY", "POSTGRES_PASSWORD"]) {
69
+ expect(command).toContain(`ensure_secret ${name}`);
70
+ }
71
+ expect(command).toContain('chown root:freeholder "$tmp"');
72
+ expect(command).toContain('chmod 640 "$tmp"');
73
+ // The database password goes to psql on stdin, never on a command line.
74
+ expect(command).toMatch(/psql -v ON_ERROR_STOP=1 -qtA postgres\) <<SQL/);
75
+ });
76
+
77
+ it("defaults to local media in the data directory, outside the replaceable release", () => {
78
+ expect(command).toContain("env_set FREEHOLDER_STORAGE local");
79
+ expect(command).toContain('env_set LOCAL_STORAGE_ROOT "$MEDIA"');
80
+ expect(command).toContain("MEDIA=$DATA/media");
81
+ expect(command).toContain("DATA=/var/lib/freeholder");
82
+ });
83
+
84
+ it("backs up a custom-format dump and the media with checksums, and restores into a scratch database", () => {
85
+ expect(command).toContain("pg_dump --format=custom --no-owner --no-privileges freeholder");
86
+ expect(command).toContain("media.tar.gz");
87
+ expect(command).toContain("sha256sum ./* > SHA256SUMS");
88
+ expect(command).toContain("sha256sum --quiet -c SHA256SUMS");
89
+ expect(command).toMatch(/pg_restore [^\n]*-d freeholder_restore/);
90
+ expect(command).not.toMatch(/^\s*[^#\n]*--clean/m);
91
+ // A restore takes a safety backup before it changes anything.
92
+ const restore = command.slice(command.indexOf("cmd_restore() {"));
93
+ expect(restore.indexOf('cmd_backup --reason "before-restore"')).toBeLessThan(restore.indexOf("restore_database"));
94
+ });
95
+
96
+ it("updates only to a verified release, backs up first, and rolls back the release and database on failure", () => {
97
+ const update = command.slice(command.indexOf("cmd_update() {"), command.indexOf("rollback_to() {"));
98
+ expect(command).toContain('[ -n "$expected" ] && [ "$expected" = "$actual" ]');
99
+ expect(update.indexOf("fetch_release")).toBeLessThan(update.indexOf("cmd_backup"));
100
+ expect(update.indexOf("cmd_backup")).toBeLessThan(update.indexOf("switch_to"));
101
+ expect(update).toContain('rollback_to "$from" "$backup"');
102
+ const rollback = command.slice(command.indexOf("rollback_to() {"));
103
+ expect(rollback).toContain('restore_database "$BACKUPS/$2/database.dump"');
104
+ });
105
+
106
+ it("prints the claim link only to the operator's terminal", () => {
107
+ expect(command).toContain("printf '%s/setup#claim=%s\\n'");
108
+ expect(command).toMatch(/cmd_claim_link\(\) \{\n need_root claim-link/);
109
+ });
110
+
111
+ it("starts on an sslip.io address when DNS is not ready, the same naming as the CLI", () => {
112
+ expect(command).toContain("sslip_host()");
113
+ expect(command).toContain("tr . -");
114
+ });
115
+ });
116
+
117
+ describe("systemd and Caddy", () => {
118
+ it("runs as the freeholder user with a read-only release and only the data directory writable", () => {
119
+ const unit = read(join(LINUX, "share/systemd/freeholder.service"));
120
+ expect(unit).toMatch(/^User=freeholder$/m);
121
+ expect(unit).toMatch(/^ProtectSystem=strict$/m);
122
+ expect(unit).toMatch(/^ReadWritePaths=\/var\/lib\/freeholder$/m);
123
+ expect(unit).toMatch(/HOSTNAME=127\.0\.0\.1/);
124
+ expect(unit).toMatch(/^ExecStart=\/opt\/freeholder\/current\/runtime\/node\/bin\/node server\.js$/m);
125
+ });
126
+
127
+ it("backs up nightly, catching up after downtime", () => {
128
+ const timer = read(join(LINUX, "share/systemd/freeholder-backup.timer"));
129
+ expect(timer).toMatch(/^OnCalendar=\*-\*-\* 03:15:00$/m);
130
+ expect(timer).toMatch(/^Persistent=true$/m);
131
+ expect(read(join(LINUX, "share/systemd/freeholder-backup.service"))).toContain("freeholder backup --scheduled");
132
+ });
133
+
134
+ it("the Caddyfile overwrites the trusted client header and refuses the image optimizer", () => {
135
+ const caddy = read(join(LINUX, "share/Caddyfile.template"));
136
+ expect(caddy).toContain("reverse_proxy 127.0.0.1:3000");
137
+ expect(caddy).toMatch(/header_up X-Freeholder-Client-Ip \{client_ip\}/);
138
+ expect(caddy).toMatch(/@nextImage path \/_next\/image \/_next\/image\/\*\n\s*respond @nextImage 404/);
139
+ expect(read(join(LINUX, "freeholder"))).toContain("env_set TRUSTED_CLIENT_IP_HEADER x-freeholder-client-ip");
140
+ });
141
+ });
142
+
143
+ describe("the recipe", () => {
144
+ it("is a complete recipe whose artifacts exist", () => {
145
+ const recipe = parse(read(join(LINUX, "recipe.yaml"))) as { name: string; artifacts: string[]; operations: Record<string, string> };
146
+ expect(recipe.name).toBe("linux");
147
+ for (const artifact of recipe.artifacts) expect(() => read(artifact)).not.toThrow();
148
+ for (const operation of ["install", "verify", "backup", "restore", "update", "rollback"]) {
149
+ expect(recipe.operations[operation]).toBeTruthy();
150
+ }
151
+ });
152
+ });
153
+
154
+ describe("release tarball naming", () => {
155
+ it("names one tarball per version and architecture", () => {
156
+ expect(releaseName("0.2.0-beta.5", "x64")).toBe("freeholder-0.2.0-beta.5-linux-x64");
157
+ expect(releaseName("1.0.0", "arm64")).toBe("freeholder-1.0.0-linux-arm64");
158
+ expect(() => releaseArch("ia32")).toThrow(/x64 and arm64/);
159
+ expect(() => releaseName("latest", "x64")).toThrow(/release version/);
160
+ });
161
+
162
+ it("is built and installed for both architectures before a release gets it", () => {
163
+ const workflow = read(".github/workflows/release-tarballs.yml");
164
+ expect(workflow).toContain("runner: ubuntu-24.04-arm");
165
+ expect(workflow).toContain("sudo sh dist/release/install.sh --tarball");
166
+ expect(workflow).toContain("sudo freeholder restore latest");
167
+ expect(workflow).toContain("actions/attest-build-provenance@");
168
+ });
169
+ });