@crombolo/server 0.67.0 → 0.69.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.67.0",
3
+ "version": "0.69.0",
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.67.0",
36
- "@crombolo/api-management": "0.67.0",
37
- "@crombolo/auth": "0.67.0",
38
- "@crombolo/backoffice-host": "0.67.0",
39
- "@crombolo/common": "0.67.0",
40
- "@crombolo/content": "0.67.0",
41
- "@crombolo/contracts": "0.67.0",
42
- "@crombolo/core": "0.67.0",
43
- "@crombolo/data": "0.67.0",
44
- "@crombolo/extension": "0.67.0",
45
- "@crombolo/render": "0.67.0",
46
- "@crombolo/schema": "0.67.0",
47
- "@crombolo/transfer": "0.67.0",
35
+ "@crombolo/api-delivery": "0.69.0",
36
+ "@crombolo/api-management": "0.69.0",
37
+ "@crombolo/auth": "0.69.0",
38
+ "@crombolo/backoffice-host": "0.69.0",
39
+ "@crombolo/common": "0.69.0",
40
+ "@crombolo/content": "0.69.0",
41
+ "@crombolo/contracts": "0.69.0",
42
+ "@crombolo/core": "0.69.0",
43
+ "@crombolo/data": "0.69.0",
44
+ "@crombolo/extension": "0.69.0",
45
+ "@crombolo/render": "0.69.0",
46
+ "@crombolo/schema": "0.69.0",
47
+ "@crombolo/transfer": "0.69.0",
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 ??
@@ -1290,7 +1314,7 @@ export function describeDatabase(
1290
1314
  }
1291
1315
  }
1292
1316
 
1293
- export const VERSION = '0.67.0'
1317
+ export const VERSION = '0.69.0'
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. */
@@ -53,8 +53,16 @@ export interface IdentityProviderOptions {
53
53
  * provider's tokens for a sign-in as the person they name. The token's `aud`
54
54
  * must be `audience`, the site's origin by default, and never a sign-in
55
55
  * client id. `CROMBOLO_REMOTE_EXCHANGE_PROVIDERS` turns it on too.
56
+ * `actors` names the clients a token can be issued to, by client id, for the
57
+ * history (story 366).
56
58
  */
57
- remoteExchange?: boolean | { audience?: string }
59
+ remoteExchange?: boolean | RemoteExchangeOptions
60
+ }
61
+
62
+ /** How a provider's tokens are exchanged at the remote (stories 364 and 366). */
63
+ export interface RemoteExchangeOptions {
64
+ audience?: string
65
+ actors?: Readonly<Record<string, string>>
58
66
  }
59
67
 
60
68
  /** Which preset made a provider: what the Entra bundle looks for. */
@@ -74,8 +82,8 @@ export interface IdentityProvider {
74
82
  memberType: string | undefined
75
83
  /** Declared `locked: true`. */
76
84
  locked: boolean
77
- /** Declared `remoteExchange`: the audience its exchanged tokens carry, when not the site's origin. */
78
- remoteExchange: { audience?: string } | undefined
85
+ /** Declared `remoteExchange`: the audience its exchanged tokens carry, and the actors it names. */
86
+ remoteExchange: RemoteExchangeOptions | undefined
79
87
  /** Why it cannot sign anyone in as it stands, such as a new issuer with no secret of its own. */
80
88
  unavailable?: string
81
89
  }
package/src/index.ts CHANGED
@@ -143,6 +143,7 @@ export * from './remote-ci.ts'
143
143
  export * from './remote-credentials.ts'
144
144
  export * from './remote-media.ts'
145
145
  export { FILE_NAME_HEADER } from './remote-media-library.ts'
146
+ export { actorOf, type ExchangeActor } from './remote-people.ts'
146
147
  export * from './restart-pending.ts'
147
148
  export * from './routes.ts'
148
149
  export * from './schema.ts'
@@ -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'
@@ -40,6 +40,46 @@ const text = (claims: JWTPayload, name: string | undefined): string | undefined
40
40
  return typeof value === 'string' && value !== '' ? value : undefined
