@crombolo/server 0.69.1 → 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 (45) 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 +161 -21
  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/node-operations.ts +150 -2
  24. package/src/ports.ts +174 -52
  25. package/src/remote-changes.ts +279 -0
  26. package/src/remote-schema.ts +126 -0
  27. package/src/remote-workspaces.ts +82 -0
  28. package/src/remote.ts +289 -192
  29. package/src/schema-transfer.ts +240 -41
  30. package/src/schema.ts +7 -2
  31. package/src/seed/compile.ts +13 -1
  32. package/src/seed/values.ts +3 -0
  33. package/src/server.ts +948 -364
  34. package/src/settings.ts +123 -5
  35. package/src/site-sections.ts +1 -1
  36. package/src/workspace-access.ts +152 -0
  37. package/src/workspace-checks.ts +299 -0
  38. package/src/workspace-losses.ts +95 -0
  39. package/src/workspace-processes.ts +306 -0
  40. package/src/workspace-render-child.ts +168 -0
  41. package/src/workspace-schema-dir.ts +100 -0
  42. package/src/workspace-schema.ts +598 -0
  43. package/src/workspace-sites.ts +179 -0
  44. package/src/workspace-views.ts +121 -0
  45. 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'
@@ -113,6 +114,9 @@ import {
113
114
  searchProvidersOf,
114
115
  TransferRunRepository,
115
116
  UserRepository,
117
+ WorkspaceFileRepository,
118
+ WorkspaceLinkRepository,
119
+ WorkspaceRepository,
116
120
  type WritesPaused,
117
121
  withAuditContext,
118
122
  } from '@crombolo/data'
@@ -191,10 +195,12 @@ import { handleComponentTemplates } from './component-templates-api.ts'
191
195
  import { checkTypes, listEmailTemplates, siteLayouts } from './components.ts'
192
196
  import {
193
197
  type CromboloConfig,
198
+ contentLocked,
194
199
  listeningBodyLimit,
195
200
  loadConfig,
196
201
  type ServerRole,
197
202
  VERSION,
203
+ workspacesOn,
198
204
  } from './config.ts'
199
205
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
200
206
  import { createCore } from './core.ts'
@@ -286,6 +292,7 @@ import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
286
292
  import { createTrustedSignersAdmin } from './trusted-signers-admin.ts'
287
293
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
288
294
  import type { JobsStatus } from './worker-watch.ts'
295
+ import { inSchemaPlace, type SchemaPlace } from './workspace-schema-dir.ts'
289
296
 
290
297
  export { PREVIEW_COOKIE }
291
298
 
@@ -294,7 +301,10 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
294
301
 
295
302
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
296
303
  import { backofficeAudience } from './backoffice-external.ts'
304
+ import { createChangeTransfer } from './change-transfer.ts'
305
+ import { createChangesApi } from './changes-api.ts'
297
306
  import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
307
+ import { createEnvironmentValuesApi } from './environment-values-api.ts'
298
308
  import { createExternalSignIn } from './external-sign-in.ts'
299
309
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
300
310
  import { exchangingProviders } from './identity-providers.ts'
@@ -339,6 +349,28 @@ import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
339
349
  import { summariseUpgrades } from './upgrade-summary.ts'
340
350
  import { createViewAs } from './view-as.ts'
341
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'
342
374
 
