@crombolo/server 0.69.0 → 0.70.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 (46) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/workspace-dictionary.ts +287 -0
  10. package/src/adapters/workspace-file-port.ts +160 -0
  11. package/src/adapters/workspace-languages.ts +94 -0
  12. package/src/approvals-api.ts +16 -7
  13. package/src/bundle-api.ts +19 -16
  14. package/src/bundle-install.ts +4 -0
  15. package/src/change-transfer.ts +676 -0
  16. package/src/changes-api.ts +258 -0
  17. package/src/component-templates-api.ts +2 -2
  18. package/src/config.ts +162 -22
  19. package/src/content-events.ts +65 -1
  20. package/src/content-operations.ts +22 -3
  21. package/src/core.ts +2 -0
  22. package/src/environment-values-api.ts +161 -0
  23. package/src/host-token.ts +30 -1
  24. package/src/node-operations.ts +150 -2
  25. package/src/ports.ts +174 -52
  26. package/src/remote-changes.ts +279 -0
  27. package/src/remote-schema.ts +126 -0
  28. package/src/remote-workspaces.ts +82 -0
  29. package/src/remote.ts +289 -192
  30. package/src/schema-transfer.ts +240 -41
  31. package/src/schema.ts +7 -2
  32. package/src/seed/compile.ts +13 -1
  33. package/src/seed/values.ts +3 -0
  34. package/src/server.ts +971 -364
  35. package/src/settings.ts +123 -5
  36. package/src/site-sections.ts +1 -1
  37. package/src/workspace-access.ts +152 -0
  38. package/src/workspace-checks.ts +299 -0
  39. package/src/workspace-losses.ts +95 -0
  40. package/src/workspace-processes.ts +306 -0
  41. package/src/workspace-render-child.ts +168 -0
  42. package/src/workspace-schema-dir.ts +100 -0
  43. package/src/workspace-schema.ts +598 -0
  44. package/src/workspace-sites.ts +179 -0
  45. package/src/workspace-views.ts +121 -0
  46. package/src/workspaces.ts +1031 -0
package/src/server.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * API, the SPA shells, then the front-end site.
7
7
  */
8
8
 
9
+ import { AsyncLocalStorage } from 'node:async_hooks'
9
10
  import { timingSafeEqual } from 'node:crypto'
10
11
  import { existsSync, readFileSync } from 'node:fs'
11
12
  import { basename, join } from 'node:path'