41
41
  }
42
42
 
43
+ /** Text from a token for the history: control characters gone, and no longer than `limit`. */
44
+ const plain = (value: string, limit: number) =>
45
+ value
46
+ .replace(/\p{Cc}/gu, '')
47
+ .trim()
48
+ .slice(0, limit)
49
+
50
+ /** Who acts for the person (story 366): the tool a token names, by id and by name. */
51
+ export interface ExchangeActor {
52
+ id: string
53
+ name: string | null
54
+ }
55
+
56
+ /**
57
+ * The actor a verified token names: its `act` (RFC 8693), or else the client it
58
+ * was issued to (`azp`, or Entra v1's `appid`), named by the provider's `actors`.
59
+ * `malformed` for an `act` with no string `sub`.
60
+ */
61
+ export function actorOf(
62
+ claims: JWTPayload,
63
+ actors: Readonly<Record<string, string>> = {},
64
+ ): ExchangeActor | undefined | 'malformed' {
65
+ if (claims.act !== undefined) {
66
+ const act = claims.act
67
+ if (!act || typeof act !== 'object' || Array.isArray(act)) return 'malformed'
68
+ const { sub, name } = act as Record<string, unknown>
69
+ const id = typeof sub === 'string' ? plain(sub, 200) : ''
70
+ if (!id) return 'malformed'
71
+ const named = typeof name === 'string' ? plain(name, 100) : ''
72
+ return { id, name: named || (Object.hasOwn(actors, id) ? (actors[id] ?? null) : null) }
73
+ }
74
+ const client = text(claims, 'azp') ?? text(claims, 'appid')
75
+ const id = client ? plain(client, 200) : ''
76
+ if (!id) return undefined
77
+ return { id, name: Object.hasOwn(actors, id) ? (actors[id] ?? null) : null }
78
+ }
79
+
80
+ /** Entra's v1 issuer for a tenant, which the exchange recognises only to refuse. */
81
+ const entraV1Issuer = (tenantId: string) => `https://sts.windows.net/${tenantId}`
82
+
43
83
  const list = (claims: JWTPayload, name: string | undefined): string[] => {
44
84
  const value = name ? claims[name] : undefined
45
85
  if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string')
@@ -59,11 +99,17 @@ export interface ExchangeAccounts {
59
99
  provider: { id: string; name: string },
60
100
  seconds: number,
61
101
  ip: string | undefined,
102
+ actor: ExchangeActor | undefined,
62
103
  ): Promise<{ accessToken: string } | { refused: string }>
63
104
  }
64
105
 
65
106
  export type PeopleExchangeOutcome =
66
- | { ok: true; provider: IdentityProvider; account: ExternalAccount }
107
+ | {
108
+ ok: true
109
+ provider: IdentityProvider
110
+ account: ExternalAccount
111
+ actor: ExchangeActor | undefined
112
+ }
67
113
  | { ok: false; reason: string; provider?: IdentityProvider }
68
114
 