343
375
  export interface ServerHandle {
344
376
  config: CromboloConfig
@@ -400,6 +432,14 @@ export interface ServerHandle {
400
432
  reloadBundles(): Promise<BundleReload>
401
433
  /** Stops the watcher and the poll, then closes the database. */
402
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>
403
443
  }
404
444
 
405
445
  export interface ServerOptions {
@@ -482,10 +522,10 @@ export async function createServer(
482
522
  formSecret,
483
523
  cacheOptions,
484
524
  mediaCache,
485
- cache,
525
+ cache: sharedCache,
486
526
  afterSync,
487
527
  snapshots,
488
- renderer,
528
+ renderer: sharedRenderer,
489
529
  mediaStore,
490
530
  email,
491
531
  notifier,
@@ -500,6 +540,29 @@ export async function createServer(
500
540
  wake,
501
541
  urlChange,
502
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
+
503
566
  /** The extensions that are on: granted, and not turned off (story 309). */
504
567
  const onExtensions = () =>
505
568
  extensions.list().filter(
@@ -777,6 +840,7 @@ export async function createServer(
777
840
  const draftSource = createPublishedContentSource(db, {
778
841
  nodeState: schema.nodeState,
779
842
  nodeId: schema.nodeId,
843
+ environment: config.environment,
780
844
  drafts: true,
781
845
  })
782
846
  const draftCache = async (): Promise<PublishedCache> => {
@@ -1055,6 +1119,14 @@ export async function createServer(
1055
1119
  jobsWaitingSince: () => core.workerWatch.status().waitingSince,
1056
1120
  activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
1057
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
+ }),
1058
1130
  onApplied: async () => {
1059
1131
  cache.invalidate()
1060
1132
  mediaCache.clear()
@@ -1388,6 +1460,7 @@ export async function createServer(
1388
1460
  const draft = await loadDraftNode(db, key, {
1389
1461
  nodeState: schema.nodeState,
1390
1462
  nodeId: schema.nodeId,
1463
+ environment: config.environment,
1391
1464
  })
1392
1465
  if (!draft) return undefined
1393
1466
  const snapshot = await cache.snapshot()
@@ -1609,6 +1682,27 @@ export async function createServer(
1609
1682
  })
1610
1683
  },
1611
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
+ }
1612
1706
  const api = createManagementApiRouter({
1613
1707
  deps: managementDeps,
1614
1708
  authenticate,
@@ -1629,6 +1723,8 @@ export async function createServer(
1629
1723
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
1630
1724
  },
1631
1725
  onServerEvent: announce,
1726
+ // Story 375: a request in a workspace, with the workspace held while it runs.
1727
+ scope: workspaceScope,
1632
1728
  })
1633
1729
 
1634
1730
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
@@ -1717,12 +1813,121 @@ export async function createServer(
1717
1813
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1718
1814
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1719
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
+ })
1720
1923
  const previewLinkPath = `${paths.pluginPath}/api/preview-link`
1721
1924
  const selfAudited = [
1722
1925
  `${paths.pluginPath}/api/email/`,
1723
1926
  `${paths.pluginPath}/api/schema-transfer/`,
1724
1927
  viewAsPath,
1725
1928
  cliTokensPath,
1929
+ workspacesPath,
1930
+ changesPath,
1726
1931
  ]
1727
1932
  const bundleInstallPaths = new Set(
1728
1933
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
@@ -1783,7 +1988,7 @@ export async function createServer(
1783
1988
  'crombolo.node.role': config.role,
1784
1989
  },
1785
1990
  async (span) => {
1786
- const response = await answer(request)
1991
+ const response = await inWorkspaceSite(request, () => answer(request))
1787
1992
  // Readers are answered from the previous cache while it rebuilds (story
1788
1993
  // 175), so a change is in it before the request that made it is answered.
1789
1994
  if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
@@ -1968,6 +2173,269 @@ export async function createServer(
1968
2173
  : {}
1969
2174
  }
1970
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
+
1971
2439
  /** Story 368: a preview link for a page its person may read, audited as them. */
1972
2440
  async function askForPreviewLink(request: Request): Promise<Response> {
1973
2441
  if (request.method !== 'POST') return new Response(null, { status: 405 })
@@ -1976,6 +2444,7 @@ export async function createServer(
1976
2444
  const asked = (await request.json().catch(() => ({}))) as {
1977
2445
  document?: unknown
1978
2446
  culture?: unknown
2447
+ workspace?: unknown
1979
2448
  }
1980
2449
  const document = typeof asked.document === 'string' ? asked.document : ''
1981
2450
  const culture = typeof asked.culture === 'string' && asked.culture ? asked.culture : null
@@ -1985,6 +2454,20 @@ export async function createServer(
1985
2454
  if (!standing || !(await canReadDocument(principal, document, nodeLookup)))
1986
2455
  return Response.json({ title: 'You may not read this page' }, { status: 403 })
1987
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
+ }
1988
2471
  const page = await (await draftCache()).byKey(key, culture)
1989
2472
  const published = await cache.byKey(key, culture)
1990
2473
  const expires = Date.now() + PREVIEW_LINK_SECONDS * 1000
@@ -2408,9 +2891,9 @@ export async function createServer(
2408
2891
  if (pathname === `${paths.pluginPath}/api/schema-import`) {
2409
2892
  const principal = await authenticate(request)
2410
2893
  if (!principal) return new Response('Unauthorized', { status: 401 })
2411
- // Settings: this applies type changes to the database, which is what every
2412
- // `document-type` write requires.
2413
- 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 })
2414
2897
  if (request.method !== 'GET' && request.method !== 'POST') {
2415
2898
  return new Response('Method Not Allowed', { status: 405 })
2416
2899
  }
@@ -2870,6 +3353,51 @@ export async function createServer(
2870
3353
  )
2871
3354
  }
2872
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
+
2873
3401
  // Story 368: a link that opens one page's draft in any browser.
2874
3402
  if (pathname === previewLinkPath) return askForPreviewLink(request)
2875
3403
 
@@ -2965,373 +3493,396 @@ export async function createServer(
2965
3493
  const principal = await authenticate(request)
2966
3494
  if (!principal) return new Response('Unauthorized', { status: 401 })
2967
3495
  const action = pathname.slice(`${paths.pluginPath}/api/forms`.length).replace(/^\//, '')
2968
- // Through the registry the renderer uses, so the designer and a render
2969
- // cannot disagree; a save invalidates it rather than waiting out the memo.
2970
- const definitions = forms.all()
2971
-
2972
- // A definition is structure, like a content type: anyone who may open the
2973
- // section may read it, and the picker needs it in the Content section too.
2974
- if (action === '' && request.method === 'GET') {
2975
- const files = loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files
2976
- const file = (alias: string) => files.get(`form:${alias}`)
2977
- return Response.json({
2978
- items: definitions.map((form) => ({
2979
- ...formSummary(form, formTypes.types),
2980
- folder: file(form.alias)
2981
- ? folderOf(config.schemaDir, 'forms', file(form.alias) as string)
2982
- : '',
2983
- })),
2984
- folders: foldersIn(config.schemaDir, 'forms'),
2985
- readOnlyBecause: !config.schemaWritable
2986
- ? 'site'
2987
- : principal.isAdmin || principal.permissions.includes(FormPermissions.Manage)
2988
- ? null
2989
- : 'permission',
2990
- })
2991
- }
2992
- // Hyphenated, so no form alias (letters and digits) can be mistaken for it.
2993
- if (action === 'available-types' && request.method === 'GET')
2994
- return Response.json(describeFormTypes(formTypes.types))
2995
- // The Library forms (story 239), for a page's form picker and the entries filter.
2996
- if (action === 'library-forms' && request.method === 'GET') {
2997
- const known = new Map(definitions.map((form) => [form.key ?? form.alias, form]))
2998
- return Response.json({
2999
- items: (await listLibraryForms(db)).map((item) => ({
3000
- ...item,
3001
- formAlias: known.get(item.formKey)?.alias ?? null,
3002
- formName: known.get(item.formKey)?.name ?? null,
3003
- })),
3004
- })
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),
3005
3501
  }
3006
- // Which content types are made from a form, for the note in their editor.
3007
- if (action === 'library-types' && request.method === 'GET')
3008
- return Response.json({
3009
- items: definitions.map((form) => ({
3010
- typeKey: libraryFormTypeKey(libraryFormId(form)),
3011
- formName: form.name,
3012
- })),
3013
- })
3014
- // The designer's "E-mail design" picker.
3015
- if (action === 'email-templates' && request.method === 'GET')
3016
- return Response.json({
3017
- items: listEmailTemplates(
3018
- config.componentsDir,
3019
- definitions.flatMap((form) =>
3020
- form.workflows.flatMap((workflow) =>
3021
- 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
+ ),
3022
3562
  ),
3023
3563
  ),
3024
- ),
3025
- })
3564
+ })
3026
3565
 
3027
- const entries = new FormEntryRepository(db)
3028
- const byKey = formsByKey(definitions)
3029
- // Submissions are personal data, so reading them asks for more than a
3030
- // session. Four verbs, because designing a form and reading what people
3031
- // sent it are different jobs (`docs/forms.md`).
3032
- const may = (verb: string) => principal.isAdmin || principal.permissions.includes(verb)
3033
- const formFiles = {
3034
- schemaDir: config.schemaDir,
3035
- writable: config.schemaWritable,
3036
- formTypes: formTypes.types,
3037
- componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
3038
- onChanged: config.schemaStore
3039
- ? async () => {
3040
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
3041
- }
3042
- : undefined,
3043
- }
3044
- // Every dictionary item in the default language, for the designer to suggest.
3045
- if (action === 'words' && request.method === 'GET') {
3046
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3047
- const entries = await cache.dictionaryEntries(null)
3048
- return Response.json({
3049
- words: Object.entries(entries).map(([name, text]) => ({ name, text })),
3050
- })
3051
- }
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
+ }
3052
3592
 
3053
- const maySeeEntries = may(FormPermissions.EntriesView)
3054
- const mayManageEntries = may(FormPermissions.EntriesManage)
3055
- // The group alias still counts: `sensitiveData` is how Umbraco carries
3056
- // this and how members already work, so both routes to it are honoured.
3057
- const maySeeSensitive =
3058
- may(FormPermissions.EntriesSensitive) || hasAccessToSensitiveData(principal.groups)
3059
-
3060
- const entryMatch = /^entries\/([^/]+)(?:\/(state))?$/.exec(action)
3061
- if (entryMatch) {
3062
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3063
- const id = decodeURIComponent(entryMatch[1] as string)
3064
- if (entryMatch[2] === 'state' && request.method === 'POST') {
3065
- if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3066
- const body = (await request.json().catch(() => ({}))) as { state?: unknown }
3067
- const next = parseEntryState(typeof body.state === 'string' ? body.state : null)
3068
- if (!next) return new Response('Bad Request', { status: 400 })
3069
- const updated = await entries.setState(id, next)
3070
- if (!updated) return new Response('Not Found', { status: 404 })
3071
- // Approval is the other trigger: a workflow declared `on = "approve"`
3072
- // runs now, from the values the entry holds.
3073
- if (next === 'approved') {
3074
- const form = byKey.get(updated.formKey)
3075
- const onApprove = form?.workflows.filter((workflow) => workflow.on === 'approve') ?? []
3076
- // Through a Library form: its recipients as they are now (story 239).
3077
- const recipients = updated.libraryKey
3078
- ? (await cache.libraryForm(updated.libraryKey))?.library?.recipients
3079
- : undefined
3080
- if (onApprove.length > 0)
3081
- await new FormWorkflowRepository(db).enqueue(
3082
- onApprove.map((workflow) => ({
3083
- formKey: updated.formKey,
3084
- formAlias: updated.formAlias,
3085
- workflowName: workflow.name,
3086
- workflowType: workflow.type,
3087
- runOn: workflow.on,
3088
- entryId: updated.id,
3089
- payload: updated.values.map((value) => ({
3090
- fieldAlias: value.fieldAlias,
3091
- 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 } : {}),
3092
3635
  })),
3093
- ...(recipients ? { recipients } : {}),
3094
- })),
3095
- )
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 })
3096
3644
  }
3097
- log.info('{user} set form entry {id} to {state}', {
3098
- user: principal.email,
3099
- id,
3100
- state: next,
3101
- })
3102
- 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 })
3103
3660
  }
