TL;DR
Tuturuuu CMS now lives in the dedicatedapps/cms satellite app.
New CMS-backed sites should use the global CMS site v1 contract. Add
site-specific structure through template and collection metadata instead of a
new adapter unless the integration has genuinely different authentication or
runtime behavior.
apps/cmsowns the CMS authoring UI, workspace picker, overview/content/preview/members routes, and the root/{wsId}/projectslinking console (reached as/internal/projectsfor the root workspace).apps/webremains the only backend/API owner for CMS and external-project traffic.apps/cmsrewrites/api/*toapps/web, so proxy behavior and bot protection stay centralized.
Product Vocabulary
The visible CMS experience is a site/content product, not an implementation console. Bound-workspace UI should say site, site template, connection, content, section, URL path, custom details, media, publishing, preview, people, invitations, and team access. Avoid implementation terms in normal UI copy, including external project, canonical, adapter, binding, slug, schema, metadata, profile data, payload, and JSON. If operators need exact implementation values, show them only in collapsed Developer details panels or internal root-console advanced controls. Keep code, API routes, database objects, migration names, and integration docs on the existingexternal-project* contracts.
Route Model
The route tree below mirrorsapps/cms/src/app/[locale]/(dashboard)/[wsId].
Workspace navigation is defined in
apps/cms/src/app/[locale]/(dashboard)/[wsId]/navigation.tsx. Every route is
workspace-scoped under /{wsId}; the root workspace uses the internal slug
(it resolves to ROOT_WORKSPACE_ID via normalizeWorkspaceId).
Root workspace
/{wsId}/projects(reached as/internal/projects): internal site-template registry, workspace-indexed connection list, and connection audit history. The internal workspace is not a bindable content workspace, so its overview, content, and/settingsroutes redirect into/{wsId}/projects.
Bound workspaces
/{wsId}: overview / continue-editing home./{wsId}/content: primary content operations surface (search, status filtering, publishing, reusable content)./{wsId}/content/collections/{collectionId}: collection (section) detail./{wsId}/content/entries/{entryId}: entry (content) detail./{wsId}/pages: page-builder surface for landing-style sections./{wsId}/media: media library./{wsId}/products: product catalog content./{wsId}/storefront: storefront configuration./{wsId}/taxonomy: taxonomy (terms, categories, tags)./{wsId}/games: game content surface, shown only when CMS Games is enabled for the workspace (getCmsGamesEnabled)./{wsId}/preview: site preview./{wsId}/members: workspace member search, invite, removal, role assignment, and role/default-permission management./{wsId}/settings: redirect-only route. It sends the internal workspace to/{wsId}/projectsand every other workspace to/{wsId}/members; CMS has no standalone settings screen.
Media publication and withdrawal
Uploads are available to workspace editors while staged. Public delivery includes media selected as a Studio cover, gallery image, audio item or finalized WebGL package, media IDs referenced by entry fields, and attachments on eligible blocks. An upload linked only to the entry stays private. A replaced cover stays private at the next publication unless another field still references it. Single and bulk publication apply the same selection rules. A finalized entry-level WebGL package counts as selected for older entries that have no saved WebGL selection. Publication rejects entries with more than 24 eligible assets before reading their stored bytes. Publishing commits the entry status, delivery event, and revision proof in one database transaction. A retry reuses a complete receipt for the current revision. If an older publish left the entry without its event or proof, the retry records a complete revision for the same entry. Each publication event stores the project’s delivery snapshot, including media references. The event payload is limited to 256 KiB of stored JSON text. If the snapshot exceeds that limit, the publication transaction rolls back. For older uploads without a saved selection, use Set as Cover for an existing image or add the gallery and audio items again before republishing. Only the server writes media publication proofs. Older event logs do not establish a media revision. Re-publish edited entries to record the verified media references for their current revision. Entries unchanged since before proofs began, including published imports, keep their attached stored media until their next edit; see the CMS public asset publication rules. Publication verifies the SHA-256 digest of each private asset before recording its proof. A public asset or revision check requires verified bytes before serving or authorizing reuse of cached media. Public media without a private stored object stays out of withdrawable delivery. Upload a new file to replace an attached object. Ordinary public asset reads cap originals at 10 MiB. Private collections and entries never deliver media anonymously. When a selected file exceeds 10 MiB or its private bytes cannot be verified, publication omits it from the proof and the CMS lists each omitted asset with its reason after publishing. Ordinary public asset reads reuse verified originals and image variants for up to two minutes in a 48 MiB cache per serving instance. Cache keys include the workspace, asset, asset revision and published digest. Byte ranges use the verified original. Each public request checks the current database publication proof before using cached bytes. Image transformations are limited to 60 requests per IP per minute per serving instance. Every WebGL finalization extracts into its own storage directory. The extraction service records the files and their SHA-256 digests after upload. Public requests serve only files whose bytes match that inventory. Older packages remain available to workspace editors for preview. Finalize and publish them again to restore public access. Use a ZIP extraction proxy that returns the digest inventory before enabling this workflow. The public delivery API returns an ETag with a no-store policy. External sites that cache resized media may use an anonymous HEAD request to/api/v1/workspaces/{wsId}/external-projects/assets/{assetId}?entry={entryId}&v={assetRevision}
to check current publication. Use the bytes only when the API returns 204
with the matching X-Tuturuuu-Published-Asset-Revision and no-store.
Public asset requests return verified bytes through the Platform after checking the
current publication. Storage URLs stay server-side. A URL issued by an
earlier deployment can remain usable until its original expiry.
Retry a failed unpublish through the same publish endpoint. It keeps an
already-withdrawn entry in draft and retries the publication event and
workspace cache invalidation. These behaviors are covered by
apps/web/src/lib/external-projects/publication.test.ts and the asset route tests.
Root Linking Console
- Treat
/{wsId}/projects(the root workspace’s/internal/projects) as a workspace-first control room. - The main left panel is the searchable workspace list.
- Each row shows the current connection state, site type, site template, and most recent change signal.
- The selected workspace panel owns connect and disconnect actions.
- The site-template registry is secondary and stays on the same page for create/edit flows.
- Binding audits stay anchored to the selected workspace instead of living as a detached global feed.
Workspace CMS
- Use
/{wsId}as the concise starting point for continue-editing tasks, launch readiness, attention queues, recent activity, and connected-site context. - Use
/{wsId}/contentfor broader content operations: search, status filtering, publishing queues, collection health, and reusable content. - Use
/{wsId}/pagesfor focused landing-style page edits, page readiness, and preview-first section work. - Use
/{wsId}/media,/{wsId}/products,/{wsId}/storefront, and/{wsId}/taxonomyfor the corresponding media, catalog, storefront, and taxonomy surfaces. - Use
/{wsId}/gamesfor game content when CMS Games is enabled for the workspace. - Use
/{wsId}/membersfor routine collaborator management without leaving CMS. - Keep collection configuration on
/{wsId}/content/collections/{collectionId}and entry authoring on/{wsId}/content/entries/{entryId}. - Use
/{wsId}/previewas the delivered-content surface backed by the existing preview delivery route. - CMS has no standalone settings screen;
/{wsId}/settingsis a redirect-only route to/{wsId}/members(or/{wsId}/projectson the internal workspace).
Member Management In CMS
- Workspace member search, invite, remove, and role-assignment controls now have a dedicated
/{wsId}/memberssidebar route. - The members surface also absorbs the essentials of the workspace roles page so CMS operators can manage named roles and default permissions without leaving CMS.
- This keeps standalone CMS usable without forcing operators back into the main platform app for routine collaborator changes.
- CMS members data must load through external-project-aware
apps/webAPI routes and@tuturuuu/internal-apihelpers. Reads should authorize by CMS workspace access so app-session users do not hit workspace settings-route 403s; writes still respect member and role management permissions. - Use CMS copy in this area: team access, people, invites, access levels, member defaults, guest defaults, and Advanced access.
- The workspace creator cannot be removed from the team. The creator can always manage the workspace, so this keeps someone who can manage members in every workspace whose creator is a member. It applies to every caller of the CMS remove route (
DELETE /api/v1/workspaces/{wsId}/external-projects/members/access?id=), including linked sites that manage their team through it; the route answers403with codeWORKSPACE_CREATOR_PROTECTEDand removes nothing, and it removes nothing when the creator cannot be read. Theidmust be a uuid written as8-4-4-4-12hex digits in either case; any other spelling is400. Cancelling an invitation by email is unaffected. Regression coverage:apps/web/src/lib/external-projects/team-member-removal.test.ts. - Board guests (people who hold direct task-board shares but no workspace membership) have no Remove action in CMS, because the CMS remove route revokes memberships and invitations, not board shares. Their row points to each board’s share settings instead. The standard workspace members page keeps Remove for them, since its removal also revokes the person’s board shares in that workspace (by user id, or by email for a guest without an account). Regression coverage:
packages/ui/src/components/ui/custom/workspace-access/workspace-access-member-row.test.tsx.
Guarded team removals
The RPCsremove_workspace_member_guarded and
remove_workspace_role_member_guarded serialize removals with a
workspace-scoped advisory lock. Only service_role may execute them.
The two CMS removal routes remove memberships only through these functions,
with the actor id their credential check resolved. Each route keeps its own
credential and permission check first; the functions authorize the actor
again as a second layer.
DELETE .../external-projects/members/access?id=validates the uuid (400) and refuses the workspace creator (403, codeWORKSPACE_CREATOR_PROTECTED) before callingremove_workspace_member_guarded. It cancels the person’s invitations only after the function answersremovedornot_found, so a refused or failed removal cancels nothing. A request with only?email=cancels the invitation without calling the function.DELETE .../external-projects/members/roles/{roleId}/members/{userId}answers404when the access level is not in the workspace and400whenuserIdis not a canonical uuid, then callsremove_workspace_role_member_guarded.
not_found is a success on both routes. The member route also cancels the
invitation of someone who was invited but never joined, by user id, and
removing an access level membership that is already gone has the result the
caller asked for. The CMS people screen shows translated messages for the two
codes instead of the server text.
Regression coverage: apps/web/src/lib/external-projects/team-member-removal.test.ts,
apps/web/src/lib/external-projects/team-access.test.ts,
packages/internal-api/src/external-project-team.test.ts and
packages/ui/src/components/ui/custom/workspace-access/workspace-access-removal-error.test.ts.
The RPCs require studio read and the corresponding workspace management
permission, or root CMS administrator permission. A root guest with an enabled
root default of admin, manage_external_projects, or manage_workspace_roles
also needs a full membership in the target workspace to remove a role
membership. Member removal accepts the root guest grant without target
membership.
If a full workspace member can manage members before a removal, at least one
must retain that permission after it. Only full members count toward this
requirement.
The RPCs return removed on success, not_found when the workspace or
scoped membership is missing, forbidden when the actor lacks permission, or
last_manager when the removal would leave no member manager. Member removal
also returns creator_protected for the workspace creator. Refusals leave the
membership and role assignments intact.
Deleting an access level
CMS deletes a named access level throughdelete_workspace_role_guarded.
The function authorizes the session actor in CMS mode and uses the same
workspace lock as team membership removal. Its transaction removes the role
and its assignments together. If a full member could manage members and
full members would still remain, the delete must retain that permission for
at least one full member. Guests and creators outside full membership do not
satisfy the rule. The existing CMS member and assignment RPCs apply their
stricter manager floor.
A refused delete returns HTTP 409 with WORKSPACE_LAST_MANAGER and the
people screen shows the translated refusal. An already absent role returns
success. The recorded Mastermind role retains its deletion protection.
The workspace-mode self-removal switch defaults off and applies only to
individual workspace-mode removals. It does not apply to CMS access levels.
Regression coverage lives in
CMS team access tests
and the
database removal suite.
Onboard editors for the first site
Use this runbook after the site-builder permission and publish changes have passed security review. Keep editor invitations on hold until the acceptance checks below pass on the deployed revision.Verify the permission contract
Verify the reviewed data/API contract before onboarding:- Confirm
edit_external_projectsexists in the permission enum and generated types. - Map editor to edit and preview; map publisher to edit, preview, and
publish_external_projects. Role names are labels; authorize by effective permissions, workspace membership, and the enabled site connection. - Keep
manage_external_projectsfor existing administrators. It currently implies publish access; do not grant it to editors or add edit access to the existing manage helper, which the publish helper also calls. - Add an edit authorization helper and policies for draft writes and private preview. Deny non-members and permission lookup errors. Restrict page versions and entries to the connected workspace and site.
- Require publish permission for every public transition, including direct status updates, bulk actions, imports, scheduling, and pointer changes.
- Keep preview read-only. The legacy entry publish endpoint accepts
eventKind: 'preview'but writesstatus: 'published'; it cannot serve as editor preview. - Commit the published version and its
workspace_external_project_publish_eventsrecord atomically. Include the authenticated actor, workspace, entry, site, event kind, and version identity. A failed audit write must leave the public version unchanged. The legacy store updates the entry before inserting the event and does not provide that guarantee.
Connect the workspace and configure access levels
- Have an authorized operator select the workspace for first site in the internal CMS Projects console and enable its site connection.
- Open that workspace’s Members page. Create the editor and publisher access levels with the reviewed permissions above.
- Check member defaults, guest defaults, and every additional role. Remove publishing grants from the editor’s effective permissions before inviting. Keep administrative, member-management, role-management, and billing grants out of both content roles unless separately authorized.
- Record the selected workspace, site, role IDs, reviewed source revision, and operator in the private operations record. Keep real IDs and addresses out of source control.
Invite an editor with an access level
- In Members, select Invite, enter the approved address, and select editor. Use an operator authorized to manage members and roles.
- Submit through the existing CMS invitation flow. It uses
inviteWorkspaceExternalProjectMembers(workspaceId, emails, { roleIds })from@tuturuuu/internal-apiand sendsPOSTto/api/v1/workspaces/{wsId}/external-projects/members/invite. - Inspect each result in
resultsand confirmsuccessCount. A successful HTTP response alone does not mean every invitation succeeded. Seat limits, invalid roles, and existing invitations can reject individual addresses. - For an existing pending invitation, use the access-level editor. It calls
updateWorkspaceExternalProjectInvitationRolesthroughPATCHon the same endpoint. Do not create a second invitation to change its role. - Have the invitee sign in with Tuturuuu Auth and accept the workspace invitation. Confirm membership and the assigned access level after acceptance. An invitation alone must not grant editor access.
create_workspace_email_invitation_with_roles. Use the external-project member
routes; ordinary workspace settings routes can reject valid CMS app sessions.
Verify gates before enabling the first site
Run these checks with disposable identities in an isolated test environment. Exercise direct API requests as well as the CMS controls:- Editor: open the page editor, save a draft, and preview it. Confirm the public version stays unchanged. Publish controls are unavailable, and publish, unpublish, public status updates, and scheduled publication are denied.
- Publisher: edit and publish. Confirm one successful publish event records the actor and the correct workspace, entry, site, and version.
- Non-member or pending invite: deny editor, draft, preview, and publish access, including requests with another workspace’s entry or role ID.
- Lookup failure: fail membership, connection, or permission resolution and confirm no content is returned or changed. A loading or error state must not enable the publish control.
- Audit failure: reject the publish-event insert and confirm neither the published pointer nor public entry status changes.
Linked-Site Email Security
Outbound email requested throughPOST /api/v1/workspaces/{wsId}/external-projects/emails is denied unless the
workspace binding has an explicit settings.outboundEmail grant. A valid app
secret and matching workspace binding are necessary but no longer sufficient.
Workspace security managers configure the grant on the main platform workspace
settings page:
enabledmust betrue.allowedRecipientDomainsmust contain every exact recipient domain. A grant forexample.comdoes not includesub.example.com, and wildcards are rejected.useRootWorkspaceCredentialsallows the workspace to borrow the managed platform sender while retaining workspace rate limits, blacklist checks, and audit attribution. Only a root user withmanage_external_projectsmay change this flag.
TURNSTILE_SECRET_KEY_RICHFIELD when present,
falling back to the platform-wide TURNSTILE_SECRET_KEY only for backwards
compatibility. This lets operators add or rotate Richfield’s widget without
changing the Turnstile secret used by other platform surfaces.
Validate focused behavior from the repository root:
Multipart upload request size
Web accepts request bodies up to 12 MiB for multipart POSTs to/api/v1/workspaces/{wsId}/external-projects/assets/upload-url and
/api/v1/workspaces/{wsId}/external-projects/storage. This limit includes form
fields and encoding overhead, with room for a 10 MiB file. For larger asset
uploads, request a signed upload URL and send the file to storage directly.
The handlers still check file type, size, and workspace quota. JSON requests,
including WebGL signed-URL requests, keep the default 512 KiB proxy limit.
apps/web/src/lib/external-projects/upload-proxy-payload-limit.test.ts covers
the two multipart paths and verifies that other methods, content types and
paths keep the default.
Upload image metadata
Multipart uploads to the same two paths, and managed asset imports from a source URL, store JPEG, PNG and WebP images without EXIF (including GPS location and camera serials), XMP, IPTC, MPF previews, comments, text chunks, embedded JFIF thumbnails, HDR gain maps (which then display as standard range) or bytes after the image end. The container is rewritten from an allowlist without decoding pixels, so quality does not change. ICC colour profiles, the fixed Adobe colour header and PNG colour chunks are kept. A non-default orientation is kept in a replacement EXIF block that holds only the Orientation tag.- Scope: the bytes decide the format, whatever type the client declares, so a
JPEG labelled
application/octet-streamis stripped too. - Refusals: bytes that look like JPEG, PNG or WebP but do not parse (for example a missing end marker, JPEG extension markers, unknown PNG critical chunks, metadata inside WebP animation frames, or files built from thousands of tiny blocks) are refused with 415. Managed imports record the same message as the asset’s failure.
- Signed-URL uploads send bytes straight to storage and are not stripped. A
signed upload request with
upsert: truewhose declared type or file extension is JPEG, PNG or WebP is refused with 400; replace images with a multipart upload. - Not stripped: GIF, AVIF, HEIC, SVG, audio and video are stored as received. HEIC, AVIF and MP4 files from phones can carry GPS location; keep them private or convert them to JPEG before publishing.
- Responses include
contentSha256(SHA-256 of the stored bytes) andmetadataStripped; the asset upload response also includes the storedsize.
packages/storage-core/src/lib/image-metadata-strip.test.ts covers the
fixtures, malformed containers, bounded work on adversarial files and fast-check
fuzzing; apps/web/src/lib/external-projects/upload-sanitize.test.ts decodes the
stored bytes with sharp to check dimensions, orientation and the colour profile.
Edge WAF exception for media uploads
Bearer-authenticated multipart uploads from linked sites can trip the Cloudflare OWASP Core rule949110: Inbound Anomaly Score Exceeded, because a
binary body scores as an anomaly. The edge answers 403 before the request
reaches the gateway or api-core, so Web logs show nothing and the app’s abuse
guard (ABUSE_CHALLENGE_REQUIRED) is not involved. JSON writes on the same
routes do not score, so a passing JSON call next to a failing upload is the
signature of this block.
The tuturuuu.com zone has a logged managed-rule exception
(15e29a570fdd4560b5c4c6e6e23d007c). It is placed directly after the Meet
audio-upload exception and before the managed-ruleset execute rules. It skips
only rule 6179ae15870a4bb7b2d480d4843b323c in the OWASP ruleset
4814384a9e5d4991b9815dcfc25d2f1f, for this expression:
- Diagnose: find the request’s Ray ID in Security Analytics (or
firewallEventsAdaptivefiltered by path) and confirm thefirewallManagedblock names rule 949110. - Extend: add a new multipart upload route (for example
external-projects/storage) to this expression through its own reviewed zone change, with a preimage and readback of the entrypoint ruleset. Never replace it with a ruleset-wide or domain-wide skip. - Roll back: delete the rule by id from the
http_request_firewall_managedentrypoint and read back that the other rules are unchanged.
Caching and publish visibility
Scope: the public delivery read (GET /api/v1/workspaces/{wsId}/external-projects/delivery),
published asset and image-variant reads, the version endpoint, and the CMS editor
shell. Affected surfaces: apps/web (delivery and asset routes),
packages/internal-api, apps/cms-renderer, and apps/cms.
Defaults:
- Delivery is edge-cached and keyed on the per-workspace delivery version. Every
content write bumps the workspace version in the same transaction, so a publish is
visible to readers within about 2 seconds (the per-isolate version memo). Public
delivery answers
Cache-Control: public, max-age=0, s-maxage=5, stale-while-revalidate=30with a weakETagand honorsIf-None-Matchwith a304. - Preview and drafts are never cached.
?preview=trueand every authenticated or draft read answerprivate, no-storeand skip the edge cache entirely.404,400and5xxresponses are never stored. - Assets are cached for 1 hour in the browser and 1 day at the edge
(
public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400), keyed on the asset, the published digest in?v=, the transform parameters and the delivery version, so an unpublish or republish is re-verified at the edge within about 2 seconds. Signed-URL redirects and authenticated asset reads stayprivate, no-store. - Fence: set
CMS_DELIVERY_EDGE_CACHE=0on the web Worker to bypass the delivery and asset edge caches. The version endpoint keeps working while the fence is on. - External apps key their own caches on the version.
GET /api/v1/workspaces/{wsId}/external-projects/delivery/versionreturns{ "version": <number> }withno-store, from one primary-key read memoized for 2 seconds. The number changes whenever any content, publish event, asset publication or binding for the workspace changes; compare it, then re-read delivery only when it moved. Delivery responses also carryX-Tuturuuu-Delivery-VersionandX-Tuturuuu-Delivery-Cache: HIT | MISS | BYPASS.
@tuturuuu/sdk(EpmClient.getDelivery()) still reads delivery withoutIf-None-Match; it benefits from the edge cache, and SDK-side revalidation is a follow-up.- Public reads through
@tuturuuu/internal-apileave the cache mode to the HTTP layer; only preview forcesno-store. apps/cms-rendererrevalidates delivery withIf-None-Matchfrom an in-isolate memo and addsX-Tuturuuu-Delivery-Versionto its rendered-HTML cache key, so a publish misses the HTML cache without a/__cms/purgecall./__cms/purgestill rotates the workspace namespace when an operator needs it.
apps/cms): authenticated editor responses are never shared-cached and every
access check is unchanged. The workspace layout starts the workspace, root permission,
binding and access reads together and consults each one only behind the same checks as
a sequential flow. Root permissions, the default binding read and the games flag are
memoized per request, so the layout, navigation and pages share one read. The content
page streams the studio payload from the server with the editor’s own session and falls
back to the client fetch if that read fails.
Intentional exceptions: draft edits also bump the version (over-invalidation is safe
because drafts are never cached), and the public delivery ETag is
W/"{revision}-v{version}", so a hard delete that leaves the content revision
unchanged still changes the tag and is never answered with a stale 304.
Regression coverage: packages/internal-api/src/external-projects.test.ts,
apps/cms-renderer/src/delivery-cache.test.ts,
apps/cms/src/app/[locale]/(dashboard)/[wsId]/layout.test.tsx,
apps/cms/src/lib/external-projects/initial-studio.test.ts, plus the delivery
edge-cache unit tests and the pgTAP version-counter test that ship with the web change.
Operations: see CMS caching and purge.
Typed entry relations
Scope: relation definitions and the entry relations written through the entry bundle routes, for every bound workspace. Affected surfaces:apps/web
(relation-definition, bundle and delivery routes) and every delivery client.
- Definitions.
GET /api/v1/workspaces/{wsId}/external-projects/relation-definitions(read access) lists the workspace’s definitions withtargetCollectionIds;?sourceCollectionId={uuid}narrows the list to one collection.POSTon the same path andPATCH/DELETEon/relation-definitions/{id}need manage access. A definition has akey(no whitespace, unique per source collection),label, optionalinverse_label,cardinality(oneormany),isRequired,sortOrderand at least one target collection. Source and target collections must belong to the same workspace; composite foreign keys enforce it. Linked apps call these routes with their app token (external-projects:readorexternal-projects:manage), as with every other studio route. - Writes.
POST /entries/bundleandPUT /entries/{id}/bundlereplace an entry’s outgoing relations. Each relation is{ definitionId, toEntryId, sortOrder, metadata }. The definition must start at the entry’s collection and target the far entry’s collection, andcardinality: oneallows a single relation per definition. A pair of entries holds at most one relation per definition.metadatais a flat object of string (up to 280 characters), number, boolean or null values, at most 2 KB as UTF-8 JSON; a bundle carries at most 256 relations. Anything else is refused with400before the database is written. - Studio view.
GET /api/v1/workspaces/{wsId}/external-projects(including?view=content&collectionSlugs=…) returnsrelationsfor the view’s source entries. Relations, definitions and targets are read page by page past the API row limit, and the response carriesrelationsComplete: trueto say so; a client can trust the list when it saves an entry’s relations. - Delivery. Each delivered entry’s
relationslists its typed relations whose far entry is also delivered (published, in a delivered collection, not flagged private), withrelation_definition_id,relation_type(the definition key when the relation was written;keyis the definition’s current key),sort_order,metadata,to_entry_id, and thedefinitionId/keyaliases. Relations without a definition are not delivered. The payload’srelationDefinitionslists definitions whose source collection is delivered, withtarget_collection_idslimited to delivered collections; a definition with no delivered target is left out. - Default and compatibility. All of these fields are additive. A workspace with
no relation definitions for its delivered collections has no
relationDefinitionskey, and its payload and revision are unchanged. When definitions are present, they are folded into the revision, so a label or target change refreshes the publicETag. Writes to relations, definitions, targets and blocks bump the delivery version counter, so edge caches revalidate without a purge.
apps/web/src/lib/external-projects/delivery-relations.test.ts,
apps/web/src/lib/external-projects/entry-bundle-relations.test.ts, the
relation-definitions and entry-bundle route tests, and the pgTAP
external-project-entry-bundles.sql suite.
Implementation Notes
- Keep CMS as a pure satellite frontend. Do not move API ownership into
apps/cms. - Continue adding or extending client helpers in
packages/internal-apifor CMS-facing API calls. - Keep preview sourced from the existing delivery route instead of introducing a second preview payload contract.
- Backend/database naming remains
external-project*; the product surface is what changed. - Protect CMS-owned product copy with the CMS copy hygiene test, and add explicit admin/developer-detail exceptions only when a staff workflow truly needs an implementation value.
- Translation validation now treats
nullleaves as invalid so missing shared keys fail checks instead of silently passing parity. POST /api/v1/workspaces/{wsId}/external-projects/setupenables the studio and is restricted to root external-project admins (see CMS studio enablement). For a root admin, setup preserves an existing same-adapter binding while refreshing the project schema and field definitions; otherwise it creates the canonical{adapter}-mainproject if needed, binds the workspace, and writes a binding audit row. A linked app using its app credentials may call setup only for its already-enabled workspace, which refreshes field definitions and template without touching the canonical project. Workspace managers use diff/apply on an enabled studio instead.- External apps can mark manifest assets with
metadata.publicPath,metadata.localAssetPath, or a relativesourceUrlsuch as/media/hero.png. - For a registered branded app using the
customadapter, make its app ID equal to the linked canonical template key (for example,rennu). Token exchange and subsequent content requests match that exact key, not the sharedcustomadapter name. Built-in integrations still match their adapter. The registered app workspace allowlist, enabled binding, user membership, and scoped permissions are all still required. A mismatch producesApp is not linked to this workspace; do not fix it by sharing another site’s app credentials. - Before diff/apply, run the public-folder linker so the manifest stores deterministic Drive paths under
external-projects/{adapter}/{collectionSlug}/{entrySlug}/{filename}. - Diff/apply routes are workspace-scoped. They may persist manifest schema into the bound workspace’s collections and field definitions, but they must not update
canonical_external_projectsor other root/canonical registry state. - Before apply, upload those files through the external-project asset app-server upload route. Abort the apply if a local public asset is missing so CMS never receives storage paths for objects that were not uploaded.
- Asset
storagePath/storage_pathvalues must stay underexternal-projects/. Do not point CMS assets at Drive, finance, or other workspace storage namespaces; delivery and admin cleanup only operate on assets that satisfy the CMS namespace invariant.
Storage analytics cache
The authenticated external-project storage analytics endpoint reads Supabase project statistics from a private Postgres snapshot keyed by workspace and adapter. It calculates file totals and highlights fromstorage.objects metadata, with a
1,000-object cap and an explicit truncated flag. Archived versions and folder
placeholders do not contribute to file totals.
Snapshots expire after five minutes. Storage inserts, updates, deletes, and moves
invalidate workspace snapshots in the same transaction, including direct uploads.
A shared workspace lock serializes refresh and invalidation so a concurrent file
change cannot leave a newly stored stale snapshot. Workspace quota is read live.
The cache is available only through a service-role RPC, after endpoint access and
rate-limit checks.
R2 uses the bounded provider scan. A missing RPC during an additive migration
rollout also uses that scan; other database failures remain visible. Production
activation requires the normal gated Supabase migration workflow. No cache
backfill is required.
The first-class Next handler preserves bodyless HEAD responses and request-time
authorization. Its future Rust port mirrors the Supabase cache response with live
quota and falls through to Next for fully configured R2 providers and unported
methods. Rust is not deployed; satellite-session and rate-limit parity remain
tracked prerequisites for a future cutover.
Database contract gate
external-project-storage-analytics-contract.yaml checks the exact PR head with
all tracked Supabase schema inputs. Its verifier requires the reviewed migration
body under the root-reserved forward filename, runs all 15 strict SQL assertions,
generates actual public/private/storage types, and closes its owned disposable
stack. A skipped wrapper or local source test does not establish this DB gate.
After the 15-assertion sequential fixture, the gate uses distinct bounded psql
sessions for first-cache-row refresh versus insert/update. It observes the
contender waiting on the actual workspace advisory lock (namespace 73007), then
requires invalidation and exact recalculation after both sessions complete.
Authored Node wiring tests do not establish that race; its actual hosted receipt
is required before merge. Linux’s shared rootful Docker daemon is not a
qualified contained executor; do not run this verifier there to bypass that gate.
Team Guidance
- Link into the CMS-native route map directly.
- Prefer the root
/internal/projectsconsole (the root workspace’s/{wsId}/projects) for site-template and workspace-link operations. - Keep bound-workspace collaborator management on the dedicated
/{wsId}/membersroute, and do not surface the root projects console inside non-root workspace sidebars. - Update both
apps/cms/messages/en.jsonandapps/cms/messages/vi.json, then runbun i18n:sortwhenever CMS copy changes.
Content reference scope
CMS root administration requiresmanage_external_projects in the root
workspace. Role administration alone does not grant this capability. Content
blocks reference entries in their own workspace, and collection-specific fields
reference collections in that workspace. Global fields may omit a collection.
These rules apply to the CMS satellite and Web’s shared content store; regression
coverage lives in the CMS access tests and Web’s
store-reference-scope.test.ts.