@kernhq/module-quire 0.11.1 → 0.13.0

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 (52) hide show
  1. package/dist/contract/models.d.ts +46 -0
  2. package/dist/contract/models.d.ts.map +1 -1
  3. package/dist/contract/models.js +73 -0
  4. package/dist/contract/models.js.map +1 -1
  5. package/dist/contract/permissions.d.ts +17 -1
  6. package/dist/contract/permissions.d.ts.map +1 -1
  7. package/dist/contract/permissions.js +35 -0
  8. package/dist/contract/permissions.js.map +1 -1
  9. package/dist/contract/router.d.ts +756 -0
  10. package/dist/contract/router.d.ts.map +1 -1
  11. package/dist/contract/router.js +346 -2
  12. package/dist/contract/router.js.map +1 -1
  13. package/dist/server/_impl.d.ts +826 -0
  14. package/dist/server/_impl.d.ts.map +1 -1
  15. package/dist/server/_impl.js +336 -2
  16. package/dist/server/_impl.js.map +1 -1
  17. package/dist/server/schema.d.ts +318 -1
  18. package/dist/server/schema.d.ts.map +1 -1
  19. package/dist/server/schema.js +86 -0
  20. package/dist/server/schema.js.map +1 -1
  21. package/dist/server/services/access.d.ts +1 -0
  22. package/dist/server/services/access.d.ts.map +1 -1
  23. package/dist/server/services/index.d.ts +3 -0
  24. package/dist/server/services/index.d.ts.map +1 -1
  25. package/dist/server/services/index.js +5 -1
  26. package/dist/server/services/index.js.map +1 -1
  27. package/dist/server/services/pages.d.ts.map +1 -1
  28. package/dist/server/services/pages.js +6 -0
  29. package/dist/server/services/pages.js.map +1 -1
  30. package/dist/server/services/publications.d.ts +191 -0
  31. package/dist/server/services/publications.d.ts.map +1 -0
  32. package/dist/server/services/publications.js +772 -0
  33. package/dist/server/services/publications.js.map +1 -0
  34. package/dist/server/services/versions.d.ts +26 -1
  35. package/dist/server/services/versions.d.ts.map +1 -1
  36. package/dist/server/services/versions.js +44 -15
  37. package/dist/server/services/versions.js.map +1 -1
  38. package/migrations/0008_publications.sql +140 -0
  39. package/migrations/0009_public_asset_references.sql +35 -0
  40. package/migrations/meta/_journal.json +14 -0
  41. package/package.json +1 -1
  42. package/src/client/components/PublishDialog.svelte +920 -0
  43. package/src/client/components/SidebarRecents.svelte +17 -1
  44. package/src/client/i18n.ts +448 -0
  45. package/src/client/index.ts +21 -0
  46. package/src/client/mock.ts +436 -2
  47. package/src/client/pages/PageView.svelte +139 -0
  48. package/src/client/public-url.ts +76 -0
  49. package/src/client/query.ts +16 -0
  50. package/src/contract/models.ts +77 -0
  51. package/src/contract/permissions.ts +54 -1
  52. package/src/contract/router.ts +380 -1
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where a published site lives, decided in exactly one place.
3
+ *
4
+ * The module's `public.*` procedures deliberately know nothing about this. They answer `path`
5
+ * relative to a publication — `''` for the front page, `guide/install` for a nested one — and take
6
+ * `basePath` as an argument, because one instance may serve a site under this prefix and another
7
+ * under a domain of its own. That is the right call on the server and it leaves somebody having to
8
+ * decide the address, so this file is that somebody: the share dialog shows what it returns, the
9
+ * header link opens it, and whatever route eventually renders a published page has to match it.
10
+ *
11
+ * **`/p/` is a literal segment before the workspace, not after it.** Every other Kern URL starts
12
+ * with the workspace — `/{workspace}/quire/{space}/{page}` — and a published site cannot, because
13
+ * the shell's top-level route is `[ws]`: `/{workspace}/p/…` would be inside the signed-in app,
14
+ * behind its guard, which is the one thing a public URL must not be. A static first segment sorts
15
+ * ahead of a dynamic one in SvelteKit, so `/p/…` is reachable signed out and cannot be shadowed by
16
+ * a workspace. The cost is that a workspace whose slug is exactly `p` would collide, which is why
17
+ * the segment is here as a constant rather than typed out at three call sites.
18
+ *
19
+ * **The workspace is named by id, and it was named by slug until that address stopped resolving.**
20
+ * A slug is the nicer half of the trade — a customer publishing a handbook is publishing a URL they
21
+ * will print — and it is only nicer if it works. Turning a slug into the workspace id the public
22
+ * procedures require is a lookup nothing can do signed out: every workspace read in `core` is
23
+ * behind a membership check, and a published site has no member reading it. So the route layer
24
+ * accepts the id form and refuses everything else, and this dialog was handing customers an address
25
+ * that answered 404 in every deployment that is not the mock — measured by copying the link out of
26
+ * the share dialog and fetching it.
27
+ *
28
+ * The id is not a secret: it is already the first segment of the API path the address resolves to,
29
+ * and it names a tenant rather than anything inside one. When `core` grows a signed-out
30
+ * `workspaces.publicBySlug`, the slug form becomes correct as well and this is the one function
31
+ * that has to change.
32
+ */
33
+ export const PUBLIC_SITE_PREFIX = 'p'
34
+
35
+ export interface PublicSiteAddress {
36
+ /** the workspace's id, which is what the public procedures resolve a tenant by */
37
+ workspaceId: string
38
+ /** the publication's slug */
39
+ slug: string
40
+ /**
41
+ * A page's path *inside* the publication, as `public.site` and `public.page` report it. `''` is
42
+ * the front page, which is the whole of what the share dialog ever shows.
43
+ */
44
+ path?: string
45
+ }
46
+
47
+ /**
48
+ * `/p/<workspace>/<publication>` — **no trailing slash**, both segments already encoded.
49
+ *
50
+ * The route serves the canonical form without one and answers the trailing-slash form with a 308,
51
+ * so a base that ended in `/` put an extra hop into every link a customer printed or pasted.
52
+ *
53
+ * This is not the `basePath` argument `public.page` takes: that one has to start *and* end with a
54
+ * slash, and the route layer builds it from this by adding one.
55
+ */
56
+ export function publicSiteBasePath({ workspaceId, slug }: PublicSiteAddress): string {
57
+ return `/${PUBLIC_SITE_PREFIX}/${encodeURIComponent(workspaceId)}/${encodeURIComponent(slug)}`
58
+ }
59
+
60
+ /**
61
+ * The address to show somebody, absolute when there is an origin to be absolute against.
62
+ *
63
+ * `location` is read defensively rather than assumed: this module's client is source, built by the
64
+ * consumer, and a consumer that renders a screen on the server has no `location` at all. A relative
65
+ * address is still correct there — it is only the *copyable* one that has to be absolute.
66
+ */
67
+ export function publicSiteUrl(address: PublicSiteAddress, origin?: string): string {
68
+ const root = origin ?? (typeof location === 'undefined' ? '' : location.origin.replace(/\/+$/, ''))
69
+ const trail = (address.path ?? '')
70
+ .split('/')
71
+ .filter((segment) => segment.length > 0)
72
+ .map(encodeURIComponent)
73
+ .join('/')
74
+ const base = `${root}${publicSiteBasePath(address)}`
75
+ return trail ? `${base}/${trail}` : base
76
+ }
@@ -38,6 +38,22 @@ export const quireKeys = {
38
38
  recents: (workspaceId: string) => ['quire', 'recent', workspaceId] as const,
39
39
  watchers: (workspaceId: string, pageId: string) => ['quire', 'watcher', workspaceId, pageId] as const,
40
40
 
41
+ /**
42
+ * Who has published what.
43
+ *
44
+ * `publication` is the entity `publications.create|update|remove` announce, so every screen
45
+ * holding one of these keys redraws when somebody else publishes or takes a site down — which
46
+ * matters more here than anywhere else in the module, because the thing that changed is whether
47
+ * strangers can read a page.
48
+ *
49
+ * `site` is under the same entity on purpose. It is the *anonymous* read of a published site —
50
+ * what the share dialog checks the URL against — and it is stale the instant the publication
51
+ * changes, so it must be invalidated by the same announcement rather than by remembering to.
52
+ */
53
+ publications: (workspaceId: string, spaceId: string) =>
54
+ ['quire', 'publication', workspaceId, spaceId] as const,
55
+ site: (workspaceId: string, slug: string) => ['quire', 'publication', workspaceId, 'site', slug] as const,
56
+
41
57
  /** the schema — properties and views — which every open tab of a database is drawing */
42
58
  database: (workspaceId: string, databaseId: string) =>
43
59
  ['quire', 'database', workspaceId, databaseId] as const,
@@ -87,6 +87,30 @@ export const PageNode = z.object({
87
87
  icon: z.string().nullable(),
88
88
  hasChildren: z.boolean(),
89
89
  archivedAt: Timestamp.nullable(),
90
+ /**
91
+ * Kept out of every publication, present and future — `publications.optOut` sets it.
92
+ *
93
+ * On the node rather than on `Page` because the only screen that reads it is a *list*: the share
94
+ * dialog draws one row per descendant with a switch on it, and a switch whose state has to be
95
+ * fetched page by page is a screen that opens with everything wrong and corrects itself. Two more
96
+ * booleans on a row the sidebar already loads for the whole space is the cheap end of that trade.
97
+ *
98
+ * `.default(false)` so a tree drawn by a client newer than its server still parses; the inferred
99
+ * output type is required either way, which is what makes both constructors supply it.
100
+ */
101
+ excludedFromPublic: z.boolean().default(false),
102
+ /**
103
+ * Whether a reader without edit rights has anything to be served — `publishedVersionId != null`,
104
+ * as a boolean, because the id itself addresses `versions.get` and a tree row has no business
105
+ * carrying it.
106
+ *
107
+ * Here for the same list as the flag above, and it is the half that stops that list lying. An
108
+ * opt-out switch on its own says "this page is public" about a page nobody has ever published,
109
+ * which is the wrong answer in the safe direction — and a screen that is wrong in the safe
110
+ * direction today is one nobody checks tomorrow. Always false for a `live` doc and a `database`:
111
+ * neither has a published version, because `publishing.publish` refuses anything but a `page`.
112
+ */
113
+ hasPublishedVersion: z.boolean().default(false),
90
114
  })
91
115
  export type PageNode = z.infer<typeof PageNode>
92
116
 
@@ -244,4 +268,57 @@ export const Watcher = z.object({
244
268
  })
245
269
  export type Watcher = z.infer<typeof Watcher>
246
270
 
271
+ /**
272
+ * How a published site is coloured. `auto` follows the reader's own setting rather than the
273
+ * author's, which is the only one of the three that is a preference and not an instruction.
274
+ */
275
+ export const PublicationTheme = z.enum(['auto', 'light', 'dark'])
276
+ export type PublicationTheme = z.infer<typeof PublicationTheme>
277
+
278
+ /**
279
+ * A page, and everything under it, at a URL a signed-out stranger can open.
280
+ *
281
+ * The row *is* the grant: no publication, no public page, and deleting it takes the site down. What
282
+ * a reader is served is the **pinned published version** of each page — `Page.publishedVersionId`
283
+ * and the HTML rendered onto it — never the live document and never the draft. A page with no
284
+ * published version is not public, whatever the tree says.
285
+ *
286
+ * There is no `passwordHash` here and there never should be. `hasPassword` is the whole of what a
287
+ * client needs: whether to ask. A hash is a hash, a salt and a cost, and shipping it to a browser
288
+ * turns an online guess into an offline one.
289
+ */
290
+ export const Publication = z.object({
291
+ id: Id,
292
+ workspaceId: WorkspaceId,
293
+ /** the page the site is rooted at; its own published version is the front page */
294
+ rootPageId: Id,
295
+ /** false publishes exactly one page, which is what a single shared document wants */
296
+ includeDescendants: z.boolean(),
297
+ /**
298
+ * The URL segment. Unique per workspace and not beyond it — the public URL carries the workspace,
299
+ * so two customers both wanting `handbook` is not a collision. Lowercase by the same rule as
300
+ * `Space.key`: a URL that differs only in case is one URL to a person and two rows to Postgres.
301
+ */
302
+ slug: z
303
+ .string()
304
+ .min(2)
305
+ .max(64)
306
+ .regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/, 'lowercase letters, digits and dashes'),
307
+ /** whether a password is set — never the hash, and never the password */
308
+ hasPassword: z.boolean(),
309
+ /** null never expires; past means the URL is gone */
310
+ expiresAt: Timestamp.nullable(),
311
+ /** what a search result and a link preview say; empty falls back to the root page's own title */
312
+ seoTitle: z.string().max(200),
313
+ seoDescription: z.string().max(500),
314
+ ogImageUrl: z.string().max(2048).nullable(),
315
+ /** false sends `noindex`. Public and findable are different requests, and people mean both. */
316
+ indexable: z.boolean(),
317
+ theme: PublicationTheme,
318
+ createdBy: UserId.nullable(),
319
+ createdAt: Timestamp,
320
+ updatedAt: Timestamp,
321
+ })
322
+ export type Publication = z.infer<typeof Publication>
323
+
247
324
  export const Ok = z.object({ ok: z.literal(true) })
