@crombolo/server 0.68.0 → 0.69.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.68.0",
3
+ "version": "0.69.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -32,19 +32,19 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/api-delivery": "0.68.0",
36
- "@crombolo/api-management": "0.68.0",
37
- "@crombolo/auth": "0.68.0",
38
- "@crombolo/backoffice-host": "0.68.0",
39
- "@crombolo/common": "0.68.0",
40
- "@crombolo/content": "0.68.0",
41
- "@crombolo/contracts": "0.68.0",
42
- "@crombolo/core": "0.68.0",
43
- "@crombolo/data": "0.68.0",
44
- "@crombolo/extension": "0.68.0",
45
- "@crombolo/render": "0.68.0",
46
- "@crombolo/schema": "0.68.0",
47
- "@crombolo/transfer": "0.68.0",
35
+ "@crombolo/api-delivery": "0.69.1",
36
+ "@crombolo/api-management": "0.69.1",
37
+ "@crombolo/auth": "0.69.1",
38
+ "@crombolo/backoffice-host": "0.69.1",
39
+ "@crombolo/common": "0.69.1",
40
+ "@crombolo/content": "0.69.1",
41
+ "@crombolo/contracts": "0.69.1",
42
+ "@crombolo/core": "0.69.1",
43
+ "@crombolo/data": "0.69.1",
44
+ "@crombolo/extension": "0.69.1",
45
+ "@crombolo/render": "0.69.1",
46
+ "@crombolo/schema": "0.69.1",
47
+ "@crombolo/transfer": "0.69.1",
48
48
  "@logtape/logtape": "^2.3.8",
49
49
  "@opentelemetry/api": "1.10.0",
50
50
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/approvals.ts CHANGED
@@ -331,12 +331,20 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
331
331
  const groupAliases = async (principal: Principal): Promise<Set<string>> =>
332
332
  new Set((await groups.byKeys(principal.groupKeys)).map((g) => g.alias))
333
333
 
334
+ /**
335
+ * A tool acting for a person through an exchanged token (story 367) is gated
336
+ * as the command line is: it never stands in for a person deciding to skip.
337
+ */
338
+ const unattended = (principal: Principal | undefined): boolean =>
339
+ principal === undefined || principal.viaExchange !== undefined
340
+
334
341
  /** A local operator (no principal) holds no publishing rights of their own. */
335
342
  const mayPublish = (
336
343
  principal: Principal | undefined,
337
344
  facts: PageFacts,
338
345
  action: ApprovalAction,
339
346
  ): boolean =>
347
+ !unattended(principal) &&
340
348
  principal !== undefined &&