69
115
  export interface PeopleExchange {
@@ -87,7 +133,7 @@ export function createPeopleExchange(options: {
87
133
  onExchange(outcome: PeopleExchangeOutcome, request: Request): Promise<void>
88
134
  }): PeopleExchange {
89
135
  const logins = new ExternalLoginRepository(options.db)
90
- const ids = new RemoteExchangeIds(options.db)
136
+ const ids = new SingleUseTokens(options.db)
91
137
  const keysOf = issuerKeys()
92
138
  const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
93
139
 
@@ -103,6 +149,18 @@ export function createPeopleExchange(options: {
103
149
  provider.remoteExchange?.audience ?? origin
104
150
  const usable = (provider: IdentityProvider) =>
105
151
  !provider.unavailable && usableIssuer(issuerOf(provider))
152
+ /** The exchanging provider a token's issuer is, and whether it came as Entra's v1 token. */
153
+ const providerFor = async (issuer: string | undefined) => {
154
+ if (!issuer) return undefined
155
+ const bare = issuer.replace(/\/+$/, '')
156
+ for (const p of await effective()) {
157
+ if (!usable(p)) continue
158
+ if (issuerOf(p) === issuer) return { provider: p, v1: false }
159
+ if (p.kind === 'entra' && p.tenantId && entraV1Issuer(p.tenantId) === bare)
160
+ return { provider: p, v1: true }
161
+ }
162
+ return undefined
163
+ }
106
164
 
107
165
  const json = (body: unknown, status: number) =>
108
166
  Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
@@ -169,7 +227,7 @@ export function createPeopleExchange(options: {
169
227
  },
170
228
 
171
229
  async handles(issuer) {
172
- return (await effective()).some((p) => usable(p) && issuerOf(p) === issuer)
230
+ return (await providerFor(issuer)) !== undefined
173
231
  },
174
232
 
175
233
  async exchange(request, url, ip) {
@@ -188,11 +246,19 @@ export function createPeopleExchange(options: {
188
246
  const token = form.get('subject_token') ?? ''
189
247
 
190
248
  const issuer = unverifiedIssuer(token)
191
- const provider = (await effective()).find((p) => usable(p) && issuerOf(p) === issuer)
192
- if (!issuer || !provider)
249
+ const found = await providerFor(issuer)
250
+ if (!issuer || !found)
193
251
  return refuse(request, ip, 'an issuer that is not an exchanging provider')
194
- if (limiter.blocked(`issuer:${issuer}`))
252
+ const { provider } = found
253
+ if (limiter.blocked(`issuer:${issuerOf(provider)}`))
195
254
  return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
255
+ if (found.v1)
256
+ return refuse(
257
+ request,
258
+ ip,
259
+ 'it is an Entra v1 token: set requestedAccessTokenVersion to 2 in the manifest of the app it was issued for',
260
+ provider,
261
+ )
196
262
 
197
263
  const audience = audienceOf(provider, url.origin)
198
264
  const signInClients = await Promise.all(
@@ -227,15 +293,18 @@ export function createPeopleExchange(options: {
227
293
  // Entra calls its one-time id `uti`.
228
294
  const tokenId = text(claims, 'jti') ?? text(claims, 'uti')
229
295
  if (!tokenId) return refuse(request, ip, 'the token has no one-time id', provider)
230
- if (!(await ids.spend(issuer, tokenId, new Date(exp * 1000))))
296
+ if (!(await ids.use(issuer, tokenId, new Date(exp * 1000))))
231
297
  return refuse(request, ip, 'the token was already used', provider)
298
+ const actor = actorOf(claims, provider.remoteExchange?.actors)
299
+ if (actor === 'malformed')
300
+ return refuse(request, ip, 'its act claim names no actor by a string sub', provider)
232
301
 
233
- const found = await accountFor(provider, issuer, claims)
234
- if (typeof found === 'string') return refuse(request, ip, found, provider)
235
- const refusal = await options.accounts.refusal(found.key)
302
+ const person = await accountFor(provider, issuer, claims)
303
+ if (typeof person === 'string') return refuse(request, ip, person, provider)
304
+ const refusal = await options.accounts.refusal(person.key)
236
305
  if (refusal) return refuse(request, ip, refusal, provider)
237
306
 
238
- let account = found
307
+ let account = person
239
308
  if (Object.keys(provider.groupMap).length > 0) {
240
309
  const groups = syncedGroups(
241
310
  account.groups,
@@ -252,9 +321,10 @@ export function createPeopleExchange(options: {
252
321
  { id: provider.oidc.id, name: provider.oidc.name },
253
322
  PERSON_TOKEN_SECONDS,
254
323
  ip,
324
+ actor,
255
325
  )
256
326
  if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
257
- await options.onExchange({ ok: true, provider, account }, request)
327
+ await options.onExchange({ ok: true, provider, account, actor }, request)
258
328
  return json(
259
329
  {
260
330
  access_token: signedIn.accessToken,
@@ -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'
@@ -87,7 +88,7 @@ import type { UserPorts } from './user-admin.ts'
87
88
 
88
89
  export const REMOTE_PROTOCOL_VERSION = '1'
89
90
  export { REMOTE_DISCOVERY_PATH }
90
- export const REMOTE_API_PATH = '/umbraco/remote/v1'
91
+ export const REMOTE_API_PATH = '/crombolo/remote/v1'
91
92
 
92
93
  /** How long a finished job's file stays downloadable, and its row with it. */
93
94
  const JOB_FILE_SECONDS = 60 * 60
@@ -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)
@@ -1533,22 +1547,25 @@ export function createRemote(options: RemoteOptions): Remote {
1533
1547
  : new Response(null, { status: 405 })
1534
1548
  }
1535
1549
  if (!pathname.startsWith(`${REMOTE_API_PATH}/`)) return undefined
1536
- if (!settings.enabled)
1537
- return problem(404, { code: 'not-enabled', title: 'This site is not a remote' })
1550
+ const notEnabled = () =>
1551
+ problem(404, { code: 'not-enabled', title: 'This site is not a remote' })
1538
1552
  if (pathname === `${REMOTE_API_PATH}/token`) {
1553
+ const people = options.people
1554
+ if (!settings.enabled && !people) return notEnabled()
1539
1555
  if (request.method !== 'POST') return new Response(null, { status: 405 })
1540
1556
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
1541
1557
  // One endpoint for both: the token's issuer says whether it is CI's or a person's.
1542
- const people = options.people
1558
+ // A person's exchange answers with the remote off too (story 365); CI's does not.
1543
1559
  const issuer = people
1544
1560
  ? unverifiedIssuer(
1545
1561
  new URLSearchParams(await request.clone().text()).get('subject_token') ?? '',
1546
1562
  )
1547
1563
  : undefined
1548
- return people && issuer && (await people.handles(issuer))
1549
- ? people.exchange(request, url, ip)
1550
- : ci.exchange(request, url, ip)
1564
+ if (people && issuer && (await people.handles(issuer)))
1565
+ return people.exchange(request, url, ip)
1566
+ return settings.enabled ? ci.exchange(request, url, ip) : notEnabled()
1551
1567
  }
1568
+ if (!settings.enabled) return notEnabled()
1552
1569
  // A CI token is good here and nowhere else; a person's is the back office's own.
1553
1570
  const principal = (await ci.principalOf(request)) ?? (await options.authenticate(request))
1554
1571
  if (!principal)
package/src/server.ts CHANGED
@@ -89,6 +89,7 @@ import {
89
89
  } from '@crombolo/core'
90
90
  import {
91
91
  appendCacheInstruction,
92
+ byActor,
92
93
  currentAuditContext,
93
94
  type Db,
94
95
  ensureFormLibraryTypes,
@@ -106,6 +107,7 @@ import {
106
107
  readLedger,
107
108
  readReport,
108
109
  readUrlOptions,
110
+ SingleUseTokens,
109
111
  searchProvidersOf,
110
112
  TransferRunRepository,
111
113
  UserRepository,
@@ -239,6 +241,18 @@ import { noNodesPage } from './no-nodes.ts'
239
241
  import { NotImplementedLog } from './not-implemented.ts'
240
242
  import { overview, readOverviewQuery } from './overview.ts'
241
243
  import { createDeps, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
244
+ import {
245
+ PREVIEW_LINK_COOKIE,
246
+ PREVIEW_LINK_COOKIE_SECONDS,
247
+ PREVIEW_LINK_ISSUER,
248
+ PREVIEW_LINK_PARAM,
249
+ PREVIEW_LINK_SECONDS,
250
+ previewLinkCookie,
251
+ readPreviewCookie,
252
+ readPreviewLink,
253
+ signPreviewCookie,
254
+ signPreviewLink,
255
+ } from './preview-links.ts'
242
256
  import {
243
257
  previewSigningSecret,
244
258
  previewUser,
@@ -688,6 +702,7 @@ export async function createServer(
688
702
  provider:
689
703
  config.backofficeIdentityProviders.find((p) => p.oidc.id === identity.exchangedThrough)
690
704
  ?.oidc.name ?? identity.exchangedThrough,
705
+ ...(identity.exchangedActor ? { actor: identity.exchangedActor } : {}),
691
706
  }
692
707
  if (context && principal.viewingAs)
693
708
  context.viewing = {
@@ -942,9 +957,12 @@ export async function createServer(
942
957
  { id },
943
958
  )
944
959
  if (exchanging.length > 0)
945
- log.info('The remote exchanges tokens from {providers}', {
946
- providers: exchanging.map((p) => p.oidc.id).join(', '),
947
- })
960
+ log.info(
961
+ config.remote.enabled
962
+ ? 'The remote exchanges tokens from {providers}'
963
+ : "The remote is off, and its token endpoint answers only {providers}'s exchange for a person",
964
+ { providers: exchanging.map((p) => p.oidc.id).join(', ') },
965
+ )
948
966
  const people =
949
967
  exchanging.length === 0
950
968
  ? undefined
@@ -980,10 +998,16 @@ export async function createServer(
980
998
  ? undefined
981
999
  : 'the person has no access to the back office'
982
1000
  },
983
- signIn: async (key, provider, seconds, ip) => {
1001
+ signIn: async (key, provider, seconds, ip, actor) => {
984
1002
  const user = await users.byKey(key)
985
1003
  if (!user) return { refused: 'the person no longer exists' }
986
- const result = await auth.signInByExchange(user.userName, provider, seconds, ip)
1004
+ const result = await auth.signInByExchange(
1005
+ user.userName,
1006
+ provider,
1007
+ seconds,
1008
+ ip,
1009
+ actor,
1010
+ )
987
1011
  if (result.status === 'success') return { accessToken: result.accessToken }
988
1012
  return {
989
1013
  refused:
@@ -1004,8 +1028,9 @@ export async function createServer(
1004
1028
  entityKey: outcome.ok ? outcome.account.key : null,
1005
1029
  entityName: outcome.ok ? outcome.account.email : null,
1006
1030
  detail: outcome.ok
1007
- ? `Signed in through ${outcome.provider.oidc.name}, by exchange at the remote`
1031
+ ? `Signed in through ${outcome.provider.oidc.name}${byActor(outcome.actor)}, by exchange at the remote`
1008
1032
  : `Refused${outcome.provider ? ` through ${outcome.provider.oidc.name}` : ''}: ${outcome.reason}`,
1033
+ actor: outcome.ok ? (outcome.actor ?? null) : null,
1009
1034
  ...clientAddress(request),
1010
1035
  }),
1011
1036
  })
@@ -1690,6 +1715,7 @@ export async function createServer(
1690
1715
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1691
1716
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1692
1717
  const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1718
+ const previewLinkPath = `${paths.pluginPath}/api/preview-link`
1693
1719
  const selfAudited = [
1694
1720
  `${paths.pluginPath}/api/email/`,
1695
1721
  `${paths.pluginPath}/api/schema-transfer/`,
@@ -1920,6 +1946,109 @@ export async function createServer(
1920
1946
  })
1921
1947
  }
1922
1948
 
1949
+ /** Story 368: a preview link for a page its person may read, audited as them. */
1950
+ async function askForPreviewLink(request: Request): Promise<Response> {
1951
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
1952
+ const principal = await authenticate(request)
1953
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1954
+ const asked = (await request.json().catch(() => ({}))) as {
1955
+ document?: unknown
1956
+ culture?: unknown
1957
+ }
1958
+ const document = typeof asked.document === 'string' ? asked.document : ''
1959
+ const culture = typeof asked.culture === 'string' && asked.culture ? asked.culture : null
1960
+ if (!UUID_PATTERN.test(document))
1961
+ return Response.json({ title: 'Name the page by its key' }, { status: 400 })
1962
+ const standing = await previewUser(db, { key: principal.id })
1963
+ if (!standing || !(await canReadDocument(principal, document, nodeLookup)))
1964
+ return Response.json({ title: 'You may not read this page' }, { status: 403 })
1965
+ const key = normaliseUuid(document)
1966
+ const page = await (await draftCache()).byKey(key, culture)
1967
+ const published = await cache.byKey(key, culture)
1968
+ const expires = Date.now() + PREVIEW_LINK_SECONDS * 1000
1969
+ const token = signPreviewLink(previewSecret, {
1970
+ user: standing.id,
1971
+ stamp: standing.stamp,
1972
+ document: key,
1973
+ culture,
1974
+ expires,
1975
+ id: crypto.randomUUID(),
1976
+ })
1977
+ const url = new URL(published?.url ?? `/${key}`, publicOrigin(request, config))
1978
+ url.searchParams.set(PREVIEW_LINK_PARAM, token)
1979
+ await recordAudit(db, {
1980
+ category: 'content',
1981
+ action: 'PreviewLink',
1982
+ source: 'request',
1983
+ userKey: principal.id,
1984
+ userName: principal.name,
1985
+ entityType: 'Document',
1986
+ entityKey: key,
1987
+ entityName: page?.name ?? published?.name ?? null,
1988
+ detail: culture ? `A preview link, for ${culture}` : 'A preview link',
1989
+ ...clientAddress(request),
1990
+ })
1991
+ return Response.json(
1992
+ { url: url.toString(), expiresAt: new Date(expires).toISOString() },
1993
+ { headers: { 'cache-control': PRIVATE_NO_STORE } },
1994
+ )
1995
+ }
1996
+
1997
+ /**
1998
+ * A link's first use (story 368): its token swapped for the cookie, once, and
1999
+ * the browser sent to the same address without it. A token that is spent,
2000
+ * expired or forged is dropped from the address the same way, with no cookie.
2001
+ */
2002
+ async function usePreviewLink(request: Request, url: URL): Promise<Response | undefined> {
2003
+ if (request.method !== 'GET' && request.method !== 'HEAD') return undefined
2004
+ const token = url.searchParams.get(PREVIEW_LINK_PARAM)
2005
+ if (token === null) return undefined
2006
+ const clean = new URL(url)
2007
+ clean.searchParams.delete(PREVIEW_LINK_PARAM)
2008
+ const headers = new Headers({
2009
+ location: `${clean.pathname}${clean.search}`,
2010
+ 'cache-control': PRIVATE_NO_STORE,
2011
+ 'referrer-policy': 'no-referrer',
2012
+ })
2013
+ const claims = readPreviewLink(previewSecret, token)
2014
+ const standing = claims ? await previewUser(db, { id: claims.user }) : undefined
2015
+ if (
2016
+ claims &&
2017
+ standing?.stamp === claims.stamp &&
2018
+ (await new SingleUseTokens(db).use(PREVIEW_LINK_ISSUER, claims.id, new Date(claims.expires)))
2019
+ )
2020
+ headers.set(
2021
+ 'set-cookie',
2022
+ previewLinkCookie(
2023
+ signPreviewCookie(previewSecret, {
2024
+ user: claims.user,
2025
+ stamp: claims.stamp,
2026
+ document: claims.document,
2027
+ culture: claims.culture,
2028
+ expires: Date.now() + PREVIEW_LINK_COOKIE_SECONDS * 1000,
2029
+ }),
2030
+ config.secureCookies,
2031
+ ),
2032
+ )
2033
+ return new Response(null, { status: 303, headers })
2034
+ }
2035
+
2036
+ /** Who a used link previews as, and which page: undefined once they may not, or it has run out. */
2037
+ async function linkedPreview(request: Request) {
2038
+ const value = readCookie(request, PREVIEW_LINK_COOKIE)
2039
+ const claims = value ? readPreviewCookie(previewSecret, value) : undefined
2040
+ if (!claims) return undefined
2041
+ const standing = await previewUser(db, { id: claims.user })
2042
+ if (standing?.stamp !== claims.stamp) return undefined
2043
+ const identity = await auth.identityOf(claims.user)
2044
+ if (!identity) return undefined
2045
+ return {
2046
+ principal: await principalFrom(identity),
2047
+ document: claims.document,
2048
+ culture: claims.culture,
2049
+ }
2050
+ }
2051
+
1923
2052
  /** What a chain is carrying through one request (story 210). */
1924
2053
  interface ChainRun {
1925
2054
  original: URL
@@ -1942,6 +2071,8 @@ export async function createServer(
1942
2071
 
1943
2072
  /** A site request: the middleware chain around crombolo's own handling, when the site has one. */
1944
2073
  async function siteRequest(request: Request, url: URL): Promise<Response> {
2074
+ const linked = await usePreviewLink(request, url)
2075
+ if (linked) return linked
1945
2076
  if (!anyMiddleware()) return siteFiles(request)
1946
2077
  const run: ChainRun = {
1947
2078
  original: url,
@@ -2716,6 +2847,9 @@ export async function createServer(
2716
2847
  )
2717
2848
  }
2718
2849
 
2850
+ // Story 368: a link that opens one page's draft in any browser.
2851
+ if (pathname === previewLinkPath) return askForPreviewLink(request)
2852
+
2719
2853
  // Story 314: an administrator's session seen as user groups, and back.
2720
2854
  if (pathname === viewAsPath) {
2721
2855
  const identity = await identify(request)
@@ -3726,18 +3860,22 @@ export async function createServer(
3726
3860
  * draft of the page it resolves to.
3727
3861
  */
3728
3862
  async function renderPreview(request: Request, pathname: string, host: string) {
3729
- if (!readCookie(request, PREVIEW_COOKIE)) return undefined
3730
- const principal = await authenticate(request)
3863
+ const editor = readCookie(request, PREVIEW_COOKIE) ? await authenticate(request) : undefined
3864
+ // Story 368: else a used preview link, for its one page.
3865
+ const link = editor ? undefined : await linkedPreview(request)
3866
+ const principal = editor ?? link?.principal
3731
3867
  if (!principal) return undefined
3732
3868
  const byKey = /^\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(
3733
3869
  pathname,
3734
3870
  )
3735
3871
  const key = byKey?.[1] ?? (await cache.resolve(host, pathname))?.content.key
3736
3872
  if (!key) return undefined
3737
- const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
3873
+ if (link && normaliseUuid(key) !== normaliseUuid(link.document)) return undefined
3874
+ const culture = link ? link.culture : new URL(request.url).searchParams.get('culture')
3875
+ const draft = await draftModel(key, culture, principal)
3738
3876
  if (!draft) return undefined
3739
3877
  // The previewing editor is the visitor: signed out, or a member they chose (story 264).
3740
- const member = await previewMember(request, principal)
3878
+ const member = link ? undefined : await previewMember(request, principal)
3741
3879
  return renderer.renderModel(draft.content, draft.culture, {
3742
3880
  ...(await pageRequest(request)),
3743
3881
  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',
package/src/telemetry.ts CHANGED
@@ -361,6 +361,7 @@ export function withTraceHeaders(headers: Record<string, string>): Record<string
361
361
  export function routeOf(pathname: string, backOfficePath: string): string {
362
362
  if (pathname === '/health') return '/health'
363
363
  if (pathname.startsWith('/umbraco/delivery/api/')) return '/umbraco/delivery/api/*'
364
+ if (pathname.startsWith('/crombolo/remote/v1/')) return '/crombolo/remote/v1/*'
364
365
  if (pathname.startsWith(`${backOfficePath}/management/api/`))
365
366
  return `${backOfficePath}/management/api/*`
366
367
  if (pathname === backOfficePath || pathname.startsWith(`${backOfficePath}/`))