@crombolo/server 0.69.1 → 0.71.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.
- package/package.json +15 -14
- package/src/adapters/blueprints.ts +51 -5
- package/src/adapters/change-recording.ts +140 -0
- package/src/adapters/content.ts +132 -21
- package/src/adapters/documents.ts +26 -5
- package/src/adapters/elements.ts +3 -0
- package/src/adapters/media.ts +7 -1
- package/src/adapters/schema-files.ts +89 -1
- package/src/adapters/users.ts +17 -12
- package/src/adapters/workspace-dictionary.ts +287 -0
- package/src/adapters/workspace-file-port.ts +160 -0
- package/src/adapters/workspace-languages.ts +94 -0
- package/src/approvals-api.ts +16 -7
- package/src/bundle-api.ts +19 -16
- package/src/bundle-install.ts +4 -0
- package/src/change-transfer.ts +676 -0
- package/src/changes-api.ts +258 -0
- package/src/component-templates-api.ts +2 -2
- package/src/config.ts +195 -21
- package/src/content-events.ts +65 -1
- package/src/content-operations.ts +22 -3
- package/src/core.ts +2 -0
- package/src/environment-values-api.ts +161 -0
- package/src/external-sign-in.ts +9 -2
- package/src/index.ts +1 -0
- package/src/managed-users.ts +122 -0
- package/src/node-operations.ts +150 -2
- package/src/ports.ts +174 -52
- package/src/principal.ts +1 -0
- package/src/remote-changes.ts +279 -0
- package/src/remote-schema.ts +126 -0
- package/src/remote-workspaces.ts +82 -0
- package/src/remote.ts +289 -192
- package/src/schema-transfer.ts +240 -41
- package/src/schema.ts +7 -2
- package/src/seed/compile.ts +13 -1
- package/src/seed/values.ts +3 -0
- package/src/server.ts +965 -364
- package/src/settings.ts +137 -5
- package/src/site-sections.ts +1 -1
- package/src/user-admin.ts +2 -0
- package/src/workspace-access.ts +152 -0
- package/src/workspace-checks.ts +299 -0
- package/src/workspace-losses.ts +95 -0
- package/src/workspace-processes.ts +306 -0
- package/src/workspace-render-child.ts +168 -0
- package/src/workspace-schema-dir.ts +100 -0
- package/src/workspace-schema.ts +598 -0
- package/src/workspace-sites.ts +179 -0
- package/src/workspace-views.ts +121 -0
- 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,13 @@ 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,
|
|
202
|
+
usersManaged,
|
|
197
203
|
VERSION,
|
|
204
|
+
workspacesOn,
|
|
198
205
|
} from './config.ts'
|
|
199
206
|
import { answerContentQuery, contentQueryScope } from './content-query.ts'
|
|
200
207
|
import { createCore } from './core.ts'
|
|
@@ -286,6 +293,7 @@ import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
|
|
|
286
293
|
import { createTrustedSignersAdmin } from './trusted-signers-admin.ts'
|
|
287
294
|
import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
|
|
288
295
|
import type { JobsStatus } from './worker-watch.ts'
|
|
296
|
+
import { inSchemaPlace, type SchemaPlace } from './workspace-schema-dir.ts'
|
|
289
297
|
|
|
290
298
|
export { PREVIEW_COOKIE }
|
|
291
299
|
|
|
@@ -294,7 +302,10 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
|
|
|
294
302
|
|
|
295
303
|
import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
|
|
296
304
|
import { backofficeAudience } from './backoffice-external.ts'
|
|
305
|
+
import { createChangeTransfer } from './change-transfer.ts'
|
|
306
|
+
import { createChangesApi } from './changes-api.ts'
|
|
297
307
|
import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
|
|
308
|
+
import { createEnvironmentValuesApi } from './environment-values-api.ts'
|
|
298
309
|
import { createExternalSignIn } from './external-sign-in.ts'
|
|
299
310
|
import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
|
|
300
311
|
import { exchangingProviders } from './identity-providers.ts'
|
|
@@ -304,6 +315,7 @@ import {
|
|
|
304
315
|
viteIslandManifest,
|
|
305
316
|
viteOutDir,
|
|
306
317
|
} from './islands.ts'
|
|
318
|
+
import { managedHref } from './managed-users.ts'
|
|
307
319
|
import {
|
|
308
320
|
hasMiddleware,
|
|
309
321
|
isSitePath,
|
|
@@ -339,6 +351,28 @@ import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
|
|
|
339
351
|
import { summariseUpgrades } from './upgrade-summary.ts'
|
|
340
352
|
import { createViewAs } from './view-as.ts'
|
|
341
353
|
import { webhookStoreView } from './webhooks.ts'
|
|
354
|
+
import {
|
|
355
|
+
accessCookie,
|
|
356
|
+
linkSecretHash,
|
|
357
|
+
readAccess,
|
|
358
|
+
readHandoff,
|
|
359
|
+
signAccess,
|
|
360
|
+
signHandoff,
|
|
361
|
+
WORKSPACE_COOKIE,
|
|
362
|
+
WORKSPACE_COOKIE_SECONDS,
|
|
363
|
+
WORKSPACE_HANDOFF_ISSUER,
|
|
364
|
+
WORKSPACE_HANDOFF_PARAM,
|
|
365
|
+
WORKSPACE_HANDOFF_SECONDS,
|
|
366
|
+
WORKSPACE_LINK_HEADER,
|
|
367
|
+
WORKSPACE_LINK_PARAM,
|
|
368
|
+
type WorkspaceAccess,
|
|
369
|
+
workspaceHosts,
|
|
370
|
+
} from './workspace-access.ts'
|
|
371
|
+
import { createWorkspaceChecks } from './workspace-checks.ts'
|
|
372
|
+
import { createWorkspaceProcesses, type WorkspaceProcesses } from './workspace-processes.ts'
|
|
373
|
+
import { createWorkspaceSchema } from './workspace-schema.ts'
|
|
374
|
+
import { createWorkspaceSites } from './workspace-sites.ts'
|
|
375
|
+
import { createWorkspaceScope, createWorkspacesApi } from './workspaces.ts'
|
|
342
376
|
|
|
343
377
|
export interface ServerHandle {
|
|
344
378
|
config: CromboloConfig
|
|
@@ -400,6 +434,14 @@ export interface ServerHandle {
|
|
|
400
434
|
reloadBundles(): Promise<BundleReload>
|
|
401
435
|
/** Stops the watcher and the poll, then closes the database. */
|
|
402
436
|
close(): Promise<void>
|
|
437
|
+
/** Where workspaces that changed their views render (story 378); none on a database in memory. */
|
|
438
|
+
workspaceProcesses: WorkspaceProcesses | undefined
|
|
439
|
+
/**
|
|
440
|
+
* A remote-protocol request as `principal`, in this process (story 386): how a
|
|
441
|
+
* command run in a site's folder reaches its workspaces and changes, as it would a
|
|
442
|
+
* hosted site's, with no server listening and the remote off.
|
|
443
|
+
*/
|
|
444
|
+
remoteAs(request: Request, principal: Principal): Promise<Response>
|
|
403
445
|
}
|
|
404
446
|
|
|
405
447
|
export interface ServerOptions {
|
|
@@ -482,10 +524,10 @@ export async function createServer(
|
|
|
482
524
|
formSecret,
|
|
483
525
|
cacheOptions,
|
|
484
526
|
mediaCache,
|
|
485
|
-
cache,
|
|
527
|
+
cache: sharedCache,
|
|
486
528
|
afterSync,
|
|
487
529
|
snapshots,
|
|
488
|
-
renderer,
|
|
530
|
+
renderer: sharedRenderer,
|
|
489
531
|
mediaStore,
|
|
490
532
|
email,
|
|
491
533
|
notifier,
|
|
@@ -500,6 +542,29 @@ export async function createServer(
|
|
|
500
542
|
wake,
|
|
501
543
|
urlChange,
|
|
502
544
|
} = core
|
|
545
|
+
// Story 379: while a request is served from a workspace's site, the cache and the
|
|
546
|
+
// renderer it reads are the workspace's; everything handed them follows.
|
|
547
|
+
const workspaceSiteScope = new AsyncLocalStorage<{
|
|
548
|
+
cache: PublishedCache
|
|
549
|
+
renderer: Renderer
|
|
550
|
+
workspace?: { id: number; key: string }
|
|
551
|
+
}>()
|
|
552
|
+
const viaWorkspaceSite = <T extends object>(
|
|
553
|
+
shared: T,
|
|
554
|
+
pick: (site: { cache: PublishedCache; renderer: Renderer }) => T,
|
|
555
|
+
): T =>
|
|
556
|
+
new Proxy(shared, {
|
|
557
|
+
get(target, prop) {
|
|
558
|
+
const site = workspaceSiteScope.getStore()
|
|
559
|
+
const actual = site ? pick(site) : target
|
|
560
|
+
// The real object as the receiver: its getters read private fields.
|
|
561
|
+
const value = Reflect.get(actual, prop, actual)
|
|
562
|
+
return typeof value === 'function' ? value.bind(actual) : value
|
|
563
|
+
},
|
|
564
|
+
})
|
|
565
|
+
const cache = viaWorkspaceSite(sharedCache, (site) => site.cache)
|
|
566
|
+
const renderer = viaWorkspaceSite(sharedRenderer, (site) => site.renderer)
|
|
567
|
+
|
|
503
568
|
/** The extensions that are on: granted, and not turned off (story 309). */
|
|
504
569
|
const onExtensions = () =>
|
|
505
570
|
extensions.list().filter(
|
|
@@ -674,6 +739,7 @@ export async function createServer(
|
|
|
674
739
|
applicationUrl: config.applicationUrl,
|
|
675
740
|
secureCookies: config.secureCookies,
|
|
676
741
|
log: (message) => log.warning('Backoffice sign-in: {message}', { message }),
|
|
742
|
+
managed: () => usersManaged(config),
|
|
677
743
|
resolve: (provider) =>
|
|
678
744
|
new IdentityProviderOverrides(
|
|
679
745
|
db,
|
|
@@ -777,6 +843,7 @@ export async function createServer(
|
|
|
777
843
|
const draftSource = createPublishedContentSource(db, {
|
|
778
844
|
nodeState: schema.nodeState,
|
|
779
845
|
nodeId: schema.nodeId,
|
|
846
|
+
environment: config.environment,
|
|
780
847
|
drafts: true,
|
|
781
848
|
})
|
|
782
849
|
const draftCache = async (): Promise<PublishedCache> => {
|
|
@@ -1055,6 +1122,14 @@ export async function createServer(
|
|
|
1055
1122
|
jobsWaitingSince: () => core.workerWatch.status().waitingSince,
|
|
1056
1123
|
activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
|
|
1057
1124
|
onMediaAccessChange: (key) => mediaCache.drop([key]),
|
|
1125
|
+
// Made further down, and asked only once a request comes.
|
|
1126
|
+
schema: () => schemaTransfer,
|
|
1127
|
+
workspaces: () => workspacesApi,
|
|
1128
|
+
changes: () => (workspacesOn(config) ? changeTransfer : undefined),
|
|
1129
|
+
changeRoutes: () => ({
|
|
1130
|
+
handle: (request: Request, principal: Principal, rest: string) =>
|
|
1131
|
+
changesApi.handle(request, principal, rest, { ipAddress: null, forwardedFor: null }),
|
|
1132
|
+
}),
|
|
1058
1133
|
onApplied: async () => {
|
|
1059
1134
|
cache.invalidate()
|
|
1060
1135
|
mediaCache.clear()
|
|
@@ -1388,6 +1463,7 @@ export async function createServer(
|
|
|
1388
1463
|
const draft = await loadDraftNode(db, key, {
|
|
1389
1464
|
nodeState: schema.nodeState,
|
|
1390
1465
|
nodeId: schema.nodeId,
|
|
1466
|
+
environment: config.environment,
|
|
1391
1467
|
})
|
|
1392
1468
|
if (!draft) return undefined
|
|
1393
1469
|
const snapshot = await cache.snapshot()
|
|
@@ -1609,6 +1685,27 @@ export async function createServer(
|
|
|
1609
1685
|
})
|
|
1610
1686
|
},
|
|
1611
1687
|
})
|
|
1688
|
+
// Story 375: a request in a workspace, with the workspace held while it runs.
|
|
1689
|
+
const workspaceScope = createWorkspaceScope(db, {
|
|
1690
|
+
enabled: () => workspacesOn(config),
|
|
1691
|
+
required: () => config.workspacesRequired,
|
|
1692
|
+
locked: () => contentLocked(config),
|
|
1693
|
+
merge: () => core.operations.merge,
|
|
1694
|
+
schema: () => workspaceSchema,
|
|
1695
|
+
})
|
|
1696
|
+
/** Story 392: a designer's request, in the workspace it names, against its `schema/`. */
|
|
1697
|
+
const inDesignerPlace = async (
|
|
1698
|
+
request: Request,
|
|
1699
|
+
principal: Principal,
|
|
1700
|
+
operationId: string,
|
|
1701
|
+
shared: { schemaDir: string; writable: boolean },
|
|
1702
|
+
run: (place: SchemaPlace) => Promise<Response>,
|
|
1703
|
+
): Promise<Response> => {
|
|
1704
|
+
const scope = await workspaceScope(request, principal, { operationId })
|
|
1705
|
+
if (scope instanceof Response) return scope
|
|
1706
|
+
const go = () => inSchemaPlace(db, shared, request, run, principal.id)
|
|
1707
|
+
return scope ? scope.run(go) : go()
|
|
1708
|
+
}
|
|
1612
1709
|
const api = createManagementApiRouter({
|
|
1613
1710
|
deps: managementDeps,
|
|
1614
1711
|
authenticate,
|
|
@@ -1629,6 +1726,8 @@ export async function createServer(
|
|
|
1629
1726
|
void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
|
|
1630
1727
|
},
|
|
1631
1728
|
onServerEvent: announce,
|
|
1729
|
+
// Story 375: a request in a workspace, with the workspace held while it runs.
|
|
1730
|
+
scope: workspaceScope,
|
|
1632
1731
|
})
|
|
1633
1732
|
|
|
1634
1733
|
// Fixed by the contract and the client's SDK, wherever the editor is mounted.
|
|
@@ -1717,12 +1816,122 @@ export async function createServer(
|
|
|
1717
1816
|
const contentQueryPath = `${paths.pluginPath}/api/content-query`
|
|
1718
1817
|
const viewAsPath = `${paths.pluginPath}/api/view-as`
|
|
1719
1818
|
const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
|
|
1819
|
+
const usersManagedPath = `${paths.pluginPath}/api/users-managed`
|
|
1820
|
+
const workspacesPath = `${paths.pluginPath}/api/workspaces`
|
|
1821
|
+
const changesPath = `${paths.pluginPath}/api/changes`
|
|
1822
|
+
const environmentValuesPath = `${paths.pluginPath}/api/environment-values`
|
|
1823
|
+
// Story 376: a workspace's copy of the schema files.
|
|
1824
|
+
const workspaceSchema = createWorkspaceSchema(db, config, core.schema)
|
|
1825
|
+
// Story 378: a workspace that changed its views renders in a process of its own.
|
|
1826
|
+
// A database in memory cannot be opened from another process: it renders here then.
|
|
1827
|
+
const sharedDatabase = config.dialect === 'postgres' || config.sqliteFile !== ':memory:'
|
|
1828
|
+
const workspaceProcesses = sharedDatabase
|
|
1829
|
+
? createWorkspaceProcesses({
|
|
1830
|
+
dialect: config.dialect,
|
|
1831
|
+
sqliteFile: config.sqliteFile,
|
|
1832
|
+
nodeState: core.schema.nodeState,
|
|
1833
|
+
nodeId: core.schema.nodeId,
|
|
1834
|
+
componentsCacheDir: config.componentsCacheDir,
|
|
1835
|
+
environment: config.environment,
|
|
1836
|
+
limit: config.workspaceProcesses,
|
|
1837
|
+
idleMs: config.workspaceProcessIdleMinutes * 60_000,
|
|
1838
|
+
memoryMb: config.workspaceProcessMemoryMb,
|
|
1839
|
+
renderMs: config.workspaceRenderSeconds * 1000,
|
|
1840
|
+
})
|
|
1841
|
+
: undefined
|
|
1842
|
+
const workspacesApi = createWorkspacesApi(db, {
|
|
1843
|
+
enabled: () => workspacesOn(config),
|
|
1844
|
+
locked: () => contentLocked(config),
|
|
1845
|
+
editedAt: () => config.contentEditedAt ?? null,
|
|
1846
|
+
checks: () => workspaceChecks,
|
|
1847
|
+
merge: () => core.operations.merge,
|
|
1848
|
+
nodeState: core.schema.nodeState,
|
|
1849
|
+
required: () => config.workspacesRequired,
|
|
1850
|
+
schema: () => workspaceSchema,
|
|
1851
|
+
// From the workspace's own site: its published pages, with its views (stories 377, 379).
|
|
1852
|
+
render: async (workspace, path) => {
|
|
1853
|
+
const site = await workspaceSites.siteFor(workspace)
|
|
1854
|
+
const result = await site.renderer.render(path)
|
|
1855
|
+
const views = site.views
|
|
1856
|
+
if (result.status === 'ok') return { status: 'ok', html: result.html, views }
|
|
1857
|
+
if (result.status === 'error') return { status: 'error', error: result.error.message, views }
|
|
1858
|
+
return { status: result.status, views }
|
|
1859
|
+
},
|
|
1860
|
+
onClosed: (key) => {
|
|
1861
|
+
workspaceProcesses?.stop(key)
|
|
1862
|
+
workspaceSites.forget(key)
|
|
1863
|
+
},
|
|
1864
|
+
// Story 390: a discarded workspace's files go, those nothing else names, after it.
|
|
1865
|
+
onDiscardedFiles: (urls) => {
|
|
1866
|
+
void removeUnnamedFiles(urls).catch((error: unknown) =>
|
|
1867
|
+
logger('media').warn('A discarded workspace left files: {error}', { error: String(error) }),
|
|
1868
|
+
)
|
|
1869
|
+
},
|
|
1870
|
+
open: (workspace, principal, path, request) =>
|
|
1871
|
+
workspaceOpenUrl(workspace, principal, path, request),
|
|
1872
|
+
links: () => workspaceLinks,
|
|
1873
|
+
})
|
|
1874
|
+
// Story 386: a workspace's diff, conflicts and checks, for the command line.
|
|
1875
|
+
const workspaceChecks = createWorkspaceChecks({
|
|
1876
|
+
db,
|
|
1877
|
+
merge: () => core.operations.merge,
|
|
1878
|
+
schema: () => workspaceSchema,
|
|
1879
|
+
async render(workspace, path) {
|
|
1880
|
+
const site = await workspaceSites.siteFor(workspace)
|
|
1881
|
+
const result = await site.renderer.render(path)
|
|
1882
|
+
if (result.status === 'ok') return { status: 'ok', html: result.html }
|
|
1883
|
+
if (result.status === 'error') return { status: 'error', error: result.error.message }
|
|
1884
|
+
return { status: result.status }
|
|
1885
|
+
},
|
|
1886
|
+
async urlOf(workspace, key) {
|
|
1887
|
+
const site = await workspaceSites.siteFor(workspace)
|
|
1888
|
+
return (await site.cache.byKey(key))?.url
|
|
1889
|
+
},
|
|
1890
|
+
})
|
|
1891
|
+
// Story 383: a change moved from one site to another, staged and applied as a workspace.
|
|
1892
|
+
const changeTransfer = createChangeTransfer({
|
|
1893
|
+
db,
|
|
1894
|
+
repository: { nodeState: core.schema.nodeState, nodeId: core.schema.nodeId },
|
|
1895
|
+
siteName: () => config.siteName,
|
|
1896
|
+
media: mediaFiles,
|
|
1897
|
+
schema: () => workspaceSchema,
|
|
1898
|
+
merge: () => core.operations.merge,
|
|
1899
|
+
})
|
|
1900
|
+
// Story 379: each workspace's site, kept on this node while it is looked at.
|
|
1901
|
+
const workspaceSites = createWorkspaceSites({
|
|
1902
|
+
db,
|
|
1903
|
+
environment: config.environment,
|
|
1904
|
+
nodeState: core.schema.nodeState,
|
|
1905
|
+
cacheOptions,
|
|
1906
|
+
processes: workspaceProcesses,
|
|
1907
|
+
componentsCacheDir: config.componentsCacheDir,
|
|
1908
|
+
componentsDir: config.componentsDir,
|
|
1909
|
+
snapshots,
|
|
1910
|
+
renderTimeoutMs: config.renderTimeoutMs,
|
|
1911
|
+
limit: config.workspaceSites,
|
|
1912
|
+
idleMs: config.workspaceSiteIdleMinutes * 60_000,
|
|
1913
|
+
})
|
|
1914
|
+
// Story 387: a property's value per environment.
|
|
1915
|
+
const environmentValuesApi = createEnvironmentValuesApi(db, {
|
|
1916
|
+
environment: () => config.environment,
|
|
1917
|
+
repository: { nodeState: core.schema.nodeState, nodeId: core.schema.nodeId },
|
|
1918
|
+
documents: () => core.operations.documents,
|
|
1919
|
+
readOnly: () => config.environmentValuesReadOnly || contentLocked(config),
|
|
1920
|
+
})
|
|
1921
|
+
// Story 381: every change to the site, and its revert.
|
|
1922
|
+
const changesApi = createChangesApi(db, {
|
|
1923
|
+
schema: () => workspaceSchema,
|
|
1924
|
+
nodeState: core.schema.nodeState,
|
|
1925
|
+
onReverted: () => core.cache.invalidate(),
|
|
1926
|
+
})
|
|
1720
1927
|
const previewLinkPath = `${paths.pluginPath}/api/preview-link`
|
|
1721
1928
|
const selfAudited = [
|
|
1722
1929
|
`${paths.pluginPath}/api/email/`,
|
|
1723
1930
|
`${paths.pluginPath}/api/schema-transfer/`,
|
|
1724
1931
|
viewAsPath,
|
|
1725
1932
|
cliTokensPath,
|
|
1933
|
+
workspacesPath,
|
|
1934
|
+
changesPath,
|
|
1726
1935
|
]
|
|
1727
1936
|
const bundleInstallPaths = new Set(
|
|
1728
1937
|
['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
|
|
@@ -1783,7 +1992,7 @@ export async function createServer(
|
|
|
1783
1992
|
'crombolo.node.role': config.role,
|
|
1784
1993
|
},
|
|
1785
1994
|
async (span) => {
|
|
1786
|
-
const response = await answer(request)
|
|
1995
|
+
const response = await inWorkspaceSite(request, () => answer(request))
|
|
1787
1996
|
// Readers are answered from the previous cache while it rebuilds (story
|
|
1788
1997
|
// 175), so a change is in it before the request that made it is answered.
|
|
1789
1998
|
if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
|
|
@@ -1968,6 +2177,269 @@ export async function createServer(
|
|
|
1968
2177
|
: {}
|
|
1969
2178
|
}
|
|
1970
2179
|
|
|
2180
|
+
// ---------------------------------------------------------------- workspace sites (story 379)
|
|
2181
|
+
|
|
2182
|
+
const workspaceHostsOf = () => workspaceHosts(config.workspacesHost)
|
|
2183
|
+
|
|
2184
|
+
/** Where a workspace's site is, for a request on `origin`: its host, or the site's own. */
|
|
2185
|
+
function workspaceOrigin(workspace: { key: string }, request: Request): URL {
|
|
2186
|
+
const origin = new URL(publicOrigin(request, config))
|
|
2187
|
+
const hosts = workspaceHostsOf()
|
|
2188
|
+
if (hosts) origin.host = hosts.hostFor(workspace.key, origin.host)
|
|
2189
|
+
return origin
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
/** A member's way in: a link with a single-use token, swapped for a cookie on first use. */
|
|
2193
|
+
async function workspaceOpenUrl(
|
|
2194
|
+
workspace: { key: string },
|
|
2195
|
+
principal: Principal,
|
|
2196
|
+
path: string,
|
|
2197
|
+
request?: Request,
|
|
2198
|
+
): Promise<string | undefined> {
|
|
2199
|
+
const standing = await previewUser(db, { key: principal.id })
|
|
2200
|
+
if (!standing) return undefined
|
|
2201
|
+
const token = signHandoff(previewSecret, {
|
|
2202
|
+
workspace: workspace.key,
|
|
2203
|
+
user: standing.id,
|
|
2204
|
+
stamp: standing.stamp,
|
|
2205
|
+
id: crypto.randomUUID(),
|
|
2206
|
+
expires: Date.now() + WORKSPACE_HANDOFF_SECONDS * 1000,
|
|
2207
|
+
})
|
|
2208
|
+
const url = new URL(
|
|
2209
|
+
path.startsWith('/') ? path : `/${path}`,
|
|
2210
|
+
request
|
|
2211
|
+
? workspaceOrigin(workspace, request)
|
|
2212
|
+
: publicOrigin(new Request('http://localhost/'), config),
|
|
2213
|
+
)
|
|
2214
|
+
url.searchParams.set(WORKSPACE_HANDOFF_PARAM, token)
|
|
2215
|
+
return url.toString()
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
/** Links a member makes for someone else to look at the workspace's site. */
|
|
2219
|
+
const workspaceLinks = {
|
|
2220
|
+
maxDays: () => config.workspaceLinkMaxDays,
|
|
2221
|
+
async make(workspace: { id: number; key: string }, principal: Principal, days: number) {
|
|
2222
|
+
const secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
|
|
2223
|
+
const link = await new WorkspaceLinkRepository(db).make({
|
|
2224
|
+
workspaceId: workspace.id,
|
|
2225
|
+
madeBy: principal.id,
|
|
2226
|
+
secretHash: linkSecretHash(secret),
|
|
2227
|
+
expiresAt: new Date(Date.now() + days * 86_400_000),
|
|
2228
|
+
})
|
|
2229
|
+
const url = new URL('/', publicOrigin(new Request('http://localhost/'), config))
|
|
2230
|
+
const hosts = workspaceHostsOf()
|
|
2231
|
+
if (hosts) url.host = hosts.hostFor(workspace.key, url.host)
|
|
2232
|
+
url.searchParams.set(WORKSPACE_LINK_PARAM, secret)
|
|
2233
|
+
return { id: link.id, url: url.toString(), secret, expiresAt: link.expiresAt.toISOString() }
|
|
2234
|
+
},
|
|
2235
|
+
list: (workspaceId: number) => new WorkspaceLinkRepository(db).of(workspaceId),
|
|
2236
|
+
withdraw: (workspaceId: number, id: number) =>
|
|
2237
|
+
new WorkspaceLinkRepository(db).withdraw(workspaceId, id),
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
/** The workspace an access names, if whoever holds it may still look: a member, or a link in date. */
|
|
2241
|
+
async function stillAllowed(access: WorkspaceAccess) {
|
|
2242
|
+
const repo = new WorkspaceRepository(db)
|
|
2243
|
+
const workspace = await repo.byKey(access.workspace)
|
|
2244
|
+
if (workspace?.state !== 'open') return undefined
|
|
2245
|
+
if ('user' in access) {
|
|
2246
|
+
const standing = await previewUser(db, { id: access.user })
|
|
2247
|
+
if (standing?.stamp !== access.stamp) return undefined
|
|
2248
|
+
const user = await db.q
|
|
2249
|
+
.selectFrom('user_account')
|
|
2250
|
+
.select('key')
|
|
2251
|
+
.where('id', '=', access.user)
|
|
2252
|
+
.execute()
|
|
2253
|
+
const key = user[0] ? normaliseUuid(String(user[0].key)) : ''
|
|
2254
|
+
return workspace.ownerKey === key || workspace.memberKeys.includes(key)
|
|
2255
|
+
? workspace
|
|
2256
|
+
: undefined
|
|
2257
|
+
}
|
|
2258
|
+
const link = await new WorkspaceLinkRepository(db).byId(access.link)
|
|
2259
|
+
if (!link || link.workspaceId !== workspace.id || link.withdrawnAt) return undefined
|
|
2260
|
+
if (link.expiresAt.getTime() <= Date.now() || config.workspaceLinkMaxDays <= 0) return undefined
|
|
2261
|
+
// A link goes with its maker, when they leave the workspace.
|
|
2262
|
+
return workspace.ownerKey === link.madeBy || workspace.memberKeys.includes(link.madeBy)
|
|
2263
|
+
? workspace
|
|
2264
|
+
: undefined
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
/** What a link's secret opens: its workspace, as access for a cookie. */
|
|
2268
|
+
async function accessFromLink(secret: string): Promise<WorkspaceAccess | undefined> {
|
|
2269
|
+
const link = await new WorkspaceLinkRepository(db).bySecretHash(linkSecretHash(secret))
|
|
2270
|
+
if (!link) return undefined
|
|
2271
|
+
const workspace = (await new WorkspaceRepository(db).all()).find(
|
|
2272
|
+
(w: { id: number }) => w.id === link.workspaceId,
|
|
2273
|
+
)
|
|
2274
|
+
if (!workspace) return undefined
|
|
2275
|
+
const access: WorkspaceAccess = {
|
|
2276
|
+
workspace: workspace.key,
|
|
2277
|
+
link: link.id,
|
|
2278
|
+
expires: Math.min(link.expiresAt.getTime(), Date.now() + WORKSPACE_COOKIE_SECONDS * 1000),
|
|
2279
|
+
}
|
|
2280
|
+
return (await stillAllowed(access)) ? access : undefined
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
/** A member's handoff, used once: access for a cookie, or nothing. */
|
|
2284
|
+
async function accessFromHandoff(token: string): Promise<WorkspaceAccess | undefined> {
|
|
2285
|
+
const claims = readHandoff(previewSecret, token)
|
|
2286
|
+
if (!claims) return undefined
|
|
2287
|
+
const standing = await previewUser(db, { id: claims.user })
|
|
2288
|
+
if (standing?.stamp !== claims.stamp) return undefined
|
|
2289
|
+
if (
|
|
2290
|
+
!(await new SingleUseTokens(db).use(
|
|
2291
|
+
WORKSPACE_HANDOFF_ISSUER,
|
|
2292
|
+
claims.id,
|
|
2293
|
+
new Date(claims.expires),
|
|
2294
|
+
))
|
|
2295
|
+
)
|
|
2296
|
+
return undefined
|
|
2297
|
+
const access: WorkspaceAccess = {
|
|
2298
|
+
workspace: claims.workspace,
|
|
2299
|
+
user: claims.user,
|
|
2300
|
+
stamp: claims.stamp,
|
|
2301
|
+
expires: Date.now() + WORKSPACE_COOKIE_SECONDS * 1000,
|
|
2302
|
+
}
|
|
2303
|
+
return (await stillAllowed(access)) ? access : undefined
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
/**
|
|
2307
|
+
* A request on a workspace's host, or with a workspace's cookie on the site's
|
|
2308
|
+
* own: answered from that workspace's site, to a member or a link's holder, and
|
|
2309
|
+
* never kept or indexed. Anything else goes on as it was.
|
|
2310
|
+
*/
|
|
2311
|
+
async function inWorkspaceSite(
|
|
2312
|
+
request: Request,
|
|
2313
|
+
next: () => Promise<Response>,
|
|
2314
|
+
): Promise<Response> {
|
|
2315
|
+
if (!workspacesOn(config)) return next()
|
|
2316
|
+
const url = new URL(request.url)
|
|
2317
|
+
const path = url.pathname
|
|
2318
|
+
const delivery = path.startsWith(DELIVERY_API_PREFIX)
|
|
2319
|
+
if (
|
|
2320
|
+
!delivery &&
|
|
2321
|
+
(path === paths.backOfficePath ||
|
|
2322
|
+
path.startsWith(`${paths.backOfficePath}/`) ||
|
|
2323
|
+
path.startsWith('/umbraco/'))
|
|
2324
|
+
)
|
|
2325
|
+
return next()
|
|
2326
|
+
const hosts = workspaceHostsOf()
|
|
2327
|
+
const named = hosts?.parse(url.host)
|
|
2328
|
+
if (hosts && !named) return next()
|
|
2329
|
+
const handoff = url.searchParams.get(WORKSPACE_HANDOFF_PARAM)
|
|
2330
|
+
const linked = url.searchParams.get(WORKSPACE_LINK_PARAM)
|
|
2331
|
+
const header = request.headers.get(WORKSPACE_LINK_HEADER)
|
|
2332
|
+
const cookie = readCookie(request, WORKSPACE_COOKIE)
|
|
2333
|
+
if (!named && !handoff && !linked && !header && !cookie) return next()
|
|
2334
|
+
|
|
2335
|
+
// A token or a secret in the address is swapped for the cookie, and the address cleaned.
|
|
2336
|
+
if ((handoff || linked) && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
2337
|
+
const clean = new URL(url)
|
|
2338
|
+
clean.searchParams.delete(WORKSPACE_HANDOFF_PARAM)
|
|
2339
|
+
clean.searchParams.delete(WORKSPACE_LINK_PARAM)
|
|
2340
|
+
const headers = new Headers({
|
|
2341
|
+
location: `${clean.pathname}${clean.search}`,
|
|
2342
|
+
'cache-control': PRIVATE_NO_STORE,
|
|
2343
|
+
'referrer-policy': 'no-referrer',
|
|
2344
|
+
})
|
|
2345
|
+
const access = handoff
|
|
2346
|
+
? await accessFromHandoff(handoff)
|
|
2347
|
+
: await accessFromLink(linked as string)
|
|
2348
|
+
if (access && (!named || named.key === access.workspace))
|
|
2349
|
+
headers.set(
|
|
2350
|
+
'set-cookie',
|
|
2351
|
+
accessCookie(signAccess(previewSecret, access), config.secureCookies),
|
|
2352
|
+
)
|
|
2353
|
+
return new Response(null, { status: 303, headers })
|
|
2354
|
+
}
|
|
2355
|
+
const access = header
|
|
2356
|
+
? await accessFromLink(header)
|
|
2357
|
+
: cookie
|
|
2358
|
+
? readAccess(previewSecret, cookie)
|
|
2359
|
+
: undefined
|
|
2360
|
+
const workspace = access ? await stillAllowed(access) : undefined
|
|
2361
|
+
if (!workspace || (named && named.key !== workspace.key)) {
|
|
2362
|
+
// On a workspace's host a stranger sees nothing; on the site's own, Shared.
|
|
2363
|
+
if (!named) return next()
|
|
2364
|
+
return new Response('There is no such workspace, or it is not yours to see.', {
|
|
2365
|
+
status: 404,
|
|
2366
|
+
headers: {
|
|
2367
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
2368
|
+
'cache-control': PRIVATE_NO_STORE,
|
|
2369
|
+
'x-robots-tag': 'noindex, nofollow',
|
|
2370
|
+
},
|
|
2371
|
+
})
|
|
2372
|
+
}
|
|
2373
|
+
const site = await workspaceSites.siteFor({ id: workspace.id, key: workspace.key })
|
|
2374
|
+
const response = await workspaceSiteScope.run(site, async () => {
|
|
2375
|
+
if (path === '/robots.txt')
|
|
2376
|
+
return new Response('User-agent: *\nDisallow: /\n', {
|
|
2377
|
+
headers: { 'content-type': 'text/plain; charset=utf-8' },
|
|
2378
|
+
})
|
|
2379
|
+
if (path === '/sitemap.xml' || path.startsWith('/sitemap'))
|
|
2380
|
+
return new Response('Not Found', { status: 404 })
|
|
2381
|
+
// Its own stylesheets and scripts, as it has them (stories 377, 379).
|
|
2382
|
+
const area = path.startsWith('/css/')
|
|
2383
|
+
? { prefix: 'stylesheets/', at: '/css/', type: 'text/css; charset=utf-8' }
|
|
2384
|
+
: path.startsWith('/scripts/')
|
|
2385
|
+
? { prefix: 'scripts/', at: '/scripts/', type: 'text/javascript; charset=utf-8' }
|
|
2386
|
+
: undefined
|
|
2387
|
+
if (area) {
|
|
2388
|
+
const key = `${area.prefix}${decodeURIComponent(path.slice(area.at.length))}`
|
|
2389
|
+
const text = (await new WorkspaceFileRepository(db).files(workspace.id, area.prefix)).get(
|
|
2390
|
+
key,
|
|
2391
|
+
)
|
|
2392
|
+
if (text !== undefined)
|
|
2393
|
+
return new Response(text, { headers: { 'content-type': area.type } })
|
|
2394
|
+
}
|
|
2395
|
+
return next()
|
|
2396
|
+
})
|
|
2397
|
+
// Never kept, never indexed, never the same as Shared's.
|
|
2398
|
+
const headers = new Headers(response.headers)
|
|
2399
|
+
headers.set('cache-control', PRIVATE_NO_STORE)
|
|
2400
|
+
headers.set('x-robots-tag', 'noindex, nofollow')
|
|
2401
|
+
headers.delete('etag')
|
|
2402
|
+
headers.delete('last-modified')
|
|
2403
|
+
return new Response(response.body, {
|
|
2404
|
+
status: response.status,
|
|
2405
|
+
statusText: response.statusText,
|
|
2406
|
+
headers,
|
|
2407
|
+
})
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
/** Removes each file nothing in the site names any more: not a media item, a page, or a workspace. */
|
|
2411
|
+
async function removeUnnamedFiles(urls: readonly string[]): Promise<void> {
|
|
2412
|
+
for (const url of urls) {
|
|
2413
|
+
const named = await db.q
|
|
2414
|
+
.selectFrom('property_value')
|
|
2415
|
+
.select('id')
|
|
2416
|
+
.where((eb) =>
|
|
2417
|
+
eb.or([eb('varchar_value', 'like', `%${url}%`), eb('text_value', 'like', `%${url}%`)]),
|
|
2418
|
+
)
|
|
2419
|
+
.limit(1)
|
|
2420
|
+
.execute()
|
|
2421
|
+
const owned = await new MediaAccessRepository(db).byUrl([url])
|
|
2422
|
+
if (named.length === 0 && !owned) await mediaFiles.remove(url)
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
/** Whether a workspace's own values name a file (story 390). */
|
|
2427
|
+
async function heldByWorkspace(workspaceId: number, urls: readonly string[]): Promise<boolean> {
|
|
2428
|
+
for (const url of urls) {
|
|
2429
|
+
const rows = await db.q
|
|
2430
|
+
.selectFrom('property_value')
|
|
2431
|
+
.select('id')
|
|
2432
|
+
.where('workspace_id', '=', workspaceId)
|
|
2433
|
+
.where((eb) =>
|
|
2434
|
+
eb.or([eb('varchar_value', 'like', `%${url}%`), eb('text_value', 'like', `%${url}%`)]),
|
|
2435
|
+
)
|
|
2436
|
+
.limit(1)
|
|
2437
|
+
.execute()
|
|
2438
|
+
if (rows.length > 0) return true
|
|
2439
|
+
}
|
|
2440
|
+
return false
|
|
2441
|
+
}
|
|
2442
|
+
|
|
1971
2443
|
/** Story 368: a preview link for a page its person may read, audited as them. */
|
|
1972
2444
|
async function askForPreviewLink(request: Request): Promise<Response> {
|
|
1973
2445
|
if (request.method !== 'POST') return new Response(null, { status: 405 })
|
|
@@ -1976,6 +2448,7 @@ export async function createServer(
|
|
|
1976
2448
|
const asked = (await request.json().catch(() => ({}))) as {
|
|
1977
2449
|
document?: unknown
|
|
1978
2450
|
culture?: unknown
|
|
2451
|
+
workspace?: unknown
|
|
1979
2452
|
}
|
|
1980
2453
|
const document = typeof asked.document === 'string' ? asked.document : ''
|
|
1981
2454
|
const culture = typeof asked.culture === 'string' && asked.culture ? asked.culture : null
|
|
@@ -1985,6 +2458,20 @@ export async function createServer(
|
|
|
1985
2458
|
if (!standing || !(await canReadDocument(principal, document, nodeLookup)))
|
|
1986
2459
|
return Response.json({ title: 'You may not read this page' }, { status: 403 })
|
|
1987
2460
|
const key = normaliseUuid(document)
|
|
2461
|
+
// Story 379: a page in a workspace is looked at on the workspace's site.
|
|
2462
|
+
if (typeof asked.workspace === 'string' && UUID_PATTERN.test(asked.workspace)) {
|
|
2463
|
+
const workspace = await new WorkspaceRepository(db).byKey(asked.workspace)
|
|
2464
|
+
const me = normaliseUuid(principal.id)
|
|
2465
|
+
if (!workspace || (workspace.ownerKey !== me && !workspace.memberKeys.includes(me)))
|
|
2466
|
+
return Response.json({ title: 'There is no such workspace' }, { status: 404 })
|
|
2467
|
+
const shown = await cache.byKey(key, culture)
|
|
2468
|
+
const url = await workspaceOpenUrl(workspace, principal, shown?.url ?? '/', request)
|
|
2469
|
+
if (!url) return Response.json({ title: 'You may not read this page' }, { status: 403 })
|
|
2470
|
+
return Response.json(
|
|
2471
|
+
{ url, expiresAt: new Date(Date.now() + WORKSPACE_HANDOFF_SECONDS * 1000).toISOString() },
|
|
2472
|
+
{ headers: { 'cache-control': PRIVATE_NO_STORE } },
|
|
2473
|
+
)
|
|
2474
|
+
}
|
|
1988
2475
|
const page = await (await draftCache()).byKey(key, culture)
|
|
1989
2476
|
const published = await cache.byKey(key, culture)
|
|
1990
2477
|
const expires = Date.now() + PREVIEW_LINK_SECONDS * 1000
|
|
@@ -2408,9 +2895,9 @@ export async function createServer(
|
|
|
2408
2895
|
if (pathname === `${paths.pluginPath}/api/schema-import`) {
|
|
2409
2896
|
const principal = await authenticate(request)
|
|
2410
2897
|
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
2411
|
-
//
|
|
2412
|
-
// `document-type` write requires.
|
|
2413
|
-
if (!hasSection(principal, '
|
|
2898
|
+
// Structure: this applies type changes to the database, which is what every
|
|
2899
|
+
// `document-type` write requires (story 385).
|
|
2900
|
+
if (!hasSection(principal, 'structure')) return new Response('Forbidden', { status: 403 })
|
|
2414
2901
|
if (request.method !== 'GET' && request.method !== 'POST') {
|
|
2415
2902
|
return new Response('Method Not Allowed', { status: 405 })
|
|
2416
2903
|
}
|
|
@@ -2852,6 +3339,19 @@ export async function createServer(
|
|
|
2852
3339
|
: Response.json(outcome, { status: outcome.status })
|
|
2853
3340
|
}
|
|
2854
3341
|
|
|
3342
|
+
// Story 389: whether the Users section is the directory's, and where it links each user.
|
|
3343
|
+
if (pathname === usersManagedPath && request.method === 'GET') {
|
|
3344
|
+
const principal = await authenticate(request)
|
|
3345
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3346
|
+
const managed = usersManaged(config)
|
|
3347
|
+
const template = managed ? config.users.managedAt : undefined
|
|
3348
|
+
const key = new URL(request.url).searchParams.get('user')
|
|
3349
|
+
if (!key) return Response.json({ managed, linked: template !== undefined })
|
|
3350
|
+
if (!template || !hasSection(principal, 'users')) return Response.json({ href: null })
|
|
3351
|
+
const user = await new UserRepository(db).byKey(key).catch(() => undefined)
|
|
3352
|
+
return Response.json({ href: user ? managedHref(template, user) : null })
|
|
3353
|
+
}
|
|
3354
|
+
|
|
2855
3355
|
// Story 351: a person's command-line tokens, and an administrator's view of anyone's.
|
|
2856
3356
|
if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
|
|
2857
3357
|
const principal = await authenticate(request)
|
|
@@ -2870,6 +3370,51 @@ export async function createServer(
|
|
|
2870
3370
|
)
|
|
2871
3371
|
}
|
|
2872
3372
|
|
|
3373
|
+
// Story 375: workspaces, opened, listed, shared and discarded.
|
|
3374
|
+
if (pathname === workspacesPath || pathname.startsWith(`${workspacesPath}/`)) {
|
|
3375
|
+
const principal = await authenticate(request)
|
|
3376
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3377
|
+
return workspacesApi.handle(
|
|
3378
|
+
request,
|
|
3379
|
+
principal,
|
|
3380
|
+
pathname.slice(workspacesPath.length),
|
|
3381
|
+
clientAddress(request),
|
|
3382
|
+
)
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3385
|
+
// Story 381: the site's changes, their files' versions, and reverting one.
|
|
3386
|
+
if (pathname === changesPath || pathname.startsWith(`${changesPath}/`)) {
|
|
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: 'Changes are for people who look after content.' },
|
|
3392
|
+
{ status: 403 },
|
|
3393
|
+
)
|
|
3394
|
+
return changesApi.handle(
|
|
3395
|
+
request,
|
|
3396
|
+
principal,
|
|
3397
|
+
pathname.slice(changesPath.length),
|
|
3398
|
+
clientAddress(request),
|
|
3399
|
+
)
|
|
3400
|
+
}
|
|
3401
|
+
|
|
3402
|
+
// Story 387: a property's value per environment, edited beside its field.
|
|
3403
|
+
if (pathname === environmentValuesPath || pathname.startsWith(`${environmentValuesPath}/`)) {
|
|
3404
|
+
const principal = await authenticate(request)
|
|
3405
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3406
|
+
if (!hasSection(principal, 'content'))
|
|
3407
|
+
return Response.json(
|
|
3408
|
+
{ message: 'Values per environment are for people who look after content.' },
|
|
3409
|
+
{ status: 403 },
|
|
3410
|
+
)
|
|
3411
|
+
return environmentValuesApi.handle(
|
|
3412
|
+
request,
|
|
3413
|
+
principal,
|
|
3414
|
+
pathname.slice(environmentValuesPath.length),
|
|
3415
|
+
)
|
|
3416
|
+
}
|
|
3417
|
+
|
|
2873
3418
|
// Story 368: a link that opens one page's draft in any browser.
|
|
2874
3419
|
if (pathname === previewLinkPath) return askForPreviewLink(request)
|
|
2875
3420
|
|
|
@@ -2965,373 +3510,396 @@ export async function createServer(
|
|
|
2965
3510
|
const principal = await authenticate(request)
|
|
2966
3511
|
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
2967
3512
|
const action = pathname.slice(`${paths.pluginPath}/api/forms`.length).replace(/^\//, '')
|
|
2968
|
-
//
|
|
2969
|
-
//
|
|
2970
|
-
const
|
|
2971
|
-
|
|
2972
|
-
|
|
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
|
-
})
|
|
3513
|
+
// Story 392: in a workspace, its copy of the forms; looking up choices is a read.
|
|
3514
|
+
// Story 392: a site that takes its content by change shows its forms read-only.
|
|
3515
|
+
const shared = {
|
|
3516
|
+
schemaDir: config.schemaDir,
|
|
3517
|
+
writable: config.schemaWritable && !contentLocked(config),
|
|
3005
3518
|
}
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
definitions.
|
|
3020
|
-
form.
|
|
3021
|
-
|
|
3519
|
+
const formsIn = async (place: SchemaPlace): Promise<Response> => {
|
|
3520
|
+
// Through the registry the renderer uses, so the designer and a render
|
|
3521
|
+
// cannot disagree; a save invalidates it rather than waiting out the memo.
|
|
3522
|
+
const definitions = place.inWorkspace
|
|
3523
|
+
? (loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).set.forms ?? [])
|
|
3524
|
+
: forms.all()
|
|
3525
|
+
|
|
3526
|
+
// A definition is structure, like a content type: anyone who may open the
|
|
3527
|
+
// section may read it, and the picker needs it in the Content section too.
|
|
3528
|
+
if (action === '' && request.method === 'GET') {
|
|
3529
|
+
const files = loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).files
|
|
3530
|
+
const file = (alias: string) => files.get(`form:${alias}`)
|
|
3531
|
+
return Response.json({
|
|
3532
|
+
items: definitions.map((form) => ({
|
|
3533
|
+
...formSummary(form, formTypes.types),
|
|
3534
|
+
folder: file(form.alias)
|
|
3535
|
+
? folderOf(place.schemaDir, 'forms', file(form.alias) as string)
|
|
3536
|
+
: '',
|
|
3537
|
+
})),
|
|
3538
|
+
folders: foldersIn(place.schemaDir, 'forms'),
|
|
3539
|
+
readOnlyBecause: !place.writable
|
|
3540
|
+
? 'site'
|
|
3541
|
+
: principal.isAdmin || principal.permissions.includes(FormPermissions.Manage)
|
|
3542
|
+
? null
|
|
3543
|
+
: 'permission',
|
|
3544
|
+
})
|
|
3545
|
+
}
|
|
3546
|
+
// Hyphenated, so no form alias (letters and digits) can be mistaken for it.
|
|
3547
|
+
if (action === 'available-types' && request.method === 'GET')
|
|
3548
|
+
return Response.json(describeFormTypes(formTypes.types))
|
|
3549
|
+
// The Library forms (story 239), for a page's form picker and the entries filter.
|
|
3550
|
+
if (action === 'library-forms' && request.method === 'GET') {
|
|
3551
|
+
const known = new Map(definitions.map((form) => [form.key ?? form.alias, form]))
|
|
3552
|
+
return Response.json({
|
|
3553
|
+
items: (await listLibraryForms(db)).map((item) => ({
|
|
3554
|
+
...item,
|
|
3555
|
+
formAlias: known.get(item.formKey)?.alias ?? null,
|
|
3556
|
+
formName: known.get(item.formKey)?.name ?? null,
|
|
3557
|
+
})),
|
|
3558
|
+
})
|
|
3559
|
+
}
|
|
3560
|
+
// Which content types are made from a form, for the note in their editor.
|
|
3561
|
+
if (action === 'library-types' && request.method === 'GET')
|
|
3562
|
+
return Response.json({
|
|
3563
|
+
items: definitions.map((form) => ({
|
|
3564
|
+
typeKey: libraryFormTypeKey(libraryFormId(form)),
|
|
3565
|
+
formName: form.name,
|
|
3566
|
+
})),
|
|
3567
|
+
})
|
|
3568
|
+
// The designer's "E-mail design" picker.
|
|
3569
|
+
if (action === 'email-templates' && request.method === 'GET')
|
|
3570
|
+
return Response.json({
|
|
3571
|
+
items: listEmailTemplates(
|
|
3572
|
+
config.componentsDir,
|
|
3573
|
+
definitions.flatMap((form) =>
|
|
3574
|
+
form.workflows.flatMap((workflow) =>
|
|
3575
|
+
typeof workflow.settings.template === 'string'
|
|
3576
|
+
? [workflow.settings.template]
|
|
3577
|
+
: [],
|
|
3578
|
+
),
|
|
3022
3579
|
),
|
|
3023
3580
|
),
|
|
3024
|
-
)
|
|
3025
|
-
})
|
|
3581
|
+
})
|
|
3026
3582
|
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
if (
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3583
|
+
const entries = new FormEntryRepository(db)
|
|
3584
|
+
const byKey = formsByKey(definitions)
|
|
3585
|
+
// Submissions are personal data, so reading them asks for more than a
|
|
3586
|
+
// session. Four verbs, because designing a form and reading what people
|
|
3587
|
+
// sent it are different jobs (`docs/forms.md`).
|
|
3588
|
+
const may = (verb: string) => principal.isAdmin || principal.permissions.includes(verb)
|
|
3589
|
+
const formFiles = {
|
|
3590
|
+
schemaDir: place.schemaDir,
|
|
3591
|
+
writable: place.writable,
|
|
3592
|
+
formTypes: formTypes.types,
|
|
3593
|
+
componentAliases: () => componentAliasesIn(config.componentsDir, config.siteDir),
|
|
3594
|
+
onChanged:
|
|
3595
|
+
!place.inWorkspace && config.schemaStore
|
|
3596
|
+
? async () => {
|
|
3597
|
+
await publishSchema(config.schemaStore as SchemaStore, place.schemaDir)
|
|
3598
|
+
}
|
|
3599
|
+
: undefined,
|
|
3600
|
+
}
|
|
3601
|
+
// Every dictionary item in the default language, for the designer to suggest.
|
|
3602
|
+
if (action === 'words' && request.method === 'GET') {
|
|
3603
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3604
|
+
const entries = await cache.dictionaryEntries(null)
|
|
3605
|
+
return Response.json({
|
|
3606
|
+
words: Object.entries(entries).map(([name, text]) => ({ name, text })),
|
|
3607
|
+
})
|
|
3608
|
+
}
|
|
3052
3609
|
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3079
|
-
|
|
3080
|
-
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3610
|
+
const maySeeEntries = may(FormPermissions.EntriesView)
|
|
3611
|
+
const mayManageEntries = may(FormPermissions.EntriesManage)
|
|
3612
|
+
// The group alias still counts: `sensitiveData` is how Umbraco carries
|
|
3613
|
+
// this and how members already work, so both routes to it are honoured.
|
|
3614
|
+
const maySeeSensitive =
|
|
3615
|
+
may(FormPermissions.EntriesSensitive) || hasAccessToSensitiveData(principal.groups)
|
|
3616
|
+
|
|
3617
|
+
const entryMatch = /^entries\/([^/]+)(?:\/(state))?$/.exec(action)
|
|
3618
|
+
if (entryMatch) {
|
|
3619
|
+
if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
|
|
3620
|
+
const id = decodeURIComponent(entryMatch[1] as string)
|
|
3621
|
+
if (entryMatch[2] === 'state' && request.method === 'POST') {
|
|
3622
|
+
if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
|
|
3623
|
+
const body = (await request.json().catch(() => ({}))) as { state?: unknown }
|
|
3624
|
+
const next = parseEntryState(typeof body.state === 'string' ? body.state : null)
|
|
3625
|
+
if (!next) return new Response('Bad Request', { status: 400 })
|
|
3626
|
+
const updated = await entries.setState(id, next)
|
|
3627
|
+
if (!updated) return new Response('Not Found', { status: 404 })
|
|
3628
|
+
// Approval is the other trigger: a workflow declared `on = "approve"`
|
|
3629
|
+
// runs now, from the values the entry holds.
|
|
3630
|
+
if (next === 'approved') {
|
|
3631
|
+
const form = byKey.get(updated.formKey)
|
|
3632
|
+
const onApprove =
|
|
3633
|
+
form?.workflows.filter((workflow) => workflow.on === 'approve') ?? []
|
|
3634
|
+
// Through a Library form: its recipients as they are now (story 239).
|
|
3635
|
+
const recipients = updated.libraryKey
|
|
3636
|
+
? (await cache.libraryForm(updated.libraryKey))?.library?.recipients
|
|
3637
|
+
: undefined
|
|
3638
|
+
if (onApprove.length > 0)
|
|
3639
|
+
await new FormWorkflowRepository(db).enqueue(
|
|
3640
|
+
onApprove.map((workflow) => ({
|
|
3641
|
+
formKey: updated.formKey,
|
|
3642
|
+
formAlias: updated.formAlias,
|
|
3643
|
+
workflowName: workflow.name,
|
|
3644
|
+
workflowType: workflow.type,
|
|
3645
|
+
runOn: workflow.on,
|
|
3646
|
+
entryId: updated.id,
|
|
3647
|
+
payload: updated.values.map((value) => ({
|
|
3648
|
+
fieldAlias: value.fieldAlias,
|
|
3649
|
+
values: value.values,
|
|
3650
|
+
})),
|
|
3651
|
+
...(recipients ? { recipients } : {}),
|
|
3092
3652
|
})),
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3653
|
+
)
|
|
3654
|
+
}
|
|
3655
|
+
log.info('{user} set form entry {id} to {state}', {
|
|
3656
|
+
user: principal.email,
|
|
3657
|
+
id,
|
|
3658
|
+
state: next,
|
|
3659
|
+
})
|
|
3660
|
+
return Response.json({ id: updated.id, state: updated.state })
|
|
3096
3661
|
}
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
id,
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3662
|
+
if (request.method === 'DELETE') {
|
|
3663
|
+
if (!mayManageEntries) return new Response('Forbidden', { status: 403 })
|
|
3664
|
+
if (!(await entries.remove(id))) return new Response('Not Found', { status: 404 })
|
|
3665
|
+
log.info('{user} deleted form entry {id}', { user: principal.email, id })
|
|
3666
|
+
return new Response(null, { status: 200 })
|
|
3667
|
+
}
|
|
3668
|
+
if (request.method === 'GET') {
|
|
3669
|
+
const entry = await entries.byId(id)
|
|
3670
|
+
if (!entry) return new Response('Not Found', { status: 404 })
|
|
3671
|
+
return Response.json({
|
|
3672
|
+
...entry,
|
|
3673
|
+
values: redactSensitive(entry, byKey.get(entry.formKey), maySeeSensitive),
|
|
3674
|
+
})
|
|
3675
|
+
}
|
|
3676
|
+
return new Response('Method Not Allowed', { status: 405 })
|
|
3103
3677
|
}
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3678
|
+
|
|
3679
|
+
const csvMatch = /^([^/]+)\/entries\.csv$/.exec(action)
|
|
3680
|
+
if (csvMatch && request.method === 'GET') {
|
|
3681
|
+
if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
|
|
3682
|
+
const key = decodeURIComponent(csvMatch[1] as string)
|
|
3683
|
+
const form = byKey.get(key)
|
|
3684
|
+
if (!form) return new Response('Not Found', { status: 404 })
|
|
3685
|
+
const page = await entries.list({ formKey: key, take: 10_000 })
|
|
3686
|
+
const result = entriesCsv(await cache.resolveForm(form), page.items, {
|
|
3687
|
+
includeSensitive: maySeeSensitive,
|
|
3688
|
+
types: formTypes.types,
|
|
3689
|
+
})
|
|
3690
|
+
if (!result.ok)
|
|
3691
|
+
return new Response(result.reason, {
|
|
3692
|
+
status: 403,
|
|
3693
|
+
headers: { 'content-type': 'text/plain; charset=utf-8' },
|
|
3694
|
+
})
|
|
3695
|
+
return new Response(result.csv, {
|
|
3696
|
+
headers: {
|
|
3697
|
+
'content-type': 'text/csv; charset=utf-8',
|
|
3698
|
+
'content-disposition': `attachment; filename="${result.fileName}"`,
|
|
3699
|
+
},
|
|
3700
|
+
})
|
|
3109
3701
|
}
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3702
|
+
|
|
3703
|
+
const listMatch = /^([^/]+)\/entries$/.exec(action)
|
|
3704
|
+
if (listMatch && request.method === 'GET') {
|
|
3705
|
+
if (!maySeeEntries) return new Response('Forbidden', { status: 403 })
|
|
3706
|
+
const key = decodeURIComponent(listMatch[1] as string)
|
|
3707
|
+
const since = url.searchParams.get('from')
|
|
3708
|
+
const until = url.searchParams.get('to')
|
|
3709
|
+
// `library=none` for the entries that came through no Library form.
|
|
3710
|
+
const library = url.searchParams.get('library')
|
|
3711
|
+
const page = await entries.list({
|
|
3712
|
+
formKey: key,
|
|
3713
|
+
...(library ? { libraryKey: library === 'none' ? null : library } : {}),
|
|
3714
|
+
state: parseEntryState(url.searchParams.get('state')),
|
|
3715
|
+
culture: url.searchParams.get('language') || undefined,
|
|
3716
|
+
from: since ? new Date(since) : undefined,
|
|
3717
|
+
to: until ? new Date(until) : undefined,
|
|
3718
|
+
search: url.searchParams.get('search') ?? undefined,
|
|
3719
|
+
includeSpam: url.searchParams.get('includeSpam') === 'true',
|
|
3720
|
+
skip: Number(url.searchParams.get('skip') ?? 0) || 0,
|
|
3721
|
+
take: Number(url.searchParams.get('take') ?? 100) || 100,
|
|
3722
|
+
})
|
|
3723
|
+
const form = byKey.get(key)
|
|
3113
3724
|
return Response.json({
|
|
3114
|
-
|
|
3115
|
-
|
|
3725
|
+
total: page.total,
|
|
3726
|
+
languages: await entries.languages(key),
|
|
3727
|
+
items: page.items.map((entry) => ({
|
|
3728
|
+
...entry,
|
|
3729
|
+
values: redactSensitive(entry, form, maySeeSensitive),
|
|
3730
|
+
})),
|
|
3116
3731
|
})
|
|
3117
3732
|
}
|
|
3118
|
-
return new Response('Method Not Allowed', { status: 405 })
|
|
3119
|
-
}
|
|
3120
3733
|
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
const
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3734
|
+
// A send-to-URL workflow's secret header (story 304): sealed here, never
|
|
3735
|
+
// in the form's file, and never shown back. Set on any site, schema
|
|
3736
|
+
// writable or not, since it is the site's own and not the form's.
|
|
3737
|
+
const secretMatch = /^([^/]+)\/workflows\/([^/]+)\/secrets\/([^/]+)$/.exec(action)
|
|
3738
|
+
if (secretMatch && (request.method === 'PUT' || request.method === 'DELETE')) {
|
|
3739
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3740
|
+
const [, formKey, workflowKey, header] = secretMatch.map((part) =>
|
|
3741
|
+
decodeURIComponent(part),
|
|
3742
|
+
) as [string, string, string, string]
|
|
3743
|
+
const form = byKey.get(formKey)
|
|
3744
|
+
const workflow = form?.workflows.find((candidate) => candidate.key === workflowKey)
|
|
3745
|
+
const headers = workflow?.settings.headers as Record<string, unknown> | undefined
|
|
3746
|
+
if (!form?.key || !workflow || !isSecretHeader(headers?.[header]))
|
|
3747
|
+
return Response.json(
|
|
3748
|
+
{ message: 'The form names no such secret header; save the form first.' },
|
|
3749
|
+
{ status: 404 },
|
|
3750
|
+
)
|
|
3751
|
+
const secrets = new FormWorkflowSecretRepository(db)
|
|
3752
|
+
let set: { sealed: string; url: string } | undefined
|
|
3753
|
+
if (request.method === 'PUT') {
|
|
3754
|
+
const body = (await request.json().catch(() => ({}))) as { value?: unknown }
|
|
3755
|
+
if (typeof body.value !== 'string' || body.value === '')
|
|
3756
|
+
return Response.json({ message: 'Give the header a value.' }, { status: 400 })
|
|
3757
|
+
const key = usableSecretKey(config.secretKey)
|
|
3758
|
+
if (!key)
|
|
3759
|
+
return Response.json(
|
|
3760
|
+
{
|
|
3761
|
+
message: `Keeping a secret header needs ${SECRET_KEY_VARIABLE} set on the server.`,
|
|
3762
|
+
},
|
|
3763
|
+
{ status: 409 },
|
|
3764
|
+
)
|
|
3765
|
+
set = { sealed: sealSecret(body.value, key), url: String(workflow.settings.url ?? '') }
|
|
3766
|
+
}
|
|
3767
|
+
await secrets.set(form.key, workflowKey, header, set, principal.name ?? null)
|
|
3768
|
+
await recordAudit(db, {
|
|
3769
|
+
category: 'settings',
|
|
3770
|
+
action: set ? 'secret header set' : 'secret header removed',
|
|
3771
|
+
source: 'request',
|
|
3772
|
+
userKey: principal.id,
|
|
3773
|
+
userName: principal.name,
|
|
3774
|
+
entityType: 'form',
|
|
3775
|
+
entityKey: form.key,
|
|
3776
|
+
entityName: form.name,
|
|
3777
|
+
detail: `${workflow.name}: ${header}`,
|
|
3778
|
+
...clientAddress(request),
|
|
3136
3779
|
})
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
'content-type': 'text/csv; charset=utf-8',
|
|
3140
|
-
'content-disposition': `attachment; filename="${result.fileName}"`,
|
|
3141
|
-
},
|
|
3142
|
-
})
|
|
3143
|
-
}
|
|
3780
|
+
return Response.json({ ok: true })
|
|
3781
|
+
}
|
|
3144
3782
|
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
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
|
-
}
|
|
3783
|
+
if (action && request.method === 'GET') {
|
|
3784
|
+
const form = byKey.get(decodeURIComponent(action))
|
|
3785
|
+
if (!form) return new Response('Not Found', { status: 404 })
|
|
3786
|
+
// Which secret headers are set for the address each workflow sends to, never their values.
|
|
3787
|
+
const secrets: { workflow: string; header: string; set: boolean }[] = []
|
|
3788
|
+
for (const workflow of form.workflows) {
|
|
3789
|
+
const headers = workflow.settings.headers as Record<string, unknown> | undefined
|
|
3790
|
+
const named = Object.keys(headers ?? {}).filter((name) =>
|
|
3791
|
+
isSecretHeader(headers?.[name]),
|
|
3792
|
+
)
|
|
3793
|
+
if (named.length === 0 || !workflow.key || !form.key) continue
|
|
3794
|
+
const kept = await new FormWorkflowSecretRepository(db).of(form.key, workflow.key)
|
|
3795
|
+
for (const header of named)
|
|
3796
|
+
secrets.push({
|
|
3797
|
+
workflow: workflow.key,
|
|
3798
|
+
header,
|
|
3799
|
+
set: kept.get(header)?.url === workflow.settings.url,
|
|
3800
|
+
})
|
|
3801
|
+
}
|
|
3802
|
+
// The whole definition, which is what the designer edits.
|
|
3803
|
+
return Response.json({ ...formDetail(form), definition: form, secrets })
|
|
3804
|
+
}
|
|
3175
3805
|
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
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 },
|
|
3806
|
+
// What a choice source offers now, in the default language, for the
|
|
3807
|
+
// designer to show beside the source it is editing.
|
|
3808
|
+
if (action === 'choices' && request.method === 'POST') {
|
|
3809
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3810
|
+
const body = (await request.json().catch(() => ({}))) as { source?: unknown }
|
|
3811
|
+
const source = body.source as { kind?: unknown; parent?: unknown } | undefined
|
|
3812
|
+
if (
|
|
3813
|
+
!source ||
|
|
3814
|
+
!CHOICE_SOURCE_KINDS.includes(source.kind as ChoiceSourceKind) ||
|
|
3815
|
+
typeof source.parent !== 'string'
|
|
3192
3816
|
)
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
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 ?? '') }
|
|
3817
|
+
return new Response('Bad Request', { status: 400 })
|
|
3818
|
+
const options = await cache.choiceOptions({
|
|
3819
|
+
kind: source.kind as ChoiceSourceKind,
|
|
3820
|
+
parent: source.parent,
|
|
3821
|
+
})
|
|
3822
|
+
return Response.json({ options })
|
|
3208
3823
|
}
|
|
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
3824
|
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
if (
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3825
|
+
// Designing a form is a developer's job, so it is its own verb rather
|
|
3826
|
+
// than something an entry reader can do.
|
|
3827
|
+
if (action === 'tree-folders' || action === 'tree-move') {
|
|
3828
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3829
|
+
const response = await folderAction('forms', action, request, {
|
|
3830
|
+
...formFiles,
|
|
3831
|
+
file: (alias) =>
|
|
3832
|
+
loadSchemaDirectory(place.schemaDir, { formTypes: formTypes.types }).files.get(
|
|
3833
|
+
`form:${alias}`,
|
|
3834
|
+
),
|
|
3835
|
+
})
|
|
3836
|
+
if (response) return response
|
|
3837
|
+
}
|
|
3838
|
+
if (request.method === 'POST' || request.method === 'PUT') {
|
|
3839
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3840
|
+
const body = await request.json().catch(() => ({}))
|
|
3841
|
+
const folder = url.searchParams.get('folder') ?? undefined
|
|
3842
|
+
const refused = await refusedSendAddresses(coerceForm(body), config.allowPrivateAddresses)
|
|
3843
|
+
if (refused.length > 0)
|
|
3844
|
+
return Response.json({ status: 'invalid', problems: refused }, { status: 400 })
|
|
3845
|
+
const written = await saveForm(coerceForm(body), { ...formFiles, folder })
|
|
3846
|
+
if (!written.ok) {
|
|
3847
|
+
log.warning('{user} could not save a form: {detail}', {
|
|
3848
|
+
user: principal.email,
|
|
3849
|
+
detail: written.problems.map((problem) => problem.message).join('; '),
|
|
3240
3850
|
})
|
|
3851
|
+
return Response.json(
|
|
3852
|
+
{ status: written.status, problems: written.problems },
|
|
3853
|
+
{ status: written.status === 'readOnly' ? 409 : 400 },
|
|
3854
|
+
)
|
|
3855
|
+
}
|
|
3856
|
+
// The memo would otherwise hold the old definition for a second, which
|
|
3857
|
+
// is exactly long enough for the designer to reload and see it.
|
|
3858
|
+
if (!place.inWorkspace) {
|
|
3859
|
+
forms.invalidate()
|
|
3860
|
+
await ensureFormLibraryTypes(db, forms.all())
|
|
3861
|
+
cache.invalidate()
|
|
3862
|
+
}
|
|
3863
|
+
const saved = coerceForm(body)
|
|
3864
|
+
if (saved.key && !place.inWorkspace)
|
|
3865
|
+
await new FormWorkflowSecretRepository(db).forget(
|
|
3866
|
+
saved.key,
|
|
3867
|
+
saved.workflows.flatMap((workflow) => (workflow.key ? [workflow.key] : [])),
|
|
3868
|
+
)
|
|
3869
|
+
log.info('{user} saved the form {form}', {
|
|
3870
|
+
user: principal.email,
|
|
3871
|
+
form: coerceForm(body).alias,
|
|
3872
|
+
})
|
|
3873
|
+
return Response.json({ ok: true })
|
|
3241
3874
|
}
|
|
3242
|
-
// The whole definition, which is what the designer edits.
|
|
3243
|
-
return Response.json({ ...formDetail(form), definition: form, secrets })
|
|
3244
|
-
}
|
|
3245
3875
|
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
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}', {
|
|
3876
|
+
if (action && request.method === 'DELETE') {
|
|
3877
|
+
if (!may(FormPermissions.Manage)) return new Response('Forbidden', { status: 403 })
|
|
3878
|
+
const form = byKey.get(decodeURIComponent(action))
|
|
3879
|
+
if (!form) return new Response('Not Found', { status: 404 })
|
|
3880
|
+
const removed = await deleteForm(form.alias, formFiles)
|
|
3881
|
+
if (!removed.ok)
|
|
3882
|
+
return Response.json(
|
|
3883
|
+
{ status: removed.status, problems: removed.problems },
|
|
3884
|
+
{ status: removed.status === 'readOnly' ? 409 : 404 },
|
|
3885
|
+
)
|
|
3886
|
+
if (!place.inWorkspace) {
|
|
3887
|
+
forms.invalidate()
|
|
3888
|
+
await ensureFormLibraryTypes(db, forms.all())
|
|
3889
|
+
cache.invalidate()
|
|
3890
|
+
}
|
|
3891
|
+
if (form.key && !place.inWorkspace)
|
|
3892
|
+
await new FormWorkflowSecretRepository(db).forget(form.key)
|
|
3893
|
+
log.info('{user} deleted the form {form}; its entries are kept', {
|
|
3288
3894
|
user: principal.email,
|
|
3289
|
-
|
|
3895
|
+
form: form.alias,
|
|
3290
3896
|
})
|
|
3291
|
-
return Response.json(
|
|
3292
|
-
{ status: written.status, problems: written.problems },
|
|
3293
|
-
{ status: written.status === 'readOnly' ? 409 : 400 },
|
|
3294
|
-
)
|
|
3897
|
+
return Response.json({ ok: true })
|
|
3295
3898
|
}
|
|
3296
|
-
|
|
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 })
|
|
3899
|
+
return new Response('Not Found', { status: 404 })
|
|
3333
3900
|
}
|
|
3334
|
-
|
|
3901
|
+
if (action === 'choices') return formsIn({ ...shared, inWorkspace: false })
|
|
3902
|
+
return inDesignerPlace(request, principal, 'CromboloFormDesigner', shared, formsIn)
|
|
3335
3903
|
}
|
|
3336
3904
|
|
|
3337
3905
|
// Non-contract: what the Changes dashboard and the read-only banner read.
|
|
@@ -3466,23 +4034,40 @@ export async function createServer(
|
|
|
3466
4034
|
return new Response('Forbidden', { status: 403 })
|
|
3467
4035
|
const approvals = managementDeps.approvals as Approvals | undefined
|
|
3468
4036
|
if (!approvals) return new Response('Not Found', { status: 404 })
|
|
3469
|
-
const
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
{
|
|
4037
|
+
const rest = pathname.slice(`${paths.pluginPath}/api/approvals/`.length)
|
|
4038
|
+
const approvalsIn = async (place: SchemaPlace) =>
|
|
4039
|
+
(await handleApprovalsApi(request, rest, {
|
|
3473
4040
|
db,
|
|
3474
4041
|
approvals,
|
|
3475
4042
|
principal,
|
|
3476
|
-
schemaDir:
|
|
3477
|
-
writable:
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
4043
|
+
schemaDir: place.schemaDir,
|
|
4044
|
+
writable: place.writable,
|
|
4045
|
+
inWorkspace: place.inWorkspace,
|
|
4046
|
+
onChanged:
|
|
4047
|
+
config.schemaStore && !place.inWorkspace
|
|
4048
|
+
? async () => {
|
|
4049
|
+
await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
|
|
4050
|
+
}
|
|
4051
|
+
: undefined,
|
|
4052
|
+
})) ?? new Response('Not Found', { status: 404 })
|
|
4053
|
+
// Story 392: setting up a workflow in a workspace changes its copy; deciding is Shared's.
|
|
4054
|
+
const response = rest.startsWith('workflows')
|
|
4055
|
+
? await inDesignerPlace(
|
|
4056
|
+
request,
|
|
4057
|
+
principal,
|
|
4058
|
+
'CromboloWorkflowDesigner',
|
|
4059
|
+
{
|
|
4060
|
+
schemaDir: config.schemaDir,
|
|
4061
|
+
writable: config.schemaWritable && !contentLocked(config),
|
|
4062
|
+
},
|
|
4063
|
+
approvalsIn,
|
|
4064
|
+
)
|
|
4065
|
+
: await approvalsIn({
|
|
4066
|
+
schemaDir: config.schemaDir,
|
|
4067
|
+
writable: config.schemaWritable,
|
|
4068
|
+
inWorkspace: false,
|
|
4069
|
+
})
|
|
4070
|
+
if (response.status !== 404) {
|
|
3486
4071
|
if (request.method !== 'GET')
|
|
3487
4072
|
log.info('{user} {verb} on approvals: {status}', {
|
|
3488
4073
|
user: principal.email,
|
|
@@ -3773,7 +4358,14 @@ export async function createServer(
|
|
|
3773
4358
|
const owners = new MediaAccessRepository(db)
|
|
3774
4359
|
const urls = [`/media/${key}`, pathname]
|
|
3775
4360
|
const owner = await owners.byUrl(urls)
|
|
3776
|
-
|
|
4361
|
+
// Story 390: on a workspace's site, a file only its own media names is served too;
|
|
4362
|
+
// on Shared's, an unmerged file is as missing as one that is not there.
|
|
4363
|
+
const site = workspaceSiteScope.getStore()
|
|
4364
|
+
if (
|
|
4365
|
+
!owner &&
|
|
4366
|
+
!(await owners.ownedElsewhere(urls)) &&
|
|
4367
|
+
!(site?.workspace && (await heldByWorkspace(site.workspace.id, urls)))
|
|
4368
|
+
)
|
|
3777
4369
|
return new Response('Not Found', { status: 404 })
|
|
3778
4370
|
const isProtected = owner ? mediaAccess.isProtected(owner) : false
|
|
3779
4371
|
if (owner && isProtected && !(await mediaAccess.mayRead(request, owner)))
|
|
@@ -4609,8 +5201,16 @@ export async function createServer(
|
|
|
4609
5201
|
paths,
|
|
4610
5202
|
db,
|
|
4611
5203
|
auth,
|
|
4612
|
-
|
|
4613
|
-
|
|
5204
|
+
// The shared ones: a workspace's site is only ever reached through a request.
|
|
5205
|
+
cache: sharedCache,
|
|
5206
|
+
renderer: sharedRenderer,
|
|
5207
|
+
workspaceProcesses,
|
|
5208
|
+
async remoteAs(request, principal) {
|
|
5209
|
+
return (
|
|
5210
|
+
(await remote.handleAs(request, new URL(request.url), principal)) ??
|
|
5211
|
+
new Response(null, { status: 404 })
|
|
5212
|
+
)
|
|
5213
|
+
},
|
|
4614
5214
|
snapshots,
|
|
4615
5215
|
seededAdminPassword,
|
|
4616
5216
|
bundleGrants,
|
|
@@ -4674,6 +5274,7 @@ export async function createServer(
|
|
|
4674
5274
|
previewHub.stop()
|
|
4675
5275
|
watcher?.close()
|
|
4676
5276
|
viewWatcher?.close()
|
|
5277
|
+
workspaceProcesses?.close()
|
|
4677
5278
|
siteAssets.close()
|
|
4678
5279
|
publicFiles.close()
|
|
4679
5280
|
typeWatch?.stop()
|