3104
- if (request.method === 'DELETE') {
3105
- if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
3106
- if (!(await entries.remove(id))) return new Response('Not Found', { status: 404 })
3107
- log.info('{user} deleted form entry {id}', { user: principal.email, id })
3108
- 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
+ })
3109
3684
  }
3110
- if (request.method === 'GET') {
3111
- const entry = await entries.byId(id)
3112
- 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)
3113
3707
  return Response.json({
3114
- ...entry,
3115
- 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
+ })),
3116
3714
  })
3117
3715
  }
3118
- return new Response('Method Not Allowed', { status: 405 })
3119
- }
3120
3716
 
3121
- const csvMatch = /^([^/]+)\/entries\.csv$/.exec(action)
3122
- if (csvMatch && request.method === 'GET') {
3123
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3124
- const key = decodeURIComponent(csvMatch[1] as string)
3125
- const form = byKey.get(key)
3126
- if (!form) return new Response('Not Found', { status: 404 })
3127
- const page = await entries.list({ formKey: key, take: 10_000 })
3128
- const result = entriesCsv(await cache.resolveForm(form), page.items, {
3129
- includeSensitive: maySeeSensitive,
3130
- types: formTypes.types,
3131
- })
3132
- if (!result.ok)
3133
- return new Response(result.reason, {
3134
- status: 403,
3135
- 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),
3136
3762
  })