@@ -92,8 +93,10 @@ import {
92
93
  byActor,
93
94
  currentAuditContext,
94
95
  type Db,
96
+ ExternalLoginRepository,
95
97
  ensureFormLibraryTypes,
96
98
  ensureKeyValue,
99
+ externalLoginProvider,
97
100
  FormEntryRepository,
98
101
  FormWorkflowRepository,
99
102
  FormWorkflowSecretRepository,
@@ -111,6 +114,9 @@ import {
111
114
  searchProvidersOf,
112
115
  TransferRunRepository,
113
116
  UserRepository,
117
+ WorkspaceFileRepository,
118
+ WorkspaceLinkRepository,
119
+ WorkspaceRepository,
114
120
  type WritesPaused,
115
121
  withAuditContext,
116
122
  } from '@crombolo/data'
@@ -189,10 +195,12 @@ import { handleComponentTemplates } from './component-templates-api.ts'
189
195
  import { checkTypes, listEmailTemplates, siteLayouts } from './components.ts'
190
196
  import {
191
197
  type CromboloConfig,
198
+ contentLocked,
192
199
  listeningBodyLimit,
193
200
  loadConfig,
194
201
  type ServerRole,
195
202
  VERSION,
203
+ workspacesOn,
196
204
  } from './config.ts'
197
205
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
198
206
  import { createCore } from './core.ts'
@@ -284,6 +292,7 @@ import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
284
292
  import { createTrustedSignersAdmin } from './trusted-signers-admin.ts'
285
293
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
286
294
  import type { JobsStatus } from './worker-watch.ts'
295
+ import { inSchemaPlace, type SchemaPlace } from './workspace-schema-dir.ts'
287
296
 
288
297
  export { PREVIEW_COOKIE }
289
298
 
@@ -292,7 +301,10 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
292
301
 
293
302
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
294
303
  import { backofficeAudience } from './backoffice-external.ts'
304
+ import { createChangeTransfer } from './change-transfer.ts'
305
+ import { createChangesApi } from './changes-api.ts'
295
306
  import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
307
+ import { createEnvironmentValuesApi } from './environment-values-api.ts'
296
308
  import { createExternalSignIn } from './external-sign-in.ts'
297
309
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
298
310
  import { exchangingProviders } from './identity-providers.ts'
@@ -337,6 +349,28 @@ import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
337
349
  import { summariseUpgrades } from './upgrade-summary.ts'
338
350
  import { createViewAs } from './view-as.ts'
339
351
  import { webhookStoreView } from './webhooks.ts'
352
+ import {
353
+ accessCookie,
354
+ linkSecretHash,
355
+ readAccess,
356
+ readHandoff,
357
+ signAccess,
358
+ signHandoff,
359
+ WORKSPACE_COOKIE,
360
+ WORKSPACE_COOKIE_SECONDS,
361
+ WORKSPACE_HANDOFF_ISSUER,
362
+ WORKSPACE_HANDOFF_PARAM,
363
+ WORKSPACE_HANDOFF_SECONDS,
364
+ WORKSPACE_LINK_HEADER,
365
+ WORKSPACE_LINK_PARAM,
366
+ type WorkspaceAccess,
367
+ workspaceHosts,
368
+ } from './workspace-access.ts'
369
+ import { createWorkspaceChecks } from './workspace-checks.ts'
370
+ import { createWorkspaceProcesses, type WorkspaceProcesses } from './workspace-processes.ts'
371
+ import { createWorkspaceSchema } from './workspace-schema.ts'
372
+ import { createWorkspaceSites } from './workspace-sites.ts'
373
+ import { createWorkspaceScope, createWorkspacesApi } from './workspaces.ts'
340
374
 
341
375
  export interface ServerHandle {
342
376
  config: CromboloConfig
@@ -398,6 +432,14 @@ export interface ServerHandle {
398
432
  reloadBundles(): Promise<BundleReload>
399
433
  /** Stops the watcher and the poll, then closes the database. */
400
434
  close(): Promise<void>
435
+ /** Where workspaces that changed their views render (story 378); none on a database in memory. */
436
+ workspaceProcesses: WorkspaceProcesses | undefined
437
+ /**
438
+ * A remote-protocol request as `principal`, in this process (story 386): how a
439
+ * command run in a site's folder reaches its workspaces and changes, as it would a
440
+ * hosted site's, with no server listening and the remote off.
441
+ */
442
+ remoteAs(request: Request, principal: Principal): Promise<Response>
401
443
  }
402
444
 
403
445
  export interface ServerOptions {
@@ -480,10 +522,10 @@ export async function createServer(
480
522
  formSecret,
481
523
  cacheOptions,
482
524
  mediaCache,
483
- cache,
525
+ cache: sharedCache,
484
526
  afterSync,
485
527
  snapshots,
486
- renderer,
528
+ renderer: sharedRenderer,
487
529
  mediaStore,
488
530
  email,
489
531
  notifier,
@@ -498,6 +540,29 @@ export async function createServer(
498
540
  wake,
499
541
  urlChange,
500
542
  } = core
543
+ // Story 379: while a request is served from a workspace's site, the cache and the
544
+ // renderer it reads are the workspace's; everything handed them follows.
545
+ const workspaceSiteScope = new AsyncLocalStorage<{
546
+ cache: PublishedCache
547
+ renderer: Renderer
548
+ workspace?: { id: number; key: string }
549
+ }>()
550
+ const viaWorkspaceSite = <T extends object>(
551
+ shared: T,
552
+ pick: (site: { cache: PublishedCache; renderer: Renderer }) => T,
553
+ ): T =>
554
+ new Proxy(shared, {
555
+ get(target, prop) {
556
+ const site = workspaceSiteScope.getStore()
557
+ const actual = site ? pick(site) : target
558
+ // The real object as the receiver: its getters read private fields.
559
+ const value = Reflect.get(actual, prop, actual)
560
+ return typeof value === 'function' ? value.bind(actual) : value
561
+ },
562
+ })
563
+ const cache = viaWorkspaceSite(sharedCache, (site) => site.cache)
564
+ const renderer = viaWorkspaceSite(sharedRenderer, (site) => site.renderer)
565
+
501
566
  /** The extensions that are on: granted, and not turned off (story 309). */
502
567
  const onExtensions = () =>
503
568
  extensions.list().filter(
@@ -775,6 +840,7 @@ export async function createServer(
775
840
  const draftSource = createPublishedContentSource(db, {
776
841
  nodeState: schema.nodeState,
777
842
  nodeId: schema.nodeId,
843
+ environment: config.environment,
778
844
  drafts: true,
779
845
  })
780
846
  const draftCache = async (): Promise<PublishedCache> => {
@@ -1053,6 +1119,14 @@ export async function createServer(
1053
1119
  jobsWaitingSince: () => core.workerWatch.status().waitingSince,
1054
1120
  activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
1055
1121
  onMediaAccessChange: (key) => mediaCache.drop([key]),
1122
+ // Made further down, and asked only once a request comes.
1123
+ schema: () => schemaTransfer,
1124
+ workspaces: () => workspacesApi,
1125
+ changes: () => (workspacesOn(config) ? changeTransfer : undefined),
1126
+ changeRoutes: () => ({
1127
+ handle: (request: Request, principal: Principal, rest: string) =>
1128
+ changesApi.handle(request, principal, rest, { ipAddress: null, forwardedFor: null }),
1129
+ }),
1056
1130
  onApplied: async () => {
1057
1131
  cache.invalidate()
1058
1132
  mediaCache.clear()
@@ -1386,6 +1460,7 @@ export async function createServer(
1386
1460
  const draft = await loadDraftNode(db, key, {
1387
1461
  nodeState: schema.nodeState,
1388
1462
  nodeId: schema.nodeId,
1463
+ environment: config.environment,
1389
1464
  })
1390
1465
  if (!draft) return undefined
1391
1466
  const snapshot = await cache.snapshot()
@@ -1607,6 +1682,27 @@ export async function createServer(
1607
1682
  })
1608
1683
  },
1609
1684
  })
1685
+ // Story 375: a request in a workspace, with the workspace held while it runs.
1686
+ const workspaceScope = createWorkspaceScope(db, {
1687
+ enabled: () => workspacesOn(config),
1688
+ required: () => config.workspacesRequired,
1689
+ locked: () => contentLocked(config),
1690
+ merge: () => core.operations.merge,
1691
+ schema: () => workspaceSchema,
1692
+ })
1693
+ /** Story 392: a designer's request, in the workspace it names, against its `schema/`. */
1694
+ const inDesignerPlace = async (
1695
+ request: Request,
1696
+ principal: Principal,
1697
+ operationId: string,
1698
+ shared: { schemaDir: string; writable: boolean },
1699
+ run: (place: SchemaPlace) => Promise<Response>,
1700
+ ): Promise<Response> => {
1701
+ const scope = await workspaceScope(request, principal, { operationId })
1702
+ if (scope instanceof Response) return scope
1703
+ const go = () => inSchemaPlace(db, shared, request, run, principal.id)
1704
+ return scope ? scope.run(go) : go()
1705
+ }
1610
1706
  const api = createManagementApiRouter({
1611
1707
  deps: managementDeps,
1612
1708
  authenticate,
@@ -1627,6 +1723,8 @@ export async function createServer(
1627
1723
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
1628
1724
  },
1629
1725
  onServerEvent: announce,
1726
+ // Story 375: a request in a workspace, with the workspace held while it runs.
1727
+ scope: workspaceScope,
1630
1728
  })
1631
1729
 
1632
1730
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
@@ -1715,12 +1813,121 @@ export async function createServer(
1715
1813
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1716
1814
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1717
1815
  const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1816
+ const workspacesPath = `${paths.pluginPath}/api/workspaces`
1817
+ const changesPath = `${paths.pluginPath}/api/changes`
1818
+ const environmentValuesPath = `${paths.pluginPath}/api/environment-values`
1819
+ // Story 376: a workspace's copy of the schema files.
1820
+ const workspaceSchema = createWorkspaceSchema(db, config, core.schema)
1821
+ // Story 378: a workspace that changed its views renders in a process of its own.
1822
+ // A database in memory cannot be opened from another process: it renders here then.
1823
+ const sharedDatabase = config.dialect === 'postgres' || config.sqliteFile !== ':memory:'
1824
+ const workspaceProcesses = sharedDatabase
1825
+ ? createWorkspaceProcesses({
1826
+ dialect: config.dialect,
1827
+ sqliteFile: config.sqliteFile,
1828
+ nodeState: core.schema.nodeState,
1829
+ nodeId: core.schema.nodeId,
1830
+ componentsCacheDir: config.componentsCacheDir,
1831
+ environment: config.environment,
1832
+ limit: config.workspaceProcesses,
1833
+ idleMs: config.workspaceProcessIdleMinutes * 60_000,
1834
+ memoryMb: config.workspaceProcessMemoryMb,
1835
+ renderMs: config.workspaceRenderSeconds * 1000,
1836
+ })
1837
+ : undefined
1838
+ const workspacesApi = createWorkspacesApi(db, {
1839
+ enabled: () => workspacesOn(config),
1840
+ locked: () => contentLocked(config),
1841
+ editedAt: () => config.contentEditedAt ?? null,
1842
+ checks: () => workspaceChecks,
1843
+ merge: () => core.operations.merge,
1844
+ nodeState: core.schema.nodeState,
1845
+ required: () => config.workspacesRequired,
1846
+ schema: () => workspaceSchema,
1847
+ // From the workspace's own site: its published pages, with its views (stories 377, 379).
1848
+ render: async (workspace, path) => {
1849
+ const site = await workspaceSites.siteFor(workspace)
1850
+ const result = await site.renderer.render(path)
1851
+ const views = site.views
1852
+ if (result.status === 'ok') return { status: 'ok', html: result.html, views }
1853
+ if (result.status === 'error') return { status: 'error', error: result.error.message, views }
1854
+ return { status: result.status, views }
1855
+ },
1856
+ onClosed: (key) => {
1857
+ workspaceProcesses?.stop(key)
1858
+ workspaceSites.forget(key)
1859
+ },
1860
+ // Story 390: a discarded workspace's files go, those nothing else names, after it.
1861
+ onDiscardedFiles: (urls) => {
1862
+ void removeUnnamedFiles(urls).catch((error: unknown) =>
1863
+ logger('media').warn('A discarded workspace left files: {error}', { error: String(error) }),
1864
+ )
1865
+ },
1866
+ open: (workspace, principal, path, request) =>
1867
+ workspaceOpenUrl(workspace, principal, path, request),
1868
+ links: () => workspaceLinks,
1869
+ })
1870
+ // Story 386: a workspace's diff, conflicts and checks, for the command line.
1871
+ const workspaceChecks = createWorkspaceChecks({
1872
+ db,
1873
+ merge: () => core.operations.merge,
1874
+ schema: () => workspaceSchema,
1875
+ async render(workspace, path) {
1876
+ const site = await workspaceSites.siteFor(workspace)
1877
+ const result = await site.renderer.render(path)
1878
+ if (result.status === 'ok') return { status: 'ok', html: result.html }
1879
+ if (result.status === 'error') return { status: 'error', error: result.error.message }
1880
+ return { status: result.status }
1881
+ },
1882
+ async urlOf(workspace, key) {
1883
+ const site = await workspaceSites.siteFor(workspace)
1884
+ return (await site.cache.byKey(key))?.url
1885
+ },
1886
+ })
1887
+ // Story 383: a change moved from one site to another, staged and applied as a workspace.
1888
+ const changeTransfer = createChangeTransfer({
1889
+ db,
1890
+ repository: { nodeState: core.schema.nodeState, nodeId: core.schema.nodeId },
1891
+ siteName: () => config.siteName,
1892
+ media: mediaFiles,
1893
+ schema: () => workspaceSchema,
1894
+ merge: () => core.operations.merge,
1895
+ })
1896
+ // Story 379: each workspace's site, kept on this node while it is looked at.
1897
+ const workspaceSites = createWorkspaceSites({
1898
+ db,
1899
+ environment: config.environment,
1900
+ nodeState: core.schema.nodeState,
1901
+ cacheOptions,
1902
+ processes: workspaceProcesses,
1903
+ componentsCacheDir: config.componentsCacheDir,
1904
+ componentsDir: config.componentsDir,
1905
+ snapshots,
1906
+ renderTimeoutMs: config.renderTimeoutMs,
1907
+ limit: config.workspaceSites,
1908
+ idleMs: config.workspaceSiteIdleMinutes * 60_000,
1909
+ })
1910
+ // Story 387: a property's value per environment.
1911
+ const environmentValuesApi = createEnvironmentValuesApi(db, {
1912
+ environment: () => config.environment,
1913
+ repository: { nodeState: core.schema.nodeState, nodeId: core.schema.nodeId },
1914
+ documents: () => core.operations.documents,
1915
+ readOnly: () => config.environmentValuesReadOnly || contentLocked(config),
1916
+ })
1917
+ // Story 381: every change to the site, and its revert.
1918
+ const changesApi = createChangesApi(db, {
1919
+ schema: () => workspaceSchema,
1920
+ nodeState: core.schema.nodeState,
1921
+ onReverted: () => core.cache.invalidate(),
1922
+ })
1718
1923
  const previewLinkPath = `${paths.pluginPath}/api/preview-link`
1719
1924
  const selfAudited = [
1720
1925
  `${paths.pluginPath}/api/email/`,
1721
1926
  `${paths.pluginPath}/api/schema-transfer/`,
1722
1927
  viewAsPath,
1723
1928
  cliTokensPath,
1929
+ workspacesPath,
1930
+ changesPath,
1724
1931
  ]
1725
1932
  const bundleInstallPaths = new Set(
1726
1933
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
@@ -1781,7 +1988,7 @@ export async function createServer(
1781
1988
  'crombolo.node.role': config.role,
1782
1989
  },
1783
1990
  async (span) => {
1784
- const response = await answer(request)
1991
+ const response = await inWorkspaceSite(request, () => answer(request))
1785
1992
  // Readers are answered from the previous cache while it rebuilds (story
1786
1993
  // 175), so a change is in it before the request that made it is answered.
1787
1994
  if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
@@ -1946,6 +2153,289 @@ export async function createServer(
1946
2153
  })
1947
2154
  }
1948
2155
 
2156
+ /**
2157
+ * Story 372: who the person is at the host's own provider, as their last
2158
+ * sign-in through it recorded, and only from that provider's issuer.
2159
+ */
2160
+ async function hostIdentityOf(userKey: string): Promise<{ host?: { sub: string; iss: string } }> {
2161
+ const id = config.host?.provider
2162
+ const provider = id
2163
+ ? config.backofficeIdentityProviders.find((p) => p.oidc.id === id)
2164
+ : undefined
2165
+ if (!provider) return {}
2166
+ const issuer = provider.oidc.issuer
2167
+ const link = (await new ExternalLoginRepository(db).forOwner(userKey)).find(
2168
+ (l) => l.loginProvider === externalLoginProvider('user', provider.oidc.id),
2169
+ )
2170
+ const identity = link?.identity
2171
+ return identity && identity.issuer === issuer
2172
+ ? { host: { sub: identity.value, iss: issuer } }
2173
+ : {}
2174
+ }
2175
+
2176
+ // ---------------------------------------------------------------- workspace sites (story 379)
2177
+
2178
+ const workspaceHostsOf = () => workspaceHosts(config.workspacesHost)
2179
+
2180
+ /** Where a workspace's site is, for a request on `origin`: its host, or the site's own. */
2181
+ function workspaceOrigin(workspace: { key: string }, request: Request): URL {
2182
+ const origin = new URL(publicOrigin(request, config))
2183
+ const hosts = workspaceHostsOf()
2184
+ if (hosts) origin.host = hosts.hostFor(workspace.key, origin.host)
2185
+ return origin
2186
+ }
2187
+
2188
+ /** A member's way in: a link with a single-use token, swapped for a cookie on first use. */
2189
+ async function workspaceOpenUrl(
2190
+ workspace: { key: string },
2191
+ principal: Principal,
2192
+ path: string,
2193
+ request?: Request,
2194
+ ): Promise<string | undefined> {
2195
+ const standing = await previewUser(db, { key: principal.id })
2196
+ if (!standing) return undefined
2197
+ const token = signHandoff(previewSecret, {
2198
+ workspace: workspace.key,
2199
+ user: standing.id,
2200
+ stamp: standing.stamp,
2201
+ id: crypto.randomUUID(),
2202
+ expires: Date.now() + WORKSPACE_HANDOFF_SECONDS * 1000,
2203
+ })
2204
+ const url = new URL(
2205
+ path.startsWith('/') ? path : `/${path}`,
2206
+ request
2207
+ ? workspaceOrigin(workspace, request)
2208
+ : publicOrigin(new Request('http://localhost/'), config),
2209
+ )
2210
+ url.searchParams.set(WORKSPACE_HANDOFF_PARAM, token)
2211
+ return url.toString()
2212
+ }
2213
+
2214
+ /** Links a member makes for someone else to look at the workspace's site. */
2215
+ const workspaceLinks = {
2216
+ maxDays: () => config.workspaceLinkMaxDays,
2217
+ async make(workspace: { id: number; key: string }, principal: Principal, days: number) {
2218
+ const secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
2219
+ const link = await new WorkspaceLinkRepository(db).make({
2220
+ workspaceId: workspace.id,
2221
+ madeBy: principal.id,
2222
+ secretHash: linkSecretHash(secret),
2223
+ expiresAt: new Date(Date.now() + days * 86_400_000),
2224
+ })
2225
+ const url = new URL('/', publicOrigin(new Request('http://localhost/'), config))
2226
+ const hosts = workspaceHostsOf()
2227
+ if (hosts) url.host = hosts.hostFor(workspace.key, url.host)
2228
+ url.searchParams.set(WORKSPACE_LINK_PARAM, secret)
2229
+ return { id: link.id, url: url.toString(), secret, expiresAt: link.expiresAt.toISOString() }
2230
+ },
2231
+ list: (workspaceId: number) => new WorkspaceLinkRepository(db).of(workspaceId),
2232
+ withdraw: (workspaceId: number, id: number) =>
2233
+ new WorkspaceLinkRepository(db).withdraw(workspaceId, id),
2234
+ }
2235
+
2236
+ /** The workspace an access names, if whoever holds it may still look: a member, or a link in date. */
2237
+ async function stillAllowed(access: WorkspaceAccess) {
2238
+ const repo = new WorkspaceRepository(db)
2239
+ const workspace = await repo.byKey(access.workspace)
2240
+ if (workspace?.state !== 'open') return undefined
2241
+ if ('user' in access) {
2242
+ const standing = await previewUser(db, { id: access.user })
2243
+ if (standing?.stamp !== access.stamp) return undefined
2244
+ const user = await db.q
2245
+ .selectFrom('user_account')
2246
+ .select('key')
2247
+ .where('id', '=', access.user)
2248
+ .execute()
2249
+ const key = user[0] ? normaliseUuid(String(user[0].key)) : ''
2250
+ return workspace.ownerKey === key || workspace.memberKeys.includes(key)
2251
+ ? workspace
2252
+ : undefined
2253
+ }
2254
+ const link = await new WorkspaceLinkRepository(db).byId(access.link)
2255
+ if (!link || link.workspaceId !== workspace.id || link.withdrawnAt) return undefined
2256
+ if (link.expiresAt.getTime() <= Date.now() || config.workspaceLinkMaxDays <= 0) return undefined
2257
+ // A link goes with its maker, when they leave the workspace.
2258
+ return workspace.ownerKey === link.madeBy || workspace.memberKeys.includes(link.madeBy)
2259
+ ? workspace
2260
+ : undefined
2261
+ }
2262
+
2263
+ /** What a link's secret opens: its workspace, as access for a cookie. */
2264
+ async function accessFromLink(secret: string): Promise<WorkspaceAccess | undefined> {
2265
+ const link = await new WorkspaceLinkRepository(db).bySecretHash(linkSecretHash(secret))
2266
+ if (!link) return undefined
2267
+ const workspace = (await new WorkspaceRepository(db).all()).find(
2268
+ (w: { id: number }) => w.id === link.workspaceId,
2269
+ )
2270
+ if (!workspace) return undefined
2271
+ const access: WorkspaceAccess = {
2272
+ workspace: workspace.key,
2273
+ link: link.id,
2274
+ expires: Math.min(link.expiresAt.getTime(), Date.now() + WORKSPACE_COOKIE_SECONDS * 1000),
2275
+ }
2276
+ return (await stillAllowed(access)) ? access : undefined
2277
+ }
2278
+
2279
+ /** A member's handoff, used once: access for a cookie, or nothing. */
2280
+ async function accessFromHandoff(token: string): Promise<WorkspaceAccess | undefined> {
2281
+ const claims = readHandoff(previewSecret, token)
2282
+ if (!claims) return undefined
2283
+ const standing = await previewUser(db, { id: claims.user })
2284
+ if (standing?.stamp !== claims.stamp) return undefined
2285
+ if (
2286
+ !(await new SingleUseTokens(db).use(
2287
+ WORKSPACE_HANDOFF_ISSUER,
2288
+ claims.id,
2289
+ new Date(claims.expires),
2290
+ ))
2291
+ )
2292
+ return undefined
2293
+ const access: WorkspaceAccess = {
2294
+ workspace: claims.workspace,
2295
+ user: claims.user,
2296
+ stamp: claims.stamp,
2297
+ expires: Date.now() + WORKSPACE_COOKIE_SECONDS * 1000,
2298
+ }
2299
+ return (await stillAllowed(access)) ? access : undefined
2300
+ }
2301
+
2302
+ /**
2303
+ * A request on a workspace's host, or with a workspace's cookie on the site's
2304
+ * own: answered from that workspace's site, to a member or a link's holder, and
2305
+ * never kept or indexed. Anything else goes on as it was.
2306
+ */
2307
+ async function inWorkspaceSite(
2308
+ request: Request,
2309
+ next: () => Promise<Response>,
2310
+ ): Promise<Response> {
2311
+ if (!workspacesOn(config)) return next()
2312
+ const url = new URL(request.url)
2313
+ const path = url.pathname
2314
+ const delivery = path.startsWith(DELIVERY_API_PREFIX)
2315
+ if (
2316
+ !delivery &&
2317
+ (path === paths.backOfficePath ||
2318
+ path.startsWith(`${paths.backOfficePath}/`) ||
2319
+ path.startsWith('/umbraco/'))
2320
+ )
2321
+ return next()
2322
+ const hosts = workspaceHostsOf()
2323
+ const named = hosts?.parse(url.host)
2324
+ if (hosts && !named) return next()
2325
+ const handoff = url.searchParams.get(WORKSPACE_HANDOFF_PARAM)
2326
+ const linked = url.searchParams.get(WORKSPACE_LINK_PARAM)
2327
+ const header = request.headers.get(WORKSPACE_LINK_HEADER)
2328
+ const cookie = readCookie(request, WORKSPACE_COOKIE)
2329
+ if (!named && !handoff && !linked && !header && !cookie) return next()
2330
+
2331
+ // A token or a secret in the address is swapped for the cookie, and the address cleaned.
2332
+ if ((handoff || linked) && (request.method === 'GET' || request.method === 'HEAD')) {
2333
+ const clean = new URL(url)
2334
+ clean.searchParams.delete(WORKSPACE_HANDOFF_PARAM)
2335
+ clean.searchParams.delete(WORKSPACE_LINK_PARAM)
2336
+ const headers = new Headers({
2337
+ location: `${clean.pathname}${clean.search}`,
2338
+ 'cache-control': PRIVATE_NO_STORE,
2339
+ 'referrer-policy': 'no-referrer',
2340
+ })
2341
+ const access = handoff
2342
+ ? await accessFromHandoff(handoff)
2343
+ : await accessFromLink(linked as string)
2344
+ if (access && (!named || named.key === access.workspace))
2345
+ headers.set(
2346
+ 'set-cookie',
2347
+ accessCookie(signAccess(previewSecret, access), config.secureCookies),
2348
+ )
2349
+ return new Response(null, { status: 303, headers })
2350
+ }
2351
+ const access = header
2352
+ ? await accessFromLink(header)
2353
+ : cookie
2354
+ ? readAccess(previewSecret, cookie)
2355
+ : undefined
2356
+ const workspace = access ? await stillAllowed(access) : undefined
2357
+ if (!workspace || (named && named.key !== workspace.key)) {
2358
+ // On a workspace's host a stranger sees nothing; on the site's own, Shared.
2359
+ if (!named) return next()
2360
+ return new Response('There is no such workspace, or it is not yours to see.', {
2361
+ status: 404,
2362
+ headers: {
2363
+ 'content-type': 'text/plain; charset=utf-8',
2364
+ 'cache-control': PRIVATE_NO_STORE,
2365
+ 'x-robots-tag': 'noindex, nofollow',
2366
+ },
2367
+ })
2368
+ }
2369
+ const site = await workspaceSites.siteFor({ id: workspace.id, key: workspace.key })
2370
+ const response = await workspaceSiteScope.run(site, async () => {
2371
+ if (path === '/robots.txt')
2372
+ return new Response('User-agent: *\nDisallow: /\n', {
2373
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
2374
+ })
2375
+ if (path === '/sitemap.xml' || path.startsWith('/sitemap'))
2376
+ return new Response('Not Found', { status: 404 })
2377
+ // Its own stylesheets and scripts, as it has them (stories 377, 379).
2378
+ const area = path.startsWith('/css/')
2379
+ ? { prefix: 'stylesheets/', at: '/css/', type: 'text/css; charset=utf-8' }
2380
+ : path.startsWith('/scripts/')
2381
+ ? { prefix: 'scripts/', at: '/scripts/', type: 'text/javascript; charset=utf-8' }
2382
+ : undefined
2383
+ if (area) {
2384
+ const key = `${area.prefix}${decodeURIComponent(path.slice(area.at.length))}`
2385
+ const text = (await new WorkspaceFileRepository(db).files(workspace.id, area.prefix)).get(
2386
+ key,
2387
+ )
2388
+ if (text !== undefined)
2389
+ return new Response(text, { headers: { 'content-type': area.type } })
2390
+ }
2391
+ return next()
2392
+ })
2393
+ // Never kept, never indexed, never the same as Shared's.
2394
+ const headers = new Headers(response.headers)
2395
+ headers.set('cache-control', PRIVATE_NO_STORE)
2396
+ headers.set('x-robots-tag', 'noindex, nofollow')
2397
+ headers.delete('etag')
2398
+ headers.delete('last-modified')
2399
+ return new Response(response.body, {
2400
+ status: response.status,
2401
+ statusText: response.statusText,
2402
+ headers,
2403
+ })
2404
+ }
2405
+
2406
+ /** Removes each file nothing in the site names any more: not a media item, a page, or a workspace. */
2407
+ async function removeUnnamedFiles(urls: readonly string[]): Promise<void> {
2408
+ for (const url of urls) {
2409
+ const named = await db.q
2410
+ .selectFrom('property_value')
2411
+ .select('id')
2412
+ .where((eb) =>
2413
+ eb.or([eb('varchar_value', 'like', `%${url}%`), eb('text_value', 'like', `%${url}%`)]),
2414
+ )
2415
+ .limit(1)
2416
+ .execute()
2417
+ const owned = await new MediaAccessRepository(db).byUrl([url])
2418
+ if (named.length === 0 && !owned) await mediaFiles.remove(url)
2419
+ }
2420
+ }
2421
+
2422
+ /** Whether a workspace's own values name a file (story 390). */
2423
+ async function heldByWorkspace(workspaceId: number, urls: readonly string[]): Promise<boolean> {
2424
+ for (const url of urls) {
2425
+ const rows = await db.q
2426
+ .selectFrom('property_value')
2427
+ .select('id')
2428
+ .where('workspace_id', '=', workspaceId)
2429
+ .where((eb) =>
2430
+ eb.or([eb('varchar_value', 'like', `%${url}%`), eb('text_value', 'like', `%${url}%`)]),
2431
+ )
2432
+ .limit(1)
2433
+ .execute()
2434
+ if (rows.length > 0) return true
2435
+ }
2436
+ return false
2437
+ }
2438
+
1949
2439
  /** Story 368: a preview link for a page its person may read, audited as them. */
1950
2440
  async function askForPreviewLink(request: Request): Promise<Response> {
1951
2441
  if (request.method !== 'POST') return new Response(null, { status: 405 })
@@ -1954,6 +2444,7 @@ export async function createServer(
1954
2444
  const asked = (await request.json().catch(() => ({}))) as {
1955
2445
  document?: unknown
1956
2446
  culture?: unknown
2447
+ workspace?: unknown
1957
2448
  }
1958
2449
  const document = typeof asked.document === 'string' ? asked.document : ''
1959
2450
  const culture = typeof asked.culture === 'string' && asked.culture ? asked.culture : null
@@ -1963,6 +2454,20 @@ export async function createServer(
1963
2454
  if (!standing || !(await canReadDocument(principal, document, nodeLookup)))
1964
2455
  return Response.json({ title: 'You may not read this page' }, { status: 403 })
1965
2456
  const key = normaliseUuid(document)
2457
+ // Story 379: a page in a workspace is looked at on the workspace's site.
2458
+ if (typeof asked.workspace === 'string' && UUID_PATTERN.test(asked.workspace)) {
2459
+ const workspace = await new WorkspaceRepository(db).byKey(asked.workspace)
2460
+ const me = normaliseUuid(principal.id)
2461
+ if (!workspace || (workspace.ownerKey !== me && !workspace.memberKeys.includes(me)))
2462
+ return Response.json({ title: 'There is no such workspace' }, { status: 404 })
2463
+ const shown = await cache.byKey(key, culture)
2464
+ const url = await workspaceOpenUrl(workspace, principal, shown?.url ?? '/', request)
2465
+ if (!url) return Response.json({ title: 'You may not read this page' }, { status: 403 })
2466
+ return Response.json(
2467
+ { url, expiresAt: new Date(Date.now() + WORKSPACE_HANDOFF_SECONDS * 1000).toISOString() },
2468
+ { headers: { 'cache-control': PRIVATE_NO_STORE } },
2469
+ )
2470
+ }
1966
2471
  const page = await (await draftCache()).byKey(key, culture)
1967
2472
  const published = await cache.byKey(key, culture)
1968
2473
  const expires = Date.now() + PREVIEW_LINK_SECONDS * 1000
@@ -2386,9 +2891,9 @@ export async function createServer(
2386
2891
  if (pathname === `${paths.pluginPath}/api/schema-import`) {
2387
2892
  const principal = await authenticate(request)
2388
2893
  if (!principal) return new Response('Unauthorized', { status: 401 })
2389
- // Settings: this applies type changes to the database, which is what every
2390
- // `document-type` write requires.
2391
- if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2894
+ // Structure: this applies type changes to the database, which is what every
2895
+ // `document-type` write requires (story 385).
2896
+ if (!hasSection(principal, 'structure')) return new Response('Forbidden', { status: 403 })
2392
2897
  if (request.method !== 'GET' && request.method !== 'POST') {
2393
2898
  return new Response('Method Not Allowed', { status: 405 })
2394
2899
  }
@@ -2748,6 +3253,7 @@ export async function createServer(
2748
3253
  nodeId: schema.nodeId,
2749
3254
  url: config.applicationUrl || undefined,
2750
3255
  },
3256
+ ...(await hostIdentityOf(principal.id)),
2751
3257
  })
2752
3258
  log.info('Issued a host token to {user} for {host}', {
2753
3259
  user: principal.email,
@@ -2847,6 +3353,51 @@ export async function createServer(
2847
3353
  )
2848
3354
  }
2849
3355
 
3356
+ // Story 375: workspaces, opened, listed, shared and discarded.
3357
+ if (pathname === workspacesPath || pathname.startsWith(`${workspacesPath}/`)) {
3358
+ const principal = await authenticate(request)
3359
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3360
+ return workspacesApi.handle(
3361
+ request,
3362
+ principal,
3363
+ pathname.slice(workspacesPath.length),
3364
+ clientAddress(request),
3365
+ )
3366
+ }
3367
+
3368
+ // Story 381: the site's changes, their files' versions, and reverting one.
3369
+ if (pathname === changesPath || pathname.startsWith(`${changesPath}/`)) {
3370
+ const principal = await authenticate(request)
3371
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3372
+ if (!hasSection(principal, 'content'))
3373
+ return Response.json(
3374
+ { message: 'Changes are for people who look after content.' },
3375
+ { status: 403 },
3376
+ )
3377
+ return changesApi.handle(
3378
+ request,
3379
+ principal,
3380
+ pathname.slice(changesPath.length),
3381
+ clientAddress(request),
3382
+ )
3383
+ }
3384
+
3385
+ // Story 387: a property's value per environment, edited beside its field.
3386
+ if (pathname === environmentValuesPath || pathname.startsWith(`${environmentValuesPath}/`)) {
3387
+ const principal = await authenticate(request)
3388
+ if (!principal) return new Response('Unauthorized', { status: 401 })
3389
+ if (!hasSection(principal, 'content'))
3390
+ return Response.json(
3391
+ { message: 'Values per environment are for people who look after content.' },
3392
+ { status: 403 },
3393
+ )
3394
+ return environmentValuesApi.handle(
3395
+ request,
3396
+ principal,
3397
+ pathname.slice(environmentValuesPath.length),
3398
+ )
3399
+ }
3400
+
2850
3401
  // Story 368: a link that opens one page's draft in any browser.
2851
3402
  if (pathname === previewLinkPath) return askForPreviewLink(request)
2852
3403
 
@@ -2942,373 +3493,396 @@ export async function createServer(
2942
3493
  const principal = await authenticate(request)
2943
3494
  if (!principal) return new Response('Unauthorized', { status: 401 })
2944
3495
  const action = pathname.slice(`${paths.pluginPath}/api/forms`.length).replace(/^\//, '')
2945
- // Through the registry the renderer uses, so the designer and a render
2946
- // cannot disagree; a save invalidates it rather than waiting out the memo.
2947
- const definitions = forms.all()
2948
-
2949
- // A definition is structure, like a content type: anyone who may open the
2950
- // section may read it, and the picker needs it in the Content section too.
2951
- if (action === '' && request.method === 'GET') {
2952
- const files = loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files
2953
- const file = (alias: string) => files.get(`form:${alias}`)
2954
- return Response.json({
2955
- items: definitions.map((form) => ({
2956
- ...formSummary(form, formTypes.types),
2957
- folder: file(form.alias)
2958
- ? folderOf(config.schemaDir, 'forms', file(form.alias) as string)
2959
- : '',
2960
- })),
2961
- folders: foldersIn(config.schemaDir, 'forms'),
2962
- readOnlyBecause: !config.schemaWritable
2963
- ? 'site'
2964
- : principal.isAdmin || principal.permissions.includes(FormPermissions.Manage)
2965
- ? null
2966
- : 'permission',
2967
- })
2968
- }
2969
- // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
2970
- if (action === 'available-types' && request.method === 'GET')
2971
- return Response.json(describeFormTypes(formTypes.types))
2972
- // The Library forms (story 239), for a page's form picker and the entries filter.
2973
- if (action === 'library-forms' && request.method === 'GET') {
2974
- const known = new Map(definitions.map((form) => [form.key ?? form.alias, form]))
2975
- return Response.json({
2976
- items: (await listLibraryForms(db)).map((item) => ({
2977
- ...item,
2978
- formAlias: known.get(item.formKey)?.alias ?? null,
2979
- formName: known.get(item.formKey)?.name ?? null,
2980
- })),
2981
- })
3496
+ // Story 392: in a workspace, its copy of the forms; looking up choices is a read.
3497
+ // Story 392: a site that takes its content by change shows its forms read-only.
3498
+ const shared = {
3499
+ schemaDir: config.schemaDir,
3500
+ writable: config.schemaWritable && !contentLocked(config),
2982
3501
  }
2983
- // Which content types are made from a form, for the note in their editor.
2984
- if (action === 'library-types' && request.method === 'GET')
2985
- return Response.json({
2986
- items: definitions.map((form) => ({
2987
- typeKey: libraryFormTypeKey(libraryFormId(form)),
2988
- formName: form.name,
2989
- })),
2990
- })
2991
- // The designer's "E-mail design" picker.
2992
- if (action === 'email-templates' && request.method === 'GET')
2993
- return Response.json({
2994
- items: listEmailTemplates(
2995
- config.componentsDir,
2996
- definitions.flatMap((form) =>
2997
- form.workflows.flatMap((workflow) =>
2998
- typeof workflow.settings.template === 'string' ? [workflow.settings.template] : [],
3502
+ const formsIn = async (place: SchemaPlace): Promise<Response> => {
3503
+ // Through the registry the renderer uses, so the designer and a render
3504
+ // cannot disagree; a save invalidates it rather than waiting out the memo.
3505
+ const definitions = place.inWorkspace
3506
+ ? (loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).set.forms ?? [])
3507
+ : forms.all()
3508
+
3509
+ // A definition is structure, like a content type: anyone who may open the
3510
+ // section may read it, and the picker needs it in the Content section too.
3511
+ if (action === '' && request.method === 'GET') {
3512
+ const files = loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).files
3513
+ const file = (alias: string) => files.get(`form:${alias}`)
3514
+ return Response.json({
3515
+ items: definitions.map((form) => ({
3516
+ ...formSummary(form, formTypes.types),
3517
+ folder: file(form.alias)
3518
+ ? folderOf(place.schemaDir, 'forms', file(form.alias) as string)
3519
+ : '',
3520
+ })),
3521
+ folders: foldersIn(place.schemaDir, 'forms'),
3522
+ readOnlyBecause: !place.writable
3523
+ ? 'site'
3524
+ : principal.isAdmin || principal.permissions.includes(FormPermissions.Manage)
3525
+ ? null
3526
+ : 'permission',
3527
+ })
3528
+ }
3529
+ // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
3530
+ if (action === 'available-types' && request.method === 'GET')
3531
+ return Response.json(describeFormTypes(formTypes.types))
3532
+ // The Library forms (story 239), for a page's form picker and the entries filter.
3533
+ if (action === 'library-forms' && request.method === 'GET') {
3534
+ const known = new Map(definitions.map((form) => [form.key ?? form.alias, form]))
3535
+ return Response.json({
3536
+ items: (await listLibraryForms(db)).map((item) => ({
3537
+ ...item,
3538
+ formAlias: known.get(item.formKey)?.alias ?? null,
3539
+ formName: known.get(item.formKey)?.name ?? null,
3540
+ })),
3541
+ })
3542
+ }
3543
+ // Which content types are made from a form, for the note in their editor.
3544
+ if (action === 'library-types' && request.method === 'GET')
3545
+ return Response.json({
3546
+ items: definitions.map((form) => ({
3547
+ typeKey: libraryFormTypeKey(libraryFormId(form)),
3548
+ formName: form.name,
3549
+ })),
3550
+ })
3551
+ // The designer's "E-mail design" picker.
3552
+ if (action === 'email-templates' && request.method === 'GET')
3553
+ return Response.json({
3554
+ items: listEmailTemplates(
3555
+ config.componentsDir,
3556
+ definitions.flatMap((form) =>
3557
+ form.workflows.flatMap((workflow) =>
3558
+ typeof workflow.settings.template === 'string'
3559
+ ? [workflow.settings.template]
3560
+ : [],
3561
+ ),
2999
3562
  ),
3000
3563
  ),
3001
- ),
3002
- })
3564
+ })
3003
3565
 
3004
- const entries = new FormEntryRepository(db)
3005
- const byKey = formsByKey(definitions)
3006
- // Submissions are personal data, so reading them asks for more than a
3007
- // session. Four verbs, because designing a form and reading what people
3008
- // sent it are different jobs (`docs/forms.md`).
3009
- const may = (verb: string) => principal.isAdmin || principal.permissions.includes(verb)
3010
- const formFiles = {
3011
- schemaDir: config.schemaDir,
3012
- writable: config.schemaWritable,
3013
- formTypes: formTypes.types,
3014
- componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
3015
- onChanged: config.schemaStore
3016
- ? async () => {
3017
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
3018
- }
3019
- : undefined,
3020
- }
3021
- // Every dictionary item in the default language, for the designer to suggest.
3022
- if (action === 'words' && request.method === 'GET') {
3023
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3024
- const entries = await cache.dictionaryEntries(null)
3025
- return Response.json({
3026
- words: Object.entries(entries).map(([name, text]) => ({ name, text })),
3027
- })
3028
- }
3566
+ const entries = new FormEntryRepository(db)
3567
+ const byKey = formsByKey(definitions)
3568
+ // Submissions are personal data, so reading them asks for more than a
3569
+ // session. Four verbs, because designing a form and reading what people
3570
+ // sent it are different jobs (`docs/forms.md`).
3571
+ const may = (verb: string) => principal.isAdmin || principal.permissions.includes(verb)
3572
+ const formFiles = {
3573
+ schemaDir: place.schemaDir,
3574
+ writable: place.writable,
3575
+ formTypes: formTypes.types,
3576
+ componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
3577
+ onChanged:
3578
+ !place.inWorkspace && config.schemaStore
3579
+ ? async () => {
3580
+ await publishSchema(config.schemaStore as SchemaStore, place.schemaDir)
3581
+ }
3582
+ : undefined,
3583
+ }
3584
+ // Every dictionary item in the default language, for the designer to suggest.
3585
+ if (action === 'words' && request.method === 'GET') {
3586
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3587
+ const entries = await cache.dictionaryEntries(null)
3588
+ return Response.json({
3589
+ words: Object.entries(entries).map(([name, text]) => ({ name, text })),
3590
+ })
3591
+ }
3029
3592
 
3030
- const maySeeEntries = may(FormPermissions.EntriesView)
3031
- const mayManageEntries = may(FormPermissions.EntriesManage)
3032
- // The group alias still counts: `sensitiveData` is how Umbraco carries
3033
- // this and how members already work, so both routes to it are honoured.
3034
- const maySeeSensitive =
3035
- may(FormPermissions.EntriesSensitive) || hasAccessToSensitiveData(principal.groups)
3036
-
3037
- const entryMatch = /^entries\/([^/]+)(?:\/(state))?$/.exec(action)
3038
- if (entryMatch) {
3039
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3040
- const id = decodeURIComponent(entryMatch[1] as string)
3041
- if (entryMatch[2] === 'state' && request.method === 'POST') {
3042
- if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3043
- const body = (await request.json().catch(() => ({}))) as { state?: unknown }
3044
- const next = parseEntryState(typeof body.state === 'string' ? body.state : null)
3045
- if (!next) return new Response('Bad Request', { status: 400 })
3046
- const updated = await entries.setState(id, next)
3047
- if (!updated) return new Response('Not Found', { status: 404 })
3048
- // Approval is the other trigger: a workflow declared `on = "approve"`
3049
- // runs now, from the values the entry holds.
3050
- if (next === 'approved') {
3051
- const form = byKey.get(updated.formKey)
3052
- const onApprove = form?.workflows.filter((workflow) => workflow.on === 'approve') ?? []
3053
- // Through a Library form: its recipients as they are now (story 239).
3054
- const recipients = updated.libraryKey
3055
- ? (await cache.libraryForm(updated.libraryKey))?.library?.recipients
3056
- : undefined
3057
- if (onApprove.length > 0)
3058
- await new FormWorkflowRepository(db).enqueue(
3059
- onApprove.map((workflow) => ({
3060
- formKey: updated.formKey,
3061
- formAlias: updated.formAlias,
3062
- workflowName: workflow.name,
3063
- workflowType: workflow.type,
3064
- runOn: workflow.on,
3065
- entryId: updated.id,
3066
- payload: updated.values.map((value) => ({
3067
- fieldAlias: value.fieldAlias,
3068
- values: value.values,
3593
+ const maySeeEntries = may(FormPermissions.EntriesView)
3594
+ const mayManageEntries = may(FormPermissions.EntriesManage)
3595
+ // The group alias still counts: `sensitiveData` is how Umbraco carries
3596
+ // this and how members already work, so both routes to it are honoured.
3597
+ const maySeeSensitive =
3598
+ may(FormPermissions.EntriesSensitive) || hasAccessToSensitiveData(principal.groups)
3599
+
3600
+ const entryMatch = /^entries\/([^/]+)(?:\/(state))?$/.exec(action)
3601
+ if (entryMatch) {
3602
+ if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3603
+ const id = decodeURIComponent(entryMatch[1] as string)
3604
+ if (entryMatch[2] === 'state' && request.method === 'POST') {
3605
+ if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3606
+ const body = (await request.json().catch(() => ({}))) as { state?: unknown }
3607
+ const next = parseEntryState(typeof body.state === 'string' ? body.state : null)
3608
+ if (!next) return new Response('Bad Request', { status: 400 })
3609
+ const updated = await entries.setState(id, next)
3610
+ if (!updated) return new Response('Not Found', { status: 404 })
3611
+ // Approval is the other trigger: a workflow declared `on = "approve"`
3612
+ // runs now, from the values the entry holds.
3613
+ if (next === 'approved') {
3614
+ const form = byKey.get(updated.formKey)
3615
+ const onApprove =
3616
+ form?.workflows.filter((workflow) => workflow.on === 'approve') ?? []
3617
+ // Through a Library form: its recipients as they are now (story 239).
3618
+ const recipients = updated.libraryKey
3619
+ ? (await cache.libraryForm(updated.libraryKey))?.library?.recipients
3620
+ : undefined
3621
+ if (onApprove.length > 0)
3622
+ await new FormWorkflowRepository(db).enqueue(
3623
+ onApprove.map((workflow) => ({
3624
+ formKey: updated.formKey,
3625
+ formAlias: updated.formAlias,
3626
+ workflowName: workflow.name,
3627
+ workflowType: workflow.type,
3628
+ runOn: workflow.on,
3629
+ entryId: updated.id,
3630
+ payload: updated.values.map((value) => ({
3631
+ fieldAlias: value.fieldAlias,
3632
+ values: value.values,
3633
+ })),
3634
+ ...(recipients ? { recipients } : {}),
3069
3635
  })),
3070
- ...(recipients ? { recipients } : {}),
3071
- })),
3072
- )
3636
+ )
3637
+ }
3638
+ log.info('{user} set form entry {id} to {state}', {
3639
+ user: principal.email,
3640
+ id,
3641
+ state: next,
3642
+ })
3643
+ return Response.json({ id: updated.id, state: updated.state })
3073
3644
  }
3074
- log.info('{user} set form entry {id} to {state}', {
3075
- user: principal.email,
3076
- id,
3077
- state: next,
3078
- })
3079
- return Response.json({ id: updated.id, state: updated.state })
3645
+ if (request.method === 'DELETE') {
3646
+ if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3647
+ if (!(await entries.remove(id))) return new Response('Not Found', { status: 404 })
3648
+ log.info('{user} deleted form entry {id}', { user: principal.email, id })
3649
+ return new Response(null, { status: 200 })
3650
+ }
3651
+ if (request.method === 'GET') {
3652
+ const entry = await entries.byId(id)
3653
+ if (!entry) return new Response('Not Found', { status: 404 })
3654
+ return Response.json({
3655
+ ...entry,
3656
+ values: redactSensitive(entry, byKey.get(entry.formKey), maySeeSensitive),
3657
+ })
3658
+ }
3659
+ return new Response('Method Not Allowed', { status: 405 })
3080
3660
  }
3081
- if (request.method === 'DELETE') {
3082
- if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3083
- if (!(await entries.remove(id))) return new Response('Not Found', { status: 404 })
3084
- log.info('{user} deleted form entry {id}', { user: principal.email, id })
3085
- return new Response(null, { status: 200 })
3661
+
3662
+ const csvMatch = /^([^/]+)\/entries\.csv$/.exec(action)
3663
+ if (csvMatch && request.method === 'GET') {
3664
+ if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3665
+ const key = decodeURIComponent(csvMatch[1] as string)
3666
+ const form = byKey.get(key)
3667
+ if (!form) return new Response('Not Found', { status: 404 })
3668
+ const page = await entries.list({ formKey: key, take: 10_000 })
3669
+ const result = entriesCsv(await cache.resolveForm(form), page.items, {
3670
+ includeSensitive: maySeeSensitive,
3671
+ types: formTypes.types,
3672
+ })
3673
+ if (!result.ok)
3674
+ return new Response(result.reason, {
3675
+ status: 403,
3676
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
3677
+ })
3678
+ return new Response(result.csv, {
3679
+ headers: {
3680
+ 'content-type': 'text/csv; charset=utf-8',
3681
+ 'content-disposition': `attachment; filename="${result.fileName}"`,
3682
+ },
3683
+ })
3086
3684
  }
3087
- if (request.method === 'GET') {
3088
- const entry = await entries.byId(id)
3089
- if (!entry) return new Response('Not Found', { status: 404 })
3685
+
3686
+ const listMatch = /^([^/]+)\/entries$/.exec(action)
3687
+ if (listMatch && request.method === 'GET') {
3688
+ if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3689
+ const key = decodeURIComponent(listMatch[1] as string)
3690
+ const since = url.searchParams.get('from')
3691
+ const until = url.searchParams.get('to')
3692
+ // `library=none` for the entries that came through no Library form.
3693
+ const library = url.searchParams.get('library')
3694
+ const page = await entries.list({
3695
+ formKey: key,
3696
+ ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
3697
+ state: parseEntryState(url.searchParams.get('state')),
3698
+ culture: url.searchParams.get('language') || undefined,
3699
+ from: since ? new Date(since) : undefined,
3700
+ to: until ? new Date(until) : undefined,
3701
+ search: url.searchParams.get('search') ?? undefined,
3702
+ includeSpam: url.searchParams.get('includeSpam') === 'true',
3703
+ skip: Number(url.searchParams.get('skip') ?? 0) || 0,
3704
+ take: Number(url.searchParams.get('take') ?? 100) || 100,
3705
+ })
3706
+ const form = byKey.get(key)
3090
3707
  return Response.json({
3091
- ...entry,
3092
- values: redactSensitive(entry, byKey.get(entry.formKey), maySeeSensitive),
3708
+ total: page.total,
3709
+ languages: await entries.languages(key),
3710
+ items: page.items.map((entry) => ({
3711
+ ...entry,
3712
+ values: redactSensitive(entry, form, maySeeSensitive),
3713
+ })),
3093
3714
  })
3094
3715
  }
3095
- return new Response('Method Not Allowed', { status: 405 })
3096
- }
3097
3716
 
3098
- const csvMatch = /^([^/]+)\/entries\.csv$/.exec(action)
3099
- if (csvMatch && request.method === 'GET') {
3100
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3101
- const key = decodeURIComponent(csvMatch[1] as string)
3102
- const form = byKey.get(key)
3103
- if (!form) return new Response('Not Found', { status: 404 })
3104
- const page = await entries.list({ formKey: key, take: 10_000 })
3105
- const result = entriesCsv(await cache.resolveForm(form), page.items, {
3106
- includeSensitive: maySeeSensitive,
3107
- types: formTypes.types,
3108
- })
3109
- if (!result.ok)
3110
- return new Response(result.reason, {
3111
- status: 403,
3112
- headers: { 'content-type': 'text/plain; charset=utf-8' },
3717
+ // A send-to-URL workflow's secret header (story 304): sealed here, never
3718
+ // in the form's file, and never shown back. Set on any site, schema
3719
+ // writable or not, since it is the site's own and not the form's.
3720
+ const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
3721
+ if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
3722
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3723
+ const [, formKey, workflowKey, header] = secretMatch.map((part) =>
3724
+ decodeURIComponent(part),
3725
+ ) as [string, string, string, string]
3726
+ const form = byKey.get(formKey)
3727
+ const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
3728
+ const headers = workflow?.settings.headers as Record<string, unknown> | undefined
3729
+ if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
3730
+ return Response.json(
3731
+ { message: 'The form names no such secret header; save the form first.' },
3732
+ { status: 404 },
3733
+ )
3734
+ const secrets = new FormWorkflowSecretRepository(db)
3735
+ let set: { sealed: string; url: string } | undefined
3736
+ if (request.method === 'PUT') {
3737
+ const body = (await request.json().catch(() => ({}))) as { value?: unknown }
3738
+ if (typeof body.value !== 'string' || body.value === '')
3739
+ return Response.json({ message: 'Give the header a value.' }, { status: 400 })
3740
+ const key = usableSecretKey(config.secretKey)
3741
+ if (!key)
3742
+ return Response.json(
3743
+ {
3744
+ message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
3745
+ },
3746
+ { status: 409 },
3747
+ )
3748
+ set = { sealed: sealSecret(body.value, key), url: String(workflow.settings.url ?? '') }
3749
+ }
3750
+ await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
3751
+ await recordAudit(db, {
3752
+ category: 'settings',
3753
+ action: set ? 'secret header set' : 'secret header removed',
3754
+ source: 'request',
3755
+ userKey: principal.id,
3756
+ userName: principal.name,
3757
+ entityType: 'form',
3758
+ entityKey: form.key,
3759
+ entityName: form.name,
3760
+ detail: `${workflow.name}: ${header}`,
3761
+ ...clientAddress(request),
3113
3762
  })
3114
- return new Response(result.csv, {
3115
- headers: {
3116
- 'content-type': 'text/csv; charset=utf-8',
3117
- 'content-disposition': `attachment; filename="${result.fileName}"`,
3118
- },
3119
- })
3120
- }
3763
+ return Response.json({ ok: true })
3764
+ }
3121
3765
 
3122
- const listMatch = /^([^/]+)\/entries$/.exec(action)
3123
- if (listMatch && request.method === 'GET') {
3124
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3125
- const key = decodeURIComponent(listMatch[1] as string)
3126
- const since = url.searchParams.get('from')
3127
- const until = url.searchParams.get('to')
3128
- // `library=none` for the entries that came through no Library form.
3129
- const library = url.searchParams.get('library')
3130
- const page = await entries.list({
3131
- formKey: key,
3132
- ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
3133
- state: parseEntryState(url.searchParams.get('state')),
3134
- culture: url.searchParams.get('language') || undefined,
3135
- from: since ? new Date(since) : undefined,
3136
- to: until ? new Date(until) : undefined,
3137
- search: url.searchParams.get('search') ?? undefined,
3138
- includeSpam: url.searchParams.get('includeSpam') === 'true',
3139
- skip: Number(url.searchParams.get('skip') ?? 0) || 0,
3140
- take: Number(url.searchParams.get('take') ?? 100) || 100,
3141
- })
3142
- const form = byKey.get(key)
3143
- return Response.json({
3144
- total: page.total,
3145
- languages: await entries.languages(key),
3146
- items: page.items.map((entry) => ({
3147
- ...entry,
3148
- values: redactSensitive(entry, form, maySeeSensitive),
3149
- })),
3150
- })
3151
- }
3766
+ if (action && request.method === 'GET') {
3767
+ const form = byKey.get(decodeURIComponent(action))
3768
+ if (!form) return new Response('Not Found', { status: 404 })
3769
+ // Which secret headers are set for the address each workflow sends to, never their values.
3770
+ const secrets: { workflow: string; header: string; set: boolean }[] = []
3771
+ for (const workflow of form.workflows) {
3772
+ const headers = workflow.settings.headers as Record<string, unknown> | undefined
3773
+ const named = Object.keys(headers ?? {}).filter((name) =>
3774
+ isSecretHeader(headers?.[name]),
3775
+ )
3776
+ if (named.length === 0 || !workflow.key || !form.key) continue
3777
+ const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
3778
+ for (const header of named)
3779
+ secrets.push({
3780
+ workflow: workflow.key,
3781
+ header,
3782
+ set: kept.get(header)?.url === workflow.settings.url,
3783
+ })
3784
+ }
3785
+ // The whole definition, which is what the designer edits.
3786
+ return Response.json({ ...formDetail(form), definition: form, secrets })
3787
+ }
3152
3788
 
3153
- // A send-to-URL workflow's secret header (story 304): sealed here, never
3154
- // in the form's file, and never shown back. Set on any site, schema
3155
- // writable or not, since it is the site's own and not the form's.
3156
- const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
3157
- if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
3158
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3159
- const [, formKey, workflowKey, header] = secretMatch.map((part) =>
3160
- decodeURIComponent(part),
3161
- ) as [string, string, string, string]
3162
- const form = byKey.get(formKey)
3163
- const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
3164
- const headers = workflow?.settings.headers as Record<string, unknown> | undefined
3165
- if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
3166
- return Response.json(
3167
- { message: 'The form names no such secret header; save the form first.' },
3168
- { status: 404 },
3789
+ // What a choice source offers now, in the default language, for the
3790
+ // designer to show beside the source it is editing.
3791
+ if (action === 'choices' && request.method === 'POST') {
3792
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3793
+ const body = (await request.json().catch(() => ({}))) as { source?: unknown }
3794
+ const source = body.source as { kind?: unknown; parent?: unknown } | undefined
3795
+ if (
3796
+ !source ||
3797
+ !CHOICE_SOURCE_KINDS.includes(source.kind as ChoiceSourceKind) ||
3798
+ typeof source.parent !== 'string'
3169
3799
  )
3170
- const secrets = new FormWorkflowSecretRepository(db)
3171
- let set: { sealed: string; url: string } | undefined
3172
- if (request.method === 'PUT') {
3173
- const body = (await request.json().catch(() => ({}))) as { value?: unknown }
3174
- if (typeof body.value !== 'string' || body.value === '')
3175
- return Response.json({ message: 'Give the header a value.' }, { status: 400 })
3176
- const key = usableSecretKey(config.secretKey)
3177
- if (!key)
3178
- return Response.json(
3179
- {
3180
- message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
3181
- },
3182
- { status: 409 },
3183
- )
3184
- set = { sealed: sealSecret(body.value, key), url: String(workflow.settings.url ?? '') }
3800
+ return new Response('Bad Request', { status: 400 })
3801
+ const options = await cache.choiceOptions({
3802
+ kind: source.kind as ChoiceSourceKind,
3803
+ parent: source.parent,
3804
+ })
3805
+ return Response.json({ options })
3185
3806
  }
3186
- await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
3187
- await recordAudit(db, {
3188
- category: 'settings',
3189
- action: set ? 'secret header set' : 'secret header removed',
3190
- source: 'request',
3191
- userKey: principal.id,
3192
- userName: principal.name,
3193
- entityType: 'form',
3194
- entityKey: form.key,
3195
- entityName: form.name,
3196
- detail: `${workflow.name}: ${header}`,
3197
- ...clientAddress(request),
3198
- })
3199
- return Response.json({ ok: true })
3200
- }
3201
3807
 
3202
- if (action && request.method === 'GET') {
3203
- const form = byKey.get(decodeURIComponent(action))
3204
- if (!form) return new Response('Not Found', { status: 404 })
3205
- // Which secret headers are set for the address each workflow sends to, never their values.
3206
- const secrets: { workflow: string; header: string; set: boolean }[] = []
3207
- for (const workflow of form.workflows) {
3208
- const headers = workflow.settings.headers as Record<string, unknown> | undefined
3209
- const named = Object.keys(headers ?? {}).filter((name) => isSecretHeader(headers?.[name]))
3210
- if (named.length === 0 || !workflow.key || !form.key) continue
3211
- const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
3212
- for (const header of named)
3213
- secrets.push({
3214
- workflow: workflow.key,
3215
- header,
3216
- set: kept.get(header)?.url === workflow.settings.url,
3808
+ // Designing a form is a developer's job, so it is its own verb rather
3809
+ // than something an entry reader can do.
3810
+ if (action === 'tree-folders' || action === 'tree-move') {
3811
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3812
+ const response = await folderAction('forms', action, request, {
3813
+ ...formFiles,
3814
+ file: (alias) =>
3815
+ loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).files.get(
3816
+ `form:${alias}`,
3817
+ ),
3818
+ })
3819
+ if (response) return response
3820
+ }
3821
+ if (request.method === 'POST' || request.method === 'PUT') {
3822
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3823
+ const body = await request.json().catch(() => ({}))
3824
+ const folder = url.searchParams.get('folder') ?? undefined
3825
+ const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
3826
+ if (refused.length > 0)
3827
+ return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
3828
+ const written = await saveForm(coerceForm(body), { ...formFiles, folder })
3829
+ if (!written.ok) {
3830
+ log.warning('{user} could not save a form: {detail}', {
3831
+ user: principal.email,
3832
+ detail: written.problems.map((problem) => problem.message).join('; '),
3217
3833
  })
3834
+ return Response.json(
3835
+ { status: written.status, problems: written.problems },
3836
+ { status: written.status === 'readOnly' ? 409 : 400 },
3837
+ )
3838
+ }
3839
+ // The memo would otherwise hold the old definition for a second, which
3840
+ // is exactly long enough for the designer to reload and see it.
3841
+ if (!place.inWorkspace) {
3842
+ forms.invalidate()
3843
+ await ensureFormLibraryTypes(db, forms.all())
3844
+ cache.invalidate()
3845
+ }
3846
+ const saved = coerceForm(body)
3847
+ if (saved.key && !place.inWorkspace)
3848
+ await new FormWorkflowSecretRepository(db).forget(
3849
+ saved.key,
3850
+ saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
3851
+ )
3852
+ log.info('{user} saved the form {form}', {
3853
+ user: principal.email,
3854
+ form: coerceForm(body).alias,
3855
+ })
3856
+ return Response.json({ ok: true })
3218
3857
  }
3219
- // The whole definition, which is what the designer edits.
3220
- return Response.json({ ...formDetail(form), definition: form, secrets })
3221
- }
3222
3858
 
3223
- // What a choice source offers now, in the default language, for the
3224
- // designer to show beside the source it is editing.
3225
- if (action === 'choices' && request.method === 'POST') {
3226
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3227
- const body = (await request.json().catch(() => ({}))) as { source?: unknown }
3228
- const source = body.source as { kind?: unknown; parent?: unknown } | undefined
3229
- if (
3230
- !source ||
3231
- !CHOICE_SOURCE_KINDS.includes(source.kind as ChoiceSourceKind) ||
3232
- typeof source.parent !== 'string'
3233
- )
3234
- return new Response('Bad Request', { status: 400 })
3235
- const options = await cache.choiceOptions({
3236
- kind: source.kind as ChoiceSourceKind,
3237
- parent: source.parent,
3238
- })
3239
- return Response.json({ options })
3240
- }
3241
-
3242
- // Designing a form is a developer's job, so it is its own verb rather
3243
- // than something an entry reader can do.
3244
- if (action === 'tree-folders' || action === 'tree-move') {
3245
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3246
- const response = await folderAction('forms', action, request, {
3247
- ...formFiles,
3248
- file: (alias) =>
3249
- loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files.get(
3250
- `form:${alias}`,
3251
- ),
3252
- })
3253
- if (response) return response
3254
- }
3255
- if (request.method === 'POST' || request.method === 'PUT') {
3256
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3257
- const body = await request.json().catch(() => ({}))
3258
- const folder = url.searchParams.get('folder') ?? undefined
3259
- const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
3260
- if (refused.length > 0)
3261
- return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
3262
- const written = await saveForm(coerceForm(body), { ...formFiles, folder })
3263
- if (!written.ok) {
3264
- log.warning('{user} could not save a form: {detail}', {
3859
+ if (action && request.method === 'DELETE') {
3860
+ if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3861
+ const form = byKey.get(decodeURIComponent(action))
3862
+ if (!form) return new Response('Not Found', { status: 404 })
3863
+ const removed = await deleteForm(form.alias, formFiles)
3864
+ if (!removed.ok)
3865
+ return Response.json(
3866
+ { status: removed.status, problems: removed.problems },
3867
+ { status: removed.status === 'readOnly' ? 409 : 404 },
3868
+ )
3869
+ if (!place.inWorkspace) {
3870
+ forms.invalidate()
3871
+ await ensureFormLibraryTypes(db, forms.all())
3872
+ cache.invalidate()
3873
+ }
3874
+ if (form.key && !place.inWorkspace)
3875
+ await new FormWorkflowSecretRepository(db).forget(form.key)
3876
+ log.info('{user} deleted the form {form}; its entries are kept', {
3265
3877
  user: principal.email,
3266
- detail: written.problems.map((problem) => problem.message).join('; '),
3878
+ form: form.alias,
3267
3879
  })
3268
- return Response.json(
3269
- { status: written.status, problems: written.problems },
3270
- { status: written.status === 'readOnly' ? 409 : 400 },
3271
- )
3880
+ return Response.json({ ok: true })
3272
3881
  }
3273
- // The memo would otherwise hold the old definition for a second, which
3274
- // is exactly long enough for the designer to reload and see it.
3275
- forms.invalidate()
3276
- await ensureFormLibraryTypes(db, forms.all())
3277
- cache.invalidate()
3278
- const saved = coerceForm(body)
3279
- if (saved.key)
3280
- await new FormWorkflowSecretRepository(db).forget(
3281
- saved.key,
3282
- saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
3283
- )
3284
- log.info('{user} saved the form {form}', {
3285
- user: principal.email,
3286
- form: coerceForm(body).alias,
3287
- })
3288
- return Response.json({ ok: true })
3289
- }
3290
-
3291
- if (action && request.method === 'DELETE') {
3292
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3293
- const form = byKey.get(decodeURIComponent(action))
3294
- if (!form) return new Response('Not Found', { status: 404 })
3295
- const removed = await deleteForm(form.alias, formFiles)
3296
- if (!removed.ok)
3297
- return Response.json(
3298
- { status: removed.status, problems: removed.problems },
3299
- { status: removed.status === 'readOnly' ? 409 : 404 },
3300
- )
3301
- forms.invalidate()
3302
- await ensureFormLibraryTypes(db, forms.all())
3303
- cache.invalidate()
3304
- if (form.key) await new FormWorkflowSecretRepository(db).forget(form.key)
3305
- log.info('{user} deleted the form {form}; its entries are kept', {
3306
- user: principal.email,
3307
- form: form.alias,
3308
- })
3309
- return Response.json({ ok: true })
3882
+ return new Response('Not Found', { status: 404 })
3310
3883
  }
3311
- return new Response('Not Found', { status: 404 })
3884
+ if (action === 'choices') return formsIn({ ...shared, inWorkspace: false })
3885
+ return inDesignerPlace(request, principal, 'CromboloFormDesigner', shared, formsIn)
3312
3886
  }
3313
3887
 
3314
3888
  // Non-contract: what the Changes dashboard and the read-only banner read.
@@ -3443,23 +4017,40 @@ export async function createServer(
3443
4017
  return new Response('Forbidden', { status: 403 })
3444
4018
  const approvals = managementDeps.approvals as Approvals | undefined
3445
4019
  if (!approvals) return new Response('Not Found', { status: 404 })
3446
- const response = await handleApprovalsApi(
3447
- request,
3448
- pathname.slice(`${paths.pluginPath}/api/approvals/`.length),
3449
- {
4020
+ const rest = pathname.slice(`${paths.pluginPath}/api/approvals/`.length)
4021
+ const approvalsIn = async (place: SchemaPlace) =>
4022
+ (await handleApprovalsApi(request, rest, {
3450
4023
  db,
3451
4024
  approvals,
3452
4025
  principal,
3453
- schemaDir: config.schemaDir,
3454
- writable: config.schemaWritable,
3455
- onChanged: config.schemaStore
3456
- ? async () => {
3457
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
3458
- }
3459
- : undefined,
3460
- },
3461
- )
3462
- if (response) {
4026
+ schemaDir: place.schemaDir,
4027
+ writable: place.writable,
4028
+ inWorkspace: place.inWorkspace,
4029
+ onChanged:
4030
+ config.schemaStore && !place.inWorkspace
4031
+ ? async () => {
4032
+ await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
4033
+ }
4034
+ : undefined,
4035
+ })) ?? new Response('Not Found', { status: 404 })
4036
+ // Story 392: setting up a workflow in a workspace changes its copy; deciding is Shared's.
4037
+ const response = rest.startsWith('workflows')
4038
+ ? await inDesignerPlace(
4039
+ request,
4040
+ principal,
4041
+ 'CromboloWorkflowDesigner',
4042
+ {
4043
+ schemaDir: config.schemaDir,
4044
+ writable: config.schemaWritable && !contentLocked(config),
4045
+ },
4046
+ approvalsIn,
4047
+ )
4048
+ : await approvalsIn({
4049
+ schemaDir: config.schemaDir,
4050
+ writable: config.schemaWritable,
4051
+ inWorkspace: false,
4052
+ })
4053
+ if (response.status !== 404) {
3463
4054
  if (request.method !== 'GET')
3464
4055
  log.info('{user} {verb} on approvals: {status}', {
3465
4056
  user: principal.email,
@@ -3750,7 +4341,14 @@ export async function createServer(
3750
4341
  const owners = new MediaAccessRepository(db)
3751
4342
  const urls = [`/media/${key}`, pathname]
3752
4343
  const owner = await owners.byUrl(urls)
3753
- if (!owner && !(await owners.ownedElsewhere(urls)))
4344
+ // Story 390: on a workspace's site, a file only its own media names is served too;
4345
+ // on Shared's, an unmerged file is as missing as one that is not there.
4346
+ const site = workspaceSiteScope.getStore()
4347
+ if (
4348
+ !owner &&
4349
+ !(await owners.ownedElsewhere(urls)) &&
4350
+ !(site?.workspace && (await heldByWorkspace(site.workspace.id, urls)))
4351
+ )
3754
4352
  return new Response('Not Found', { status: 404 })
3755
4353
  const isProtected = owner ? mediaAccess.isProtected(owner) : false
3756
4354
  if (owner && isProtected && !(await mediaAccess.mayRead(request, owner)))
@@ -4586,8 +5184,16 @@ export async function createServer(
4586
5184
  paths,
4587
5185
  db,
4588
5186
  auth,
4589
- cache,
4590
- renderer,
5187
+ // The shared ones: a workspace's site is only ever reached through a request.
5188
+ cache: sharedCache,
5189
+ renderer: sharedRenderer,
5190
+ workspaceProcesses,
5191
+ async remoteAs(request, principal) {
5192
+ return (
5193
+ (await remote.handleAs(request, new URL(request.url), principal)) ??
5194
+ new Response(null, { status: 404 })
5195
+ )
5196
+ },
4591
5197
  snapshots,
4592
5198
  seededAdminPassword,
4593
5199
  bundleGrants,
@@ -4651,6 +5257,7 @@ export async function createServer(
4651
5257
  previewHub.stop()
4652
5258
  watcher?.close()
4653
5259
  viewWatcher?.close()
5260
+ workspaceProcesses?.close()
4654
5261
  siteAssets.close()
4655
5262
  publicFiles.close()
4656
5263
  typeWatch?.stop()