@@ -101,9 +101,25 @@ export const quirePermissions = definePermissions([
101
101
  * scope yet: `spaces.create` has no space to be scoped to.
102
102
  * - `filter` — a list that omits what you may not see rather than refusing. "You may not open it"
103
103
  * is a worse answer than not showing it, and `spaces.list` is deliberately the second.
104
+ * - `public` — there is no principal to ask about. See below.
105
+ *
106
+ * **`public` is the one that needs saying out loud.** Every other value here answers "which scope is
107
+ * this permission resolved at"; `public` answers "this procedure asks nobody anything", which is a
108
+ * different kind of statement and the only one in this module that can leak a customer's private
109
+ * pages to the internet. It is spelled as a value rather than an omission so that adding one is a
110
+ * line in a review instead of a missing entry nobody sees, and `authz.int.test.ts` treats it as its
111
+ * own case: it calls the procedure once as a principal denied everything and once as a genuine
112
+ * anonymous stranger, and fails unless the two answers are byte-for-byte identical. That is the
113
+ * property that matters — a public surface that quietly shows an author more than it shows a
114
+ * stranger is one whose author tests it and never sees what the world sees.
115
+ *
116
+ * `permission` is still required for a `public` entry, and it names the permission that had to be
117
+ * held to *create the grant* — `quire.page.publish`, the one somebody used to make the publication.
118
+ * It is not a check this procedure performs. `module.test.ts` holds every entry to a permission the
119
+ * module declares, and there is no honest way to write "none" that keeps the rest of that check.
104
120
  */
105
121
  export interface ProcedureAuthz {
106
- check: 'page' | 'space' | 'workspace' | 'filter'
122
+ check: 'page' | 'space' | 'workspace' | 'filter' | 'public'
107
123
  permission: string
108
124
  }
109
125
 
@@ -191,4 +207,41 @@ export const quireProcedureAuthz: Record<string, ProcedureAuthz> = {
191
207
 
192
208
  'publishing.publish': { check: 'page', permission: 'quire.page.publish' },
193
209
  'publishing.revert': { check: 'page', permission: 'quire.page.edit' },
210
+
211
+ /*
212
+ * A publication hands a page's whole subtree to the internet, so the question every one of these
213
+ * asks is about the **root page** — not the space, and not the workspace. `quire.page.publish` is
214
+ * already the permission that decides which version readers are served; deciding that the readers
215
+ * include everybody is the same decision one step further.
216
+ *
217
+ * `list` is the exception and is space-scoped, because "what has this space published" has no one
218
+ * page to resolve against. It filters as well: a publication whose root page the caller may not
219
+ * read is not named in the answer, for the same reason `pages.trash` does not name a title.
220
+ *
221
+ * `optOut` is `quire.page.publish` rather than `quire.page.edit` on purpose. Marking a page
222
+ * "never public" is a publishing decision about who may read it, not a change to what it says —
223
+ * and the two permissions are held by different people in a space where writing is open and
224
+ * publishing is not.
225
+ */
226
+ 'publications.list': { check: 'space', permission: 'quire.page.publish' },
227
+ 'publications.get': { check: 'page', permission: 'quire.page.publish' },
228
+ 'publications.create': { check: 'page', permission: 'quire.page.publish' },
229
+ 'publications.update': { check: 'page', permission: 'quire.page.publish' },
230
+ 'publications.remove': { check: 'page', permission: 'quire.page.publish' },
231
+ 'publications.optOut': { check: 'page', permission: 'quire.page.publish' },
232
+
233
+ /*
234
+ * The signed-out surface. Nothing here asks a permission, because there is nobody to ask about —
235
+ * see the note on `check: 'public'` above. What stands in for the permission check is that every
236
+ * query is scoped by the **publication**: its root page, the descendants that survive the prune,
237
+ * `excluded_from_public` false and a rendered published version. Workspace scope is what
238
+ * row-level security gives, and workspace scope is not publication scope.
239
+ */
240
+ 'public.site': { check: 'public', permission: 'quire.page.publish' },
241
+ 'public.page': { check: 'public', permission: 'quire.page.publish' },
242
+ 'public.search': { check: 'public', permission: 'quire.page.publish' },
243
+ 'public.sitemap': { check: 'public', permission: 'quire.page.publish' },
244
+ 'public.robots': { check: 'public', permission: 'quire.page.publish' },
245
+ 'public.asset': { check: 'public', permission: 'quire.page.publish' },
246
+ 'public.unlock': { check: 'public', permission: 'quire.page.publish' },
194
247
  }
@@ -1,4 +1,4 @@
1
- import { baseContract, Id, PageInput, page, UserId, WorkspaceId } from '@kernhq/contracts'
1
+ import { baseContract, Id, PageInput, page, Timestamp, UserId, WorkspaceId } from '@kernhq/contracts'
2
2
  import { z } from 'zod'
3
3
  import {
4
4
  CommentAnchor,
@@ -11,6 +11,8 @@ import {
11
11
  PageKind,
12
12
  PageNode,
13
13
  PageVersion,
14
+ Publication,
15
+ PublicationTheme,
14
16
  RecentView,
15
17
  RichDoc,
16
18
  Space,
@@ -67,6 +69,175 @@ export const WatchState = z.object({
67
69
  })
68
70
  export type WatchState = z.infer<typeof WatchState>
69
71
 
72
+ /**
73
+ * A published site addresses its pages by **path, never by id**, and that is a security decision
74
+ * rather than a matter of taste.
75
+ *
76
+ * Every id in a public response is a string somebody can try somewhere else, and the only way to be
77
+ * sure none of them opens a door is for there to be none. So the whole `public.*` surface below
78
+ * carries no page id, no space id, no version id, no user id and no workspace id — a nav entry, a
79
+ * breadcrumb, a search hit and a sitemap line are all `path`, and `path` is built from titles by the
80
+ * server. `publications.int.test.ts` walks every public response and fails on any uuid belonging to
81
+ * anything in the fixture, which is what keeps this true as the shapes grow.
82
+ *
83
+ * The root page's path is the empty string; a child's is its ancestors' slugs joined with `/`, each
84
+ * slug being its title reduced to letters, digits and dashes (Unicode letters, so a Persian title
85
+ * keeps a Persian slug) and suffixed `-2`, `-3` when two siblings would collide.
86
+ */
87
+ export const PublicNavEntry = z.object({
88
+ /** '' is the front page; everything else is `parent/child`, already URL-safe once encoded */
89
+ path: z.string(),
90
+ /** null only for the front page — the nav is flat, like `pages.tree`, and rebuilt into a tree */
91
+ parentPath: z.string().nullable(),
92
+ title: z.string(),
93
+ icon: z.string().nullable(),
94
+ })
95
+ export type PublicNavEntry = z.infer<typeof PublicNavEntry>
96
+
97
+ /** What is worth saying about a published site once a reader is allowed to see it. */
98
+ export const PublicSiteDetail = z.object({
99
+ title: z.string(),
100
+ description: z.string(),
101
+ ogImageUrl: z.string().nullable(),
102
+ /** false means the route layer sends `noindex`. Public and findable are different requests. */
103
+ indexable: z.boolean(),
104
+ /**
105
+ * The newest published version in the whole site.
106
+ *
107
+ * Deliberately *not* the newest `pages.updated_at`: that column moves on every keystroke in a
108
+ * draft, so publishing it would tell the internet when somebody was working on an unpublished
109
+ * change. A published site's freshness is when something was last published.
110
+ */
111
+ updatedAt: Timestamp,
112
+ nav: z.array(PublicNavEntry),
113
+ })
114
+ export type PublicSiteDetail = z.infer<typeof PublicSiteDetail>
115
+
116
+ /**
117
+ * A published site, or the door to it.
118
+ *
119
+ * `locked` is the one thing a password-protected site admits before the password: that there is a
120
+ * door. Everything else — the title, the description, the shape of the tree — is behind it, because
121
+ * a nav tree is a table of contents and a table of contents is most of what a private handbook is.
122
+ * `theme` comes out anyway so the challenge screen is not white on a site that is not.
123
+ */
124
+ export const PublicSite = z.object({
125
+ slug: z.string(),
126
+ theme: PublicationTheme,
127
+ locked: z.boolean(),
128
+ /** null exactly when `locked` */
129
+ site: PublicSiteDetail.nullable(),
130
+ })
131
+ export type PublicSite = z.infer<typeof PublicSite>
132
+
133
+ export const PublicBreadcrumb = z.object({ path: z.string(), title: z.string() })
134
+ export type PublicBreadcrumb = z.infer<typeof PublicBreadcrumb>
135
+
136
+ export const PublicPage = z.object({
137
+ path: z.string(),
138
+ title: z.string(),
139
+ icon: z.string().nullable(),
140
+ coverUrl: z.string().nullable(),
141
+ /**
142
+ * The pinned published version, drawn once and stored on the version — never the live document
143
+ * and never the draft — then passed through the public scrub: every `id` and `data-id` attribute
144
+ * removed, and every page mention either re-pointed at its public path or left as plain text.
145
+ */
146
+ html: z.string(),
147
+ publishedAt: Timestamp,
148
+ /**
149
+ * A cache validator for the pinned version, and **not the version's id**.
150
+ *
151
+ * A published page is immutable, so the response is a static read that should be cached until the
152
+ * page is published again — which is what an entity tag is for. It is a hash rather than the id
153
+ * because the id addresses `versions.get`, a procedure that asks a permission: handing it to the
154
+ * internet turns a cache key into something to try.
155
+ */
156
+ etag: z.string(),
157
+ breadcrumbs: z.array(PublicBreadcrumb),
158
+ })
159
+ export type PublicPage = z.infer<typeof PublicPage>
160
+
161
+ export const PublicSearchHit = z.object({
162
+ path: z.string(),
163
+ title: z.string(),
164
+ /** plain text from the published version, never from the draft */
165
+ snippet: z.string(),
166
+ })
167
+ export type PublicSearchHit = z.infer<typeof PublicSearchHit>
168
+
169
+ export const PublicSitemapEntry = z.object({ path: z.string(), lastModified: Timestamp })
170
+
171
+ /**
172
+ * One picture from a published page, **as bytes rather than as an address**.
173
+ *
174
+ * A published page used to carry its pictures as presigned storage URLs, written into the stored
175
+ * HTML at publish time. That was wrong twice over, and both halves were measured rather than
176
+ * argued. The URL is the storage key — `ws/<workspaceId>/<module>/<yyyy>/<mm>/<fileId>/<name>` —
177
+ * so every published page with a picture on it handed a stranger the tenant's workspace uuid and a
178
+ * file uuid, on the one surface whose whole rule is that no response carries an id; and a presigned
179
+ * GET expires in an hour while the HTML it was baked into is rendered once and stored for ever, so
180
+ * every image on every published site broke sixty minutes after it was published.
181
+ *
182
+ * So the HTML carries an opaque, workspace-sealed reference and the bytes come through here. The
183
+ * route layer fetches this from **its own server** and streams the body back under a URL of its
184
+ * own; nothing in the answer may reach a browser as-is, which is why it is bytes and not a link —
185
+ * there is no address in it to leak, and none to expire.
186
+ *
187
+ * Capped rather than streamed on purpose: a published handbook's illustration is tens of kilobytes,
188
+ * this path is anonymous, and an unbounded body on an unauthenticated endpoint is a way to spend
189
+ * somebody else's memory. Over the cap answers the same 404 as a picture that is not there.
190
+ */
191
+ export const PublicAsset = z.object({
192
+ /**
193
+ * The stored content type, narrowed to an image type before it is answered.
194
+ *
195
+ * The route layer serves these from the application's own origin, so the two things it owes back
196
+ * are `X-Content-Type-Options: nosniff` and, because `image/svg+xml` is a document that can carry
197
+ * script, a `Content-Security-Policy: default-src 'none'` on the response. Anything the server
198
+ * could not narrow to an image is refused here rather than sent for the route layer to be careful
199
+ * with.
200
+ */
201
+ contentType: z.string(),
202
+ /** base64 of the whole object */
203
+ bytes: z.string(),
204
+ /** how long the route layer may cache it; a version is immutable, so this is long */
205
+ maxAge: z.number().int().min(0),
206
+ })
207
+ export type PublicAsset = z.infer<typeof PublicAsset>
208
+
209
+ /**
210
+ * The URL prefix the route layer serves this site under, so a link between two published pages is a
211
+ * link and not a dead mention.
212
+ *
213
+ * The module knows a page's path inside its publication and nothing about the address it is served
214
+ * at — one instance mounts a site at `/p/<workspace>/<slug>/`, another at the root of its own
215
+ * domain. Rather than guess, it takes the prefix and refuses anything that is not one: it has to
216
+ * start and end with `/`, and its segments are unreserved characters only. That refusal is the
217
+ * point. `//evil.example/` is a protocol-relative URL wearing the costume of a local path, and a
218
+ * caller that could set it would have every link on somebody's published site point off-site.
219
+ */
220
+ export const PublicBasePath = z
221
+ .string()
222
+ .max(200)
223
+ .regex(/^\/(?:[A-Za-z0-9._~-]+\/)*$/, 'an absolute path ending in a slash')
224
+ .default('/')
225
+
226
+ /**
227
+ * The one thing the module does ask of whatever serves a published site: a place for its pictures.
228
+ *
229
+ * `public.page` writes every `<img src>` as `<basePath><segment>/<reference>`, so the route layer
230
+ * has to answer that address by calling `public.asset` and streaming the bytes back. It is a
231
+ * constant rather than a convention because two sides have to agree on it and only one of them can
232
+ * be wrong quietly — a route layer that does not serve it renders a published page with no
233
+ * pictures, which looks like a rendering bug and is a missing route.
234
+ *
235
+ * The leading `__` is what keeps it out of the way: a page's own path segment is `slugifyTitle`'s
236
+ * output, which is Unicode letters and digits separated by hyphens, so no title can ever produce a
237
+ * segment starting with an underscore and no published page can be shadowed by this one.
238
+ */
239
+ export const PUBLIC_ASSET_SEGMENT = '__media'
240
+
70
241
  export const quireContract = {
71
242
  spaces: {
72
243
  list: baseContract
@@ -519,6 +690,214 @@ export const quireContract = {
519
690
  .input(ws.extend({ pageId: Id }))
520
691
  .output(Page),
521
692
  },
693
+
694
+ /**
695
+ * Who has published what, from the inside. Every procedure here is authenticated and asks
696
+ * `quire.page.publish` about the **root page**, because that is the page whose subtree is being
697
+ * handed to the internet.
698
+ */
699
+ publications: {
700
+ list: baseContract
701
+ .route({ method: 'GET', path: '/spaces/{spaceId}/publications', ...t('publications') })
702
+ .input(ws.extend({ spaceId: Id }))
703
+ .output(z.array(Publication)),
704
+ get: baseContract
705
+ .route({ method: 'GET', path: '/publications/{publicationId}', ...t('publications') })
706
+ .input(ws.extend({ publicationId: Id }))
707
+ .output(Publication),
708
+ create: baseContract
709
+ .route({ method: 'POST', path: '/publications', ...t('publications') })
710
+ .input(
711
+ ws.extend({
712
+ rootPageId: Id,
713
+ slug: Publication.shape.slug,
714
+ includeDescendants: z.boolean().default(true),
715
+ /** the password itself, once; the server keeps a hash and never gives one back */
716
+ password: z.string().min(6).max(200).nullable().default(null),
717
+ expiresAt: Timestamp.nullable().default(null),
718
+ seoTitle: z.string().max(200).default(''),
719
+ seoDescription: z.string().max(500).default(''),
720
+ ogImageUrl: z.string().max(2048).nullable().default(null),
721
+ indexable: z.boolean().default(true),
722
+ theme: PublicationTheme.default('auto'),
723
+ }),
724
+ )
725
+ .output(Publication),
726
+ /**
727
+ * `password` is three-valued on purpose: a string sets one, `null` removes it, and leaving the
728
+ * key out changes nothing. A two-valued field would make every "rename the site" request also
729
+ * an "unlock the site" request, which is the shape that quietly takes the door off a handbook.
730
+ */
731
+ update: baseContract
732
+ .route({ method: 'PATCH', path: '/publications/{publicationId}', ...t('publications') })
733
+ .input(
734
+ ws.extend({
735
+ publicationId: Id,
736
+ slug: Publication.shape.slug.optional(),
737
+ includeDescendants: z.boolean().optional(),
738
+ password: z.string().min(6).max(200).nullable().optional(),
739
+ expiresAt: Timestamp.nullable().optional(),
740
+ seoTitle: z.string().max(200).optional(),
741
+ seoDescription: z.string().max(500).optional(),
742
+ ogImageUrl: z.string().max(2048).nullable().optional(),
743
+ indexable: z.boolean().optional(),
744
+ theme: PublicationTheme.optional(),
745
+ }),
746
+ )
747
+ .output(Publication),
748
+ /** The row is the grant, so removing it takes the site down. Nothing else is deleted. */
749
+ remove: baseContract
750
+ .route({ method: 'DELETE', path: '/publications/{publicationId}', ...t('publications') })
751
+ .input(ws.extend({ publicationId: Id }))
752
+ .output(Ok),
753
+ /**
754
+ * Keep one page — and therefore everything under it — out of every publication, present and
755
+ * future.
756
+ *
757
+ * Absolute rather than per-publication, and that is the whole reason it is a flag on the page:
758
+ * an opt-out recorded against one publication says nothing about a publication somebody roots
759
+ * above the page next month, and its author would never see it. This one holds against
760
+ * publications that do not exist yet.
761
+ */
762
+ optOut: baseContract
763
+ .route({ method: 'POST', path: '/pages/{pageId}/public-opt-out', ...t('publications') })
764
+ .input(ws.extend({ pageId: Id, excluded: z.boolean().default(true) }))
765
+ .output(z.object({ pageId: Id, excluded: z.boolean() })),
766
+ },
767
+
768
+ /**
769
+ * The signed-out surface. **This is the only part of Kern with no principal behind it.**
770
+ *
771
+ * Five rules hold here, and each of them is a test in `publications.int.test.ts`:
772
+ *
773
+ * 1. A page is public only if it is inside the publication's subtree, not opted out, not
774
+ * archived, not trashed, and has a published version that has been rendered. Failing any one
775
+ * of those is **404, never 403** — a refusal that distinguishes "not yours" from "not there"
776
+ * confirms the page exists to whoever is guessing.
777
+ * 2. Guessing a sibling, a parent, a page in another space or another workspace gets 404 too,
778
+ * which is free here because nothing is addressed by id: `path` names a place in *this*
779
+ * publication's tree or it names nothing.
780
+ * 3. No response carries a draft, a comment, an author, a version list, or any id.
781
+ * 4. A password-protected publication answers a challenge and nothing else. `unlock` mints a
782
+ * **capability token, not a session**: an AES-GCM envelope sealed with the instance secret,
783
+ * bound by its associated data to this one publication, carrying an expiry and no identity.
784
+ * The server keeps nothing. The route layer is expected to hold it in an HttpOnly cookie and
785
+ * pass it back — never to put it in a link, because a token in a URL is a token in a referrer
786
+ * header and in somebody's access log.
787
+ * 5. An expired publication is 404, checked on the request rather than by a sweep.
788
+ *
789
+ * `workspaceId` is in the path because *anonymous means no principal, not no tenant*: the request
790
+ * has to name a workspace before anything touches `mod_quire`, or row-level security has nothing
791
+ * to fence with. See the note at the top of `migrations/0008_publications.sql`.
792
+ */
793
+ public: {
794
+ site: baseContract
795
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}', ...t('public') })
796
+ .input(
797
+ z.object({
798
+ workspaceId: WorkspaceId,
799
+ slug: Publication.shape.slug,
800
+ token: z.string().max(4096).nullable().default(null),
801
+ }),
802
+ )
803
+ .output(PublicSite),
804
+ /**
805
+ * One page of a published site.
806
+ *
807
+ * `path` is a query parameter rather than a path segment because it contains slashes: a nested
808
+ * page's address is `guide/install`, and oRPC's route matcher takes one segment per parameter.
809
+ */
810
+ page: baseContract
811
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}/page', ...t('public') })
812
+ .input(
813
+ z.object({
814
+ workspaceId: WorkspaceId,
815
+ slug: Publication.shape.slug,
816
+ /** '' is the front page */
817
+ path: z.string().max(1024).default(''),
818
+ basePath: PublicBasePath,
819
+ token: z.string().max(4096).nullable().default(null),
820
+ }),
821
+ )
822
+ .output(PublicPage),
823
+ /**
824
+ * Search inside this publication and nowhere else.
825
+ *
826
+ * It reads the **published version's** flattened text, not `pages.text`. That column mirrors the
827
+ * live document, so searching it would put a sentence somebody has not published yet into a
828
+ * snippet on the public internet — the one place in this module where the draft and the
829
+ * published copy differ and the difference is the whole point.
830
+ */
831
+ search: baseContract
832
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}/search', ...t('public') })
833
+ .input(
834
+ z.object({
835
+ workspaceId: WorkspaceId,
836
+ slug: Publication.shape.slug,
837
+ q: z.string().min(2).max(200),
838
+ limit: z.number().int().min(1).max(50).default(20),
839
+ token: z.string().max(4096).nullable().default(null),
840
+ }),
841
+ )
842
+ .output(z.object({ items: z.array(PublicSearchHit) })),
843
+ /**
844
+ * What a crawler may index, which is not the same list as what a reader may open: a site behind
845
+ * a password, or marked `indexable: false`, has an empty sitemap rather than a private one.
846
+ */
847
+ sitemap: baseContract
848
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}/sitemap', ...t('public') })
849
+ .input(z.object({ workspaceId: WorkspaceId, slug: Publication.shape.slug }))
850
+ .output(z.object({ entries: z.array(PublicSitemapEntry) })),
851
+ /**
852
+ * The one procedure here that never distinguishes one slug from another.
853
+ *
854
+ * A crawler asking about a slug that does not exist, one that has expired, and one behind a
855
+ * password must all get the same answer, or `robots` becomes the oracle every other procedure
856
+ * refuses to be. So it succeeds for all three and says "do not index". (A workspace with the
857
+ * module switched off is still a 404, from the middleware — that is a statement about the
858
+ * workspace, which the path already named, and not about any slug.)
859
+ */
860
+ robots: baseContract
861
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}/robots', ...t('public') })
862
+ .input(z.object({ workspaceId: WorkspaceId, slug: Publication.shape.slug }))
863
+ .output(z.object({ indexable: z.boolean(), sitemapPath: z.string().nullable() })),
864
+ /**
865
+ * The bytes of one picture on a published page.
866
+ *
867
+ * `asset` is the opaque reference the page's own HTML carries — an AES-GCM envelope sealed with
868
+ * the instance secret and bound by its associated data to this workspace, so it names nothing
869
+ * on its own and cannot be carried to another instance. Resolving it is not enough on its own:
870
+ * the file has to be referenced by a version that is *currently* public in this publication, so
871
+ * opting a page out stops its pictures resolving in the same breath as its prose.
872
+ *
873
+ * Everything unresolvable is the same 404 as everything else here — a reference that will not
874
+ * decrypt, one for a file nothing public uses, a file that has been deleted, an object over the
875
+ * cap. And a locked publication answers the door first: the pictures are behind the password
876
+ * along with the pages they are on.
877
+ */
878
+ asset: baseContract
879
+ .route({ method: 'GET', path: '/public/{workspaceId}/{slug}/asset', ...t('public') })
880
+ .input(
881
+ z.object({
882
+ workspaceId: WorkspaceId,
883
+ slug: Publication.shape.slug,
884
+ asset: z.string().min(1).max(2048),
885
+ token: z.string().max(4096).nullable().default(null),
886
+ }),
887
+ )
888
+ .output(PublicAsset),
889
+ /** Present the password, get a token. A site with no password has no door, and answers 404. */
890
+ unlock: baseContract
891
+ .route({ method: 'POST', path: '/public/{workspaceId}/{slug}/unlock', ...t('public') })
892
+ .input(
893
+ z.object({
894
+ workspaceId: WorkspaceId,
895
+ slug: Publication.shape.slug,
896
+ password: z.string().min(1).max(200),
897
+ }),
898
+ )
899
+ .output(z.object({ token: z.string(), expiresAt: Timestamp })),
900
+ },
522
901
  } as const
523
902
  export type QuireContract = typeof quireContract
524
903