3137
- return new Response(result.csv, {
3138
- headers: {
3139
- 'content-type': 'text/csv; charset=utf-8',
3140
- 'content-disposition': `attachment; filename="${result.fileName}"`,
3141
- },
3142
- })
3143
- }
3763
+ return Response.json({ ok: true })
3764
+ }
3144
3765
 
3145
- const listMatch = /^([^/]+)\/entries$/.exec(action)
3146
- if (listMatch && request.method === 'GET') {
3147
- if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
3148
- const key = decodeURIComponent(listMatch[1] as string)
3149
- const since = url.searchParams.get('from')
3150
- const until = url.searchParams.get('to')
3151
- // `library=none` for the entries that came through no Library form.
3152
- const library = url.searchParams.get('library')
3153
- const page = await entries.list({
3154
- formKey: key,
3155
- ...(library ? { libraryKey: library === 'none' ? null : library } : {}),
3156
- state: parseEntryState(url.searchParams.get('state')),
3157
- culture: url.searchParams.get('language') || undefined,
3158
- from: since ? new Date(since) : undefined,
3159
- to: until ? new Date(until) : undefined,
3160
- search: url.searchParams.get('search') ?? undefined,
3161
- includeSpam: url.searchParams.get('includeSpam') === 'true',
3162
- skip: Number(url.searchParams.get('skip') ?? 0) || 0,
3163
- take: Number(url.searchParams.get('take') ?? 100) || 100,
3164
- })
3165
- const form = byKey.get(key)
3166
- return Response.json({
3167
- total: page.total,
3168
- languages: await entries.languages(key),
3169
- items: page.items.map((entry) => ({
3170
- ...entry,
3171
- values: redactSensitive(entry, form, maySeeSensitive),
3172
- })),
3173
- })
3174
- }
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
+ }
3175
3788
 