341
349
  (principal.isAdmin ||
342
350
  permissionsForPath(principal.groups, facts.chain).has(
@@ -858,7 +866,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
858
866
 
859
867
  async beforeSave(principal, key) {
860
868
  const request = await requests().openFor(key)
861
- if (!request || principal?.isAdmin) return undefined
869
+ if (!request || (principal?.isAdmin && !unattended(principal))) return undefined
862
870
  const edit = request.workflow.onEdit
863
871
  if (request.state === 'scheduled') {
864
872
  if (edit === 'lock' || edit === 'lock-after-first-approval')
@@ -884,7 +892,10 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
884
892
  ?.head ?? null
885
893
  if (head === request.eventId) return
886
894
  // Administrators may always edit; the request goes on, on what they saved.
887
- if (!principal?.isAdmin && request.workflow.onEdit === 'withdraw') {
895
+ if (
896
+ !(principal?.isAdmin && !unattended(principal)) &&
897
+ request.workflow.onEdit === 'withdraw'
898
+ ) {
888
899
  await repo.setState(request.id, 'withdrawn')
889
900
  await repo.record(request.id, {
890
901
  kind: 'withdrawn',
package/src/config.ts CHANGED
@@ -91,6 +91,25 @@ export interface RemoteSettings {
91
91
  * 160): a self-managed GitLab, as `CROMBOLO_REMOTE_OIDC_ISSUERS`, comma separated.
92
92
  */
93
93
  oidcIssuers?: string[]
94
+ /**
95
+ * A guide for coding agents working on a site from this remote (story 370):
96
+ * an https address that discovery names as `agents.guide`.
97
+ */
98
+ agentsGuide?: string
99
+ }
100
+
101
+ /** Why an agents' guide address can't be advertised, or undefined when it can. */
102
+ export function agentsGuideProblem(guide: string): string | undefined {
103
+ let url: URL
104
+ try {
105
+ url = new URL(guide)
106
+ } catch {
107
+ return `The remote's agentsGuide, "${guide}", is not an address.`
108
+ }
109
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
110
+ return url.protocol === 'https:' || (url.protocol === 'http:' && local)
111
+ ? undefined
112
+ : `The remote's agentsGuide, ${guide}, is not https: a guide is fetched only over https.`
94
113
  }
95
114
 
96
115
  export type ContentMode = 'development' | 'production'
@@ -1053,6 +1072,7 @@ export function loadConfig(
1053
1072
  .split(',')
1054
1073
  .map((issuer) => issuer.trim())
1055
1074
  .filter(Boolean),
1075
+ agentsGuide: setting('CROMBOLO_REMOTE_AGENTS_GUIDE') || undefined,
1056
1076
  },
1057
1077
  redirects: [],
1058
1078
  trackRedirects: setting('CROMBOLO_TRACK_REDIRECTS') !== 'false',
@@ -1157,6 +1177,10 @@ export function loadConfig(
1157
1177
  merged.remote.access = overrides.remote.enabled ? 'all' : 'off'
1158
1178
  merged.remote.access ??= merged.remote.enabled ? 'all' : 'off'
1159
1179
  merged.remote.enabled = merged.remote.access !== 'off'
1180
+ if (merged.remote.agentsGuide) {
1181
+ const problem = agentsGuideProblem(merged.remote.agentsGuide)
1182
+ if (problem) throw new Error(problem)
1183
+ }
1160
1184
  merged.errors = {
1161
1185
  showDetails:
1162
1186
  overrides.errors?.showDetails ??
@@ -1176,7 +1200,7 @@ export function loadConfig(
1176
1200
  'webhooks.allowPrivateAddresses is now CROMBOLO_ALLOW_PRIVATE_ADDRESSES (allowPrivateAddresses in the config), which covers forms and identity providers too (story 304).',
1177
1201
  )
1178
1202
  checkApiClient(merged.apiClient)
1179
- checkHost(merged.host)
1203
+ checkHost(merged.host, merged.backofficeIdentityProviders, merged.lockedIdentityProviders)
1180
1204
  // The key itself is refused, so a config left over from before says so rather
1181
1205
  // than starting without the feature it asked for.
1182
1206
  if ('assistant' in overrides)
@@ -1290,7 +1314,7 @@ export function describeDatabase(
1290
1314
  }
1291
1315
  }
1292
1316
 
1293
- export const VERSION = '0.68.0'
1317
+ export const VERSION = '0.69.1'
1294
1318
 
1295
1319
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1296
1320
  /** A positive number from a setting, else the default. */
package/src/host-token.ts CHANGED
@@ -5,6 +5,11 @@
5
5
  * docs/bundles.md, "Tools a host provides".
6
6
  */
7
7
  import { SignJWT } from 'jose'
8
+ import {
9
+ type IdentityProvider,
10
+ type LockedIdentityProviders,
11
+ lockOf,
12
+ } from './identity-providers.ts'
8
13
 
9
14
  /** The installation's host, from `crombolo.config.ts` only. */
10
15
  export interface HostConfig {
@@ -14,13 +19,23 @@ export interface HostConfig {
14
19
  signingKey: string
15
20
  /** Names the key in each token's header, for a host running many installations. */
16
21
  keyId: string
22
+ /**
23
+ * The back-office identity provider the host signs people in through (story
24
+ * 372): each token names the person's subject there, as `host_sub` and
25
+ * `host_iss`. It must be locked, so nobody can point it at another issuer.
26
+ */
27
+ provider?: string
17
28
  }
18
29
 
19
30
  /** How long a token lasts, in seconds. */
20
31
  export const HOST_TOKEN_SECONDS = 300
21
32
 
22
33
  /** Refuses a `host` that could not be used, naming the field. */
23
- export function checkHost(host: HostConfig | undefined): void {
34
+ export function checkHost(
35
+ host: HostConfig | undefined,
36
+ providers: readonly IdentityProvider[] = [],
37
+ locked: LockedIdentityProviders = [],
38
+ ): void {
24
39
  if (!host) return
25
40
  let url: URL | undefined
26
41
  try {
@@ -37,6 +52,17 @@ export function checkHost(host: HostConfig | undefined): void {
37
52
  throw new Error('host.signingKey must be at least 32 bytes.')
38
53
  if (typeof host.keyId !== 'string' || host.keyId.trim() === '')
39
54
  throw new Error('host.keyId must name the key.')
55
+ if (host.provider === undefined) return
56
+ const provider = providers.find((p) => p.oidc.id === host.provider)
57
+ if (!provider)
58
+ throw new Error(
59
+ `host.provider is "${host.provider}", which is not one of the back-office identity providers the config declares.`,
60
+ )
61
+ // Story 372: an unlocked provider could be re-pointed at an issuer an administrator controls.
62
+ if (!lockOf(provider, locked))
63
+ throw new Error(
64
+ `host.provider names ${provider.oidc.name}, which must be locked: set locked: true on it, so nobody can point it at another issuer.`,
65
+ )
40
66
  }
41
67
 
42
68
  /** Who the token is about, and which site says so. */
@@ -45,6 +71,8 @@ export interface HostTokenSubject {
45
71
  groups: readonly string[]
46
72
  sections: readonly string[]
47
73
  site: { name: string; nodeId: string; url?: string }
74
+ /** Who the person is at the host's provider (story 372), when their link recorded it. */
75
+ host?: { sub: string; iss: string }
48
76
  }
49
77
 
50
78
  export async function issueHostToken(
@@ -58,6 +86,7 @@ export async function issueHostToken(
58
86
  groups: [...subject.groups],
59
87
  sections: [...subject.sections],
60
88
  site: { name: subject.site.name, nodeId: subject.site.nodeId },
89
+ ...(subject.host ? { host_sub: subject.host.sub, host_iss: subject.host.iss } : {}),
61
90
  })
62
91
  .setProtectedHeader({ alg: 'HS256', kid: host.keyId, typ: 'JWT' })
63
92
  .setSubject(subject.user.key)
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Preview links (story 368): one page's draft in any browser for a few
3
+ * minutes, without a back-office sign-in in it. A link carries a signed,
4
+ * single-use token that the site swaps on first use for an httpOnly cookie
5
+ * naming the person and the page, then redirects away from, so the token is
6
+ * never left where the page's own scripts could read it. The person's
7
+ * standing and read rights are checked again on every request.
8
+ * docs/rendering.md, "Preview".
9
+ */
10
+ import { hmac, sameSignature } from './preview-tokens.ts'
11
+
12
+ /** The query parameter a link carries its token in. */
13
+ export const PREVIEW_LINK_PARAM = 'crombolo-preview'
14
+ /** The cookie a used link leaves. */
15
+ export const PREVIEW_LINK_COOKIE = 'crombolo_preview_link'
16
+ /** How long a link waits for its first use. */
17
+ export const PREVIEW_LINK_SECONDS = 5 * 60
18
+ /** How long the cookie shows the draft. */
19
+ export const PREVIEW_LINK_COOKIE_SECONDS = 30 * 60
20
+ /** The issuer a link's id is used under, among single-use tokens. */
21
+ export const PREVIEW_LINK_ISSUER = 'crombolo:preview-link'
22
+
23
+ export interface PreviewLinkClaims {
24
+ /** The person's user id. */
25
+ user: number
26
+ /** A digest of their security stamp when it was issued. */
27
+ stamp: string
28
+ /** The document's key. */
29
+ document: string
30
+ culture: string | null
31
+ /** Milliseconds since the epoch. */
32
+ expires: number
33
+ }
34
+
35
+ type Purpose = 'link' | 'cookie'
36
+
37
+ /**
38
+ * A key for one purpose, derived from the preview key, so a link, its cookie
39
+ * and a Delivery API preview token (053) never verify as one another.
40
+ */
41
+ const keyFor = (secret: string, purpose: Purpose) => hmac(secret, `crombolo/preview-${purpose}`)
42
+
43
+ const sign = (secret: string, purpose: Purpose, claims: object) => {
44
+ const payload = Buffer.from(JSON.stringify(claims)).toString('base64url')
45
+ return `${payload}.${hmac(keyFor(secret, purpose), payload)}`
46
+ }
47
+
48
+ function read(secret: string, purpose: Purpose, token: string, now: number) {
49
+ const [payload, signature, ...rest] = token.split('.')
50
+ if (!payload || !signature || rest.length > 0) return undefined
51
+ if (!sameSignature(hmac(keyFor(secret, purpose), payload), signature)) return undefined
52
+ try {
53
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()) as Record<
54
+ string,
55
+ unknown
56
+ >
57
+ if (
58
+ typeof claims.user !== 'number' ||
59
+ typeof claims.stamp !== 'string' ||
60
+ typeof claims.document !== 'string' ||
61
+ (claims.culture !== null && typeof claims.culture !== 'string') ||
62
+ typeof claims.expires !== 'number' ||
63
+ claims.expires <= now
64
+ )
65
+ return undefined
66
+ return claims
67
+ } catch {
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ /** A link's token: the claims and a single-use id. */
73
+ export function signPreviewLink(secret: string, claims: PreviewLinkClaims & { id: string }) {
74
+ return sign(secret, 'link', claims)
75
+ }
76
+
77
+ export function readPreviewLink(
78
+ secret: string,
79
+ token: string,
80
+ now = Date.now(),
81
+ ): (PreviewLinkClaims & { id: string }) | undefined {
82
+ const claims = read(secret, 'link', token, now)
83
+ return claims && typeof claims.id === 'string'
84
+ ? (claims as unknown as PreviewLinkClaims & { id: string })
85
+ : undefined
86
+ }
87
+
88
+ /** The cookie a used link leaves, with the claims and a fresh expiry. */
89
+ export function signPreviewCookie(secret: string, claims: PreviewLinkClaims) {
90
+ return sign(secret, 'cookie', claims)
91
+ }
92
+
93
+ export function readPreviewCookie(
94
+ secret: string,
95
+ value: string,
96
+ now = Date.now(),
97
+ ): PreviewLinkClaims | undefined {
98
+ return read(secret, 'cookie', value, now) as PreviewLinkClaims | undefined
99
+ }
100
+
101
+ /** The `Set-Cookie` value for a used link, or for clearing one. */
102
+ export function previewLinkCookie(value: string | null, secure: boolean): string {
103
+ const age = value === null ? 0 : PREVIEW_LINK_COOKIE_SECONDS
104
+ return `${PREVIEW_LINK_COOKIE}=${value ?? ''}; Path=/; Max-Age=${age}; HttpOnly; SameSite=Lax${secure ? '; Secure' : ''}`
105
+ }
@@ -25,13 +25,13 @@ export function previewSigningSecret(db: Db): Promise<string> {
25
25
  return ensureKeyValue(db, SIGNING_KEY, () => crypto.randomUUID())
26
26
  }
27
27
 
28
- function hmac(secret: string, payload: string): string {
28
+ export function hmac(secret: string, payload: string): string {
29
29
  const hasher = new Bun.CryptoHasher('sha256', secret)
30
30
  hasher.update(payload)
31
31
  return hasher.digest('base64url')
32
32
  }
33
33
 
34
- function sameSignature(a: string, b: string): boolean {
34
+ export function sameSignature(a: string, b: string): boolean {
35
35
  if (a.length !== b.length) return false
36
36
  let difference = 0
37
37
  for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i)
@@ -12,7 +12,7 @@ import {
12
12
  type Db,
13
13
  ExternalLoginRepository,
14
14
  externalLoginProvider,
15
- RemoteExchangeIds,
15
+ SingleUseTokens,
16
16
  } from '@crombolo/data'
17
17
  import { type JWTPayload, jwtVerify } from 'jose'
18
18
  import { type ExternalAccount, syncedGroups } from './external-sign-in.ts'
@@ -133,7 +133,7 @@ export function createPeopleExchange(options: {
133
133
  onExchange(outcome: PeopleExchangeOutcome, request: Request): Promise<void>
134
134
  }): PeopleExchange {
135
135
  const logins = new ExternalLoginRepository(options.db)
136
- const ids = new RemoteExchangeIds(options.db)
136
+ const ids = new SingleUseTokens(options.db)
137
137
  const keysOf = issuerKeys()
138
138
  const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
139
139
 
@@ -293,7 +293,7 @@ export function createPeopleExchange(options: {
293
293
  // Entra calls its one-time id `uti`.
294
294
  const tokenId = text(claims, 'jti') ?? text(claims, 'uti')
295
295
  if (!tokenId) return refuse(request, ip, 'the token has no one-time id', provider)
296
- if (!(await ids.spend(issuer, tokenId, new Date(exp * 1000))))
296
+ if (!(await ids.use(issuer, tokenId, new Date(exp * 1000))))
297
297
  return refuse(request, ip, 'the token was already used', provider)
298
298
  const actor = actorOf(claims, provider.remoteExchange?.actors)
299
299
  if (actor === 'malformed')
@@ -85,6 +85,12 @@ export function createUndoRoutes(options: UndoRouteOptions) {
85
85
  const skipApproval = asked.skipApproval === true
86
86
  if (skipApproval && !principal.isAdmin)
87
87
  return problem(403, { code: 'forbidden', title: 'Only an administrator can skip approval' })
88
+ if (skipApproval && principal.viaExchange)
89
+ return problem(403, {
90
+ code: 'forbidden',
91
+ title: 'A sign-in through a provider cannot skip approval',
92
+ detail: 'Sign in with your own command-line sign-in to skip it.',
93
+ })
88
94
  const version = await pageVersion(db, id)
89
95
  if (!version) return notHere('There is no such version')
90
96
  const actor = actorOf(principal, request, skipApproval)
package/src/remote.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  type RemoteJob,
33
33
  RemoteJobRepository,
34
34
  RemoteTrustRepository,
35
+ readWorkflows,
35
36
  TransferRunRepository,
36
37
  type TrustRule,
37
38
  } from '@crombolo/data'
@@ -264,6 +265,8 @@ export function createRemote(options: RemoteOptions): Remote {
264
265
  ...(options.restart && atLeast('all') ? ['restart'] : []),
265
266
  ],
266
267
  environments: [environment()],
268
+ // Story 370: a guide for agents working on a site from here.
269
+ ...(settings.agentsGuide ? { agents: { guide: settings.agentsGuide } } : {}),
267
270
  })
268
271
 
269
272
  /** Where a CI principal's run was, for its audit rows: repository, ref and run. */
@@ -1225,6 +1228,17 @@ export function createRemote(options: RemoteOptions): Remote {
1225
1228
  title: 'This environment is protected',
1226
1229
  detail: 'Pushing here replaces something people rely on, and needs its own permission.',
1227
1230
  })
1231
+ // Story 367: a push replaces pages without the page gate, so a tool never pushes over a workflow.
1232
+ if (principal.viaExchange) {
1233
+ const workflows = await readWorkflows(db)
1234
+ if (workflows.length > 0)
1235
+ return problem(403, {
1236
+ code: 'workflow-covers-pages',
1237
+ title:
1238
+ 'Pages here need approval, so a sign-in through a provider cannot push the whole site',
1239
+ detail: `Workflows: ${workflows.map((w) => w.workflow.name).join(', ')}. Push with your own command-line sign-in, or publish the pages one by one.`,
1240
+ })
1241
+ }
1228
1242
  const declared = request.headers.get('crombolo-sha256')?.toLowerCase()
1229
1243
  const passphrase = request.headers.get('crombolo-passphrase')
1230
1244
  const refused = passphraseProblem(passphrase)
package/src/server.ts CHANGED
@@ -92,8 +92,10 @@ import {
92
92
  byActor,
93
93
  currentAuditContext,
94
94
  type Db,
95
+ ExternalLoginRepository,
95
96
  ensureFormLibraryTypes,
96
97
  ensureKeyValue,
98
+ externalLoginProvider,
97
99
  FormEntryRepository,
98
100
  FormWorkflowRepository,
99
101
  FormWorkflowSecretRepository,
@@ -107,6 +109,7 @@ import {
107
109
  readLedger,
108
110
  readReport,
109
111
  readUrlOptions,
112
+ SingleUseTokens,
110
113
  searchProvidersOf,
111
114
  TransferRunRepository,
112
115
  UserRepository,
@@ -240,6 +243,18 @@ import { noNodesPage } from './no-nodes.ts'
240
243
  import { NotImplementedLog } from './not-implemented.ts'
241
244
  import { overview, readOverviewQuery } from './overview.ts'
242
245
  import { createDeps, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
246
+ import {
247
+ PREVIEW_LINK_COOKIE,
248
+ PREVIEW_LINK_COOKIE_SECONDS,
249
+ PREVIEW_LINK_ISSUER,
250
+ PREVIEW_LINK_PARAM,
251
+ PREVIEW_LINK_SECONDS,
252
+ previewLinkCookie,
253
+ readPreviewCookie,
254
+ readPreviewLink,
255
+ signPreviewCookie,
256
+ signPreviewLink,
257
+ } from './preview-links.ts'
243
258
  import {
244
259
  previewSigningSecret,
245
260
  previewUser,
@@ -1702,6 +1717,7 @@ export async function createServer(
1702
1717
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1703
1718
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1704
1719
  const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1720
+ const previewLinkPath = `${paths.pluginPath}/api/preview-link`
1705
1721
  const selfAudited = [
1706
1722
  `${paths.pluginPath}/api/email/`,
1707
1723
  `${paths.pluginPath}/api/schema-transfer/`,
@@ -1932,6 +1948,129 @@ export async function createServer(
1932
1948
  })
1933
1949
  }
1934
1950
 
1951
+ /**
1952
+ * Story 372: who the person is at the host's own provider, as their last
1953
+ * sign-in through it recorded, and only from that provider's issuer.
1954
+ */
1955
+ async function hostIdentityOf(userKey: string): Promise<{ host?: { sub: string; iss: string } }> {
1956
+ const id = config.host?.provider
1957
+ const provider = id
1958
+ ? config.backofficeIdentityProviders.find((p) => p.oidc.id === id)
1959
+ : undefined
1960
+ if (!provider) return {}
1961
+ const issuer = provider.oidc.issuer
1962
+ const link = (await new ExternalLoginRepository(db).forOwner(userKey)).find(
1963
+ (l) => l.loginProvider === externalLoginProvider('user', provider.oidc.id),
1964
+ )
1965
+ const identity = link?.identity
1966
+ return identity && identity.issuer === issuer
1967
+ ? { host: { sub: identity.value, iss: issuer } }
1968
+ : {}
1969
+ }
1970
+
1971
+ /** Story 368: a preview link for a page its person may read, audited as them. */
1972
+ async function askForPreviewLink(request: Request): Promise<Response> {
1973
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
1974
+ const principal = await authenticate(request)
1975
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1976
+ const asked = (await request.json().catch(() => ({}))) as {
1977
+ document?: unknown
1978
+ culture?: unknown
1979
+ }
1980
+ const document = typeof asked.document === 'string' ? asked.document : ''
1981
+ const culture = typeof asked.culture === 'string' && asked.culture ? asked.culture : null
1982
+ if (!UUID_PATTERN.test(document))
1983
+ return Response.json({ title: 'Name the page by its key' }, { status: 400 })
1984
+ const standing = await previewUser(db, { key: principal.id })
1985
+ if (!standing || !(await canReadDocument(principal, document, nodeLookup)))
1986
+ return Response.json({ title: 'You may not read this page' }, { status: 403 })
1987
+ const key = normaliseUuid(document)
1988
+ const page = await (await draftCache()).byKey(key, culture)
1989
+ const published = await cache.byKey(key, culture)
1990
+ const expires = Date.now() + PREVIEW_LINK_SECONDS * 1000
1991
+ const token = signPreviewLink(previewSecret, {
1992
+ user: standing.id,
1993
+ stamp: standing.stamp,
1994
+ document: key,
1995
+ culture,
1996
+ expires,
1997
+ id: crypto.randomUUID(),
1998
+ })
1999
+ const url = new URL(published?.url ?? `/${key}`, publicOrigin(request, config))
2000
+ url.searchParams.set(PREVIEW_LINK_PARAM, token)
2001
+ await recordAudit(db, {
2002
+ category: 'content',
2003
+ action: 'PreviewLink',
2004
+ source: 'request',
2005
+ userKey: principal.id,
2006
+ userName: principal.name,
2007
+ entityType: 'Document',
2008
+ entityKey: key,
2009
+ entityName: page?.name ?? published?.name ?? null,
2010
+ detail: culture ? `A preview link, for ${culture}` : 'A preview link',
2011
+ ...clientAddress(request),
2012
+ })
2013
+ return Response.json(
2014
+ { url: url.toString(), expiresAt: new Date(expires).toISOString() },
2015
+ { headers: { 'cache-control': PRIVATE_NO_STORE } },
2016
+ )
2017
+ }
2018
+
2019
+ /**
2020
+ * A link's first use (story 368): its token swapped for the cookie, once, and
2021
+ * the browser sent to the same address without it. A token that is spent,
2022
+ * expired or forged is dropped from the address the same way, with no cookie.
2023
+ */
2024
+ async function usePreviewLink(request: Request, url: URL): Promise<Response | undefined> {
2025
+ if (request.method !== 'GET' && request.method !== 'HEAD') return undefined
2026
+ const token = url.searchParams.get(PREVIEW_LINK_PARAM)
2027
+ if (token === null) return undefined
2028
+ const clean = new URL(url)
2029
+ clean.searchParams.delete(PREVIEW_LINK_PARAM)
2030
+ const headers = new Headers({
2031
+ location: `${clean.pathname}${clean.search}`,
2032
+ 'cache-control': PRIVATE_NO_STORE,
2033
+ 'referrer-policy': 'no-referrer',
2034
+ })
2035
+ const claims = readPreviewLink(previewSecret, token)
2036
+ const standing = claims ? await previewUser(db, { id: claims.user }) : undefined
2037
+ if (
2038
+ claims &&
2039
+ standing?.stamp === claims.stamp &&
2040
+ (await new SingleUseTokens(db).use(PREVIEW_LINK_ISSUER, claims.id, new Date(claims.expires)))
2041
+ )
2042
+ headers.set(
2043
+ 'set-cookie',
2044
+ previewLinkCookie(
2045
+ signPreviewCookie(previewSecret, {
2046
+ user: claims.user,
2047
+ stamp: claims.stamp,
2048
+ document: claims.document,
2049
+ culture: claims.culture,
2050
+ expires: Date.now() + PREVIEW_LINK_COOKIE_SECONDS * 1000,
2051
+ }),
2052
+ config.secureCookies,
2053
+ ),
2054
+ )
2055
+ return new Response(null, { status: 303, headers })
2056
+ }
2057
+
2058
+ /** Who a used link previews as, and which page: undefined once they may not, or it has run out. */
2059
+ async function linkedPreview(request: Request) {
2060
+ const value = readCookie(request, PREVIEW_LINK_COOKIE)
2061
+ const claims = value ? readPreviewCookie(previewSecret, value) : undefined
2062
+ if (!claims) return undefined
2063
+ const standing = await previewUser(db, { id: claims.user })
2064
+ if (standing?.stamp !== claims.stamp) return undefined
2065
+ const identity = await auth.identityOf(claims.user)
2066
+ if (!identity) return undefined
2067
+ return {
2068
+ principal: await principalFrom(identity),
2069
+ document: claims.document,
2070
+ culture: claims.culture,
2071
+ }
2072
+ }
2073
+
1935
2074
  /** What a chain is carrying through one request (story 210). */
1936
2075
  interface ChainRun {
1937
2076
  original: URL
@@ -1954,6 +2093,8 @@ export async function createServer(
1954
2093
 
1955
2094
  /** A site request: the middleware chain around crombolo's own handling, when the site has one. */
1956
2095
  async function siteRequest(request: Request, url: URL): Promise<Response> {
2096
+ const linked = await usePreviewLink(request, url)
2097
+ if (linked) return linked
1957
2098
  if (!anyMiddleware()) return siteFiles(request)
1958
2099
  const run: ChainRun = {
1959
2100
  original: url,
@@ -2629,6 +2770,7 @@ export async function createServer(
2629
2770
  nodeId: schema.nodeId,
2630
2771
  url: config.applicationUrl || undefined,
2631
2772
  },
2773
+ ...(await hostIdentityOf(principal.id)),
2632
2774
  })
2633
2775
  log.info('Issued a host token to {user} for {host}', {
2634
2776
  user: principal.email,
@@ -2728,6 +2870,9 @@ export async function createServer(
2728
2870
  )
2729
2871
  }
2730
2872
 
2873
+ // Story 368: a link that opens one page's draft in any browser.
2874
+ if (pathname === previewLinkPath) return askForPreviewLink(request)
2875
+
2731
2876
  // Story 314: an administrator's session seen as user groups, and back.
2732
2877
  if (pathname === viewAsPath) {
2733
2878
  const identity = await identify(request)
@@ -3738,18 +3883,22 @@ export async function createServer(
3738
3883
  * draft of the page it resolves to.
3739
3884
  */
3740
3885
  async function renderPreview(request: Request, pathname: string, host: string) {
3741
- if (!readCookie(request, PREVIEW_COOKIE)) return undefined
3742
- const principal = await authenticate(request)
3886
+ const editor = readCookie(request, PREVIEW_COOKIE) ? await authenticate(request) : undefined
3887
+ // Story 368: else a used preview link, for its one page.
3888
+ const link = editor ? undefined : await linkedPreview(request)
3889
+ const principal = editor ?? link?.principal
3743
3890
  if (!principal) return undefined
3744
3891
  const byKey = /^\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(
3745
3892
  pathname,
3746
3893
  )
3747
3894
  const key = byKey?.[1] ?? (await cache.resolve(host, pathname))?.content.key
3748
3895
  if (!key) return undefined
3749
- const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
3896
+ if (link && normaliseUuid(key) !== normaliseUuid(link.document)) return undefined
3897
+ const culture = link ? link.culture : new URL(request.url).searchParams.get('culture')
3898
+ const draft = await draftModel(key, culture, principal)
3750
3899
  if (!draft) return undefined
3751
3900
  // The previewing editor is the visitor: signed out, or a member they chose (story 264).
3752
- const member = await previewMember(request, principal)
3901
+ const member = link ? undefined : await previewMember(request, principal)
3753
3902
  return renderer.renderModel(draft.content, draft.culture, {
3754
3903
  ...(await pageRequest(request)),
3755
3904
  member,
package/src/settings.ts CHANGED
@@ -989,6 +989,14 @@ const DECLARED = [
989
989
  description:
990
990
  'The largest push or media file a client may upload, in gigabytes. Every other request keeps the usual body limit.',
991
991
  },
992
+ {
993
+ env: 'CROMBOLO_REMOTE_AGENTS_GUIDE',
994
+ kind: 'string',
995
+ default: '',
996
+ section: 'Remote',
997
+ description:
998
+ 'An https address of a guide for coding agents working on a site from this remote, which discovery names and `crombolo pull` writes into AGENTS.md.',
999
+ },
992
1000
  {
993
1001
  env: 'CROMBOLO_REMOTE_OIDC_ISSUERS',
994
1002
  kind: 'string',