3176
- // A send-to-URL workflow's secret header (story 304): sealed here, never
3177
- // in the form's file, and never shown back. Set on any site, schema
3178
- // writable or not, since it is the site's own and not the form's.
3179
- const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
3180
- if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
3181
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3182
- const [, formKey, workflowKey, header] = secretMatch.map((part) =>
3183
- decodeURIComponent(part),
3184
- ) as [string, string, string, string]
3185
- const form = byKey.get(formKey)
3186
- const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
3187
- const headers = workflow?.settings.headers as Record<string, unknown> | undefined
3188
- if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
3189
- return Response.json(
3190
- { message: 'The form names no such secret header; save the form first.' },
3191
- { 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'
3192
3799
  )
3193
- const secrets = new FormWorkflowSecretRepository(db)
3194
- let set: { sealed: string; url: string } | undefined
3195
- if (request.method === 'PUT') {
3196
- const body = (await request.json().catch(() => ({}))) as { value?: unknown }
3197
- if (typeof body.value !== 'string' || body.value === '')
3198
- return Response.json({ message: 'Give the header a value.' }, { status: 400 })
3199
- const key = usableSecretKey(config.secretKey)
3200
- if (!key)
3201
- return Response.json(
3202
- {
3203
- message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
3204
- },
3205
- { status: 409 },
3206
- )
3207
- 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 })
3208
3806
  }
3209
- await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
3210
- await recordAudit(db, {
3211
- category: 'settings',
3212
- action: set ? 'secret header set' : 'secret header removed',
3213
- source: 'request',
3214
- userKey: principal.id,
3215
- userName: principal.name,
3216
- entityType: 'form',
3217
- entityKey: form.key,
3218
- entityName: form.name,
3219
- detail: `${workflow.name}: ${header}`,
3220
- ...clientAddress(request),
3221
- })
3222
- return Response.json({ ok: true })
3223
- }
3224
3807
 
3225
- if (action && request.method === 'GET') {
3226
- const form = byKey.get(decodeURIComponent(action))
3227
- if (!form) return new Response('Not Found', { status: 404 })
3228
- // Which secret headers are set for the address each workflow sends to, never their values.
3229
- const secrets: { workflow: string; header: string; set: boolean }[] = []
3230
- for (const workflow of form.workflows) {
3231
- const headers = workflow.settings.headers as Record<string, unknown> | undefined
3232
- const named = Object.keys(headers ?? {}).filter((name) => isSecretHeader(headers?.[name]))
3233
- if (named.length === 0 || !workflow.key || !form.key) continue
3234
- const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
3235
- for (const header of named)
3236
- secrets.push({
3237
- workflow: workflow.key,
3238
- header,
3239
- 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('; '),
3240
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 })
3241
3857
  }
3242
- // The whole definition, which is what the designer edits.
3243
- return Response.json({ ...formDetail(form), definition: form, secrets })
3244
- }
3245
3858
 
3246
- // What a choice source offers now, in the default language, for the
3247
- // designer to show beside the source it is editing.
3248
- if (action === 'choices' && request.method === 'POST') {
3249
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3250
- const body = (await request.json().catch(() => ({}))) as { source?: unknown }
3251
- const source = body.source as { kind?: unknown; parent?: unknown } | undefined
3252
- if (
3253
- !source ||
3254
- !CHOICE_SOURCE_KINDS.includes(source.kind as ChoiceSourceKind) ||
3255
- typeof source.parent !== 'string'
3256
- )
3257
- return new Response('Bad Request', { status: 400 })
3258
- const options = await cache.choiceOptions({
3259
- kind: source.kind as ChoiceSourceKind,
3260
- parent: source.parent,
3261
- })
3262
- return Response.json({ options })
3263
- }
3264
-
3265
- // Designing a form is a developer's job, so it is its own verb rather
3266
- // than something an entry reader can do.
3267
- if (action === 'tree-folders' || action === 'tree-move') {
3268
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3269
- const response = await folderAction('forms', action, request, {
3270
- ...formFiles,
3271
- file: (alias) =>
3272
- loadSchemaDirectory(config.schemaDir, { formTypes: formTypes.types }).files.get(
3273
- `form:${alias}`,
3274
- ),
3275
- })
3276
- if (response) return response
3277
- }
3278
- if (request.method === 'POST' || request.method === 'PUT') {
3279
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3280
- const body = await request.json().catch(() => ({}))
3281
- const folder = url.searchParams.get('folder') ?? undefined
3282
- const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
3283
- if (refused.length > 0)
3284
- return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
3285
- const written = await saveForm(coerceForm(body), { ...formFiles, folder })
3286
- if (!written.ok) {
3287
- 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', {
3288
3877
  user: principal.email,
3289
- detail: written.problems.map((problem) => problem.message).join('; '),
3878
+ form: form.alias,
3290
3879
  })
3291
- return Response.json(
3292
- { status: written.status, problems: written.problems },
3293
- { status: written.status === 'readOnly' ? 409 : 400 },
3294
- )
3880
+ return Response.json({ ok: true })
3295
3881
  }
3296
- // The memo would otherwise hold the old definition for a second, which
3297
- // is exactly long enough for the designer to reload and see it.
3298
- forms.invalidate()
3299
- await ensureFormLibraryTypes(db, forms.all())
3300
- cache.invalidate()
3301
- const saved = coerceForm(body)
3302
- if (saved.key)
3303
- await new FormWorkflowSecretRepository(db).forget(
3304
- saved.key,
3305
- saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
3306
- )
3307
- log.info('{user} saved the form {form}', {
3308
- user: principal.email,
3309
- form: coerceForm(body).alias,
3310
- })
3311
- return Response.json({ ok: true })
3312
- }
3313
-
3314
- if (action && request.method === 'DELETE') {
3315
- if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
3316
- const form = byKey.get(decodeURIComponent(action))
3317
- if (!form) return new Response('Not Found', { status: 404 })
3318
- const removed = await deleteForm(form.alias, formFiles)
3319
- if (!removed.ok)
3320
- return Response.json(
3321
- { status: removed.status, problems: removed.problems },
3322
- { status: removed.status === 'readOnly' ? 409 : 404 },
3323
- )
3324
- forms.invalidate()
3325
- await ensureFormLibraryTypes(db, forms.all())
3326
- cache.invalidate()
3327
- if (form.key) await new FormWorkflowSecretRepository(db).forget(form.key)
3328
- log.info('{user} deleted the form {form}; its entries are kept', {
3329
- user: principal.email,
3330
- form: form.alias,
3331
- })
3332
- return Response.json({ ok: true })
3882
+ return new Response('Not Found', { status: 404 })
3333
3883
  }
3334
- return new Response('Not Found', { status: 404 })
3884
+ if (action === 'choices') return formsIn({ ...shared, inWorkspace: false })
3885
+ return inDesignerPlace(request, principal, 'CromboloFormDesigner', shared, formsIn)
3335
3886
  }
3336
3887
 
3337
3888
  // Non-contract: what the Changes dashboard and the read-only banner read.
@@ -3466,23 +4017,40 @@ export async function createServer(
3466
4017
  return new Response('Forbidden', { status: 403 })
3467
4018
  const approvals = managementDeps.approvals as Approvals | undefined
3468
4019
  if (!approvals) return new Response('Not Found', { status: 404 })
3469
- const response = await handleApprovalsApi(
3470
- request,
3471
- pathname.slice(`${paths.pluginPath}/api/approvals/`.length),
3472
- {
4020
+ const rest = pathname.slice(`${paths.pluginPath}/api/approvals/`.length)
4021
+ const approvalsIn = async (place: SchemaPlace) =>
4022
+ (await handleApprovalsApi(request, rest, {
3473
4023
  db,
3474
4024
  approvals,
3475
4025
  principal,
3476
- schemaDir: config.schemaDir,
3477
- writable: config.schemaWritable,
3478
- onChanged: config.schemaStore
3479
- ? async () => {
3480
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
3481
- }
3482
- : undefined,
3483
- },
3484
- )
3485
- 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) {
3486
4054
  if (request.method !== 'GET')
3487
4055
  log.info('{user} {verb} on approvals: {status}', {
3488
4056
  user: principal.email,
@@ -3773,7 +4341,14 @@ export async function createServer(
3773
4341
  const owners = new MediaAccessRepository(db)
3774
4342
  const urls = [`/media/${key}`, pathname]
3775
4343
  const owner = await owners.byUrl(urls)
3776
- 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
+ )
3777
4352
  return new Response('Not Found', { status: 404 })
3778
4353
  const isProtected = owner ? mediaAccess.isProtected(owner) : false
3779
4354
  if (owner && isProtected && !(await mediaAccess.mayRead(request, owner)))
@@ -4609,8 +5184,16 @@ export async function createServer(
4609
5184
  paths,
4610
5185
  db,
4611
5186
  auth,
4612
- cache,
4613
- 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
+ },
4614
5197
  snapshots,
4615
5198
  seededAdminPassword,
4616
5199
  bundleGrants,
@@ -4674,6 +5257,7 @@ export async function createServer(
4674
5257
  previewHub.stop()
4675
5258
  watcher?.close()
4676
5259
  viewWatcher?.close()
5260
+ workspaceProcesses?.close()
4677
5261
  siteAssets.close()
4678
5262
  publicFiles.close()
4679
5263
  typeWatch?.stop()