@crombolo/server 0.18.0 → 0.19.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.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.18.0",
34
- "@crombolo/api-management": "0.18.0",
35
- "@crombolo/assistant": "0.18.0",
36
- "@crombolo/auth": "0.18.0",
37
- "@crombolo/backoffice-host": "0.18.0",
38
- "@crombolo/contracts": "0.18.0",
39
- "@crombolo/core": "0.18.0",
40
- "@crombolo/data": "0.18.0",
41
- "@crombolo/render": "0.18.0",
42
- "@crombolo/schema": "0.18.0",
43
- "@crombolo/transfer": "0.18.0",
33
+ "@crombolo/api-delivery": "0.19.0",
34
+ "@crombolo/api-management": "0.19.0",
35
+ "@crombolo/assistant": "0.19.0",
36
+ "@crombolo/auth": "0.19.0",
37
+ "@crombolo/backoffice-host": "0.19.0",
38
+ "@crombolo/contracts": "0.19.0",
39
+ "@crombolo/core": "0.19.0",
40
+ "@crombolo/data": "0.19.0",
41
+ "@crombolo/render": "0.19.0",
42
+ "@crombolo/schema": "0.19.0",
43
+ "@crombolo/transfer": "0.19.0",
44
44
  "@logtape/logtape": "^2.3.8"
45
45
  }
46
46
  }
@@ -464,8 +464,12 @@ export function createDocumentPort(
464
464
  return toTreeItems(repo, await repo.nodes.byKeys(keys))
465
465
  },
466
466
 
467
- async collection(parentKey: string | null, paging: SkipTake): Promise<Page<DocumentAggregate>> {
468
- const page = await repo.children(parentKey, paging.skip, paging.take)
467
+ async collection(
468
+ parentKey: string | null,
469
+ paging: SkipTake,
470
+ excludeKeys: readonly string[] = [],
471
+ ): Promise<Page<DocumentAggregate>> {
472
+ const page = await repo.children(parentKey, paging.skip, paging.take, excludeKeys)
469
473
  const items: DocumentAggregate[] = []
470
474
  for (const row of page.items) {
471
475
  const aggregate = await repo.load(row)
package/src/config.ts CHANGED
@@ -740,4 +740,4 @@ export function describeDatabase(
740
740
  }
741
741
  }
742
742
 
743
- export const VERSION = '0.18.0'
743
+ export const VERSION = '0.19.0'
@@ -26,6 +26,7 @@ import {
26
26
  expireCookie,
27
27
  hashPassword,
28
28
  isNativeHash,
29
+ isSameOrigin,
29
30
  memberCookieName,
30
31
  passwordConfigJson,
31
32
  readCookie,
@@ -125,30 +126,6 @@ async function readInput(request: Request): Promise<Record<string, string>> {
125
126
  */
126
127
  const safeReturnUrl = (value: string | undefined): string | undefined => localReturnUrl(value)
127
128
 
128
- /**
129
- * Whether a POST came from this site, rather than a form on someone else's.
130
- *
131
- * These three endpoints take a plain form post and act on the member cookie, and
132
- * `SameSite=Lax` does not cover a cross-site POST's effect here: an attacker's
133
- * form can sign a visitor into an account the attacker controls, or out of their
134
- * own. Umbraco's surface controllers carry an antiforgery token for this; with no
135
- * token to hand, the fetch metadata a browser sends is what distinguishes them.
136
- *
137
- * A request with neither header is allowed: that is a non-browser client, which
138
- * carries no ambient cookies to abuse.
139
- */
140
- function fromThisSite(request: Request): boolean {
141
- const site = request.headers.get('sec-fetch-site')
142
- if (site) return site === 'same-origin' || site === 'none'
143
- const origin = request.headers.get('origin')
144
- if (!origin) return true
145
- try {
146
- return origin === new URL(request.url).origin
147
- } catch {
148
- return false
149
- }
150
- }
151
-
152
129
  export function createMemberAuth(
153
130
  db: Db,
154
131
  config: CromboloConfig,
@@ -468,7 +445,8 @@ export function createMemberAuth(
468
445
  })
469
446
  }
470
447
  if (request.method !== 'POST') return new Response(null, { status: 405 })
471
- if (!fromThisSite(request)) return new Response('Forbidden', { status: 403 })
448
+ if (!isSameOrigin(request, config.applicationUrl || undefined))
449
+ return new Response('Forbidden', { status: 403 })
472
450
  const input = await readInput(request)
473
451
  switch (step) {
474
452
  case 'setup': {
@@ -603,7 +581,10 @@ export function createMemberAuth(
603
581
  if (action === '2fa' || action.startsWith('2fa/'))
604
582
  return manageTwoFactor(request, action.slice(4))
605
583
  if (request.method !== 'POST') return new Response(null, { status: 405 })
606
- if (!fromThisSite(request)) return new Response('Forbidden', { status: 403 })
584
+ // SameSite=Lax still lets a sibling subdomain post here, signing a visitor
585
+ // into an account the attacker holds, or out of their own.
586
+ if (!isSameOrigin(request, config.applicationUrl || undefined))
587
+ return new Response('Forbidden', { status: 403 })
607
588
  switch (action) {
608
589
  case 'login':
609
590
  return login(request)
package/src/ports.ts CHANGED
@@ -699,7 +699,11 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
699
699
  const enabled = await service.enable(userKey, provider, secret, code)
700
700
  return enabled.ok
701
701
  ? { ok: true, recoveryCodes: enabled.value.recoveryCodes }
702
- : { ok: false, message: enabled.message }
702
+ : {
703
+ ok: false,
704
+ message: enabled.message,
705
+ alreadyEnabled: enabled.reason === 'alreadyEnabled',
706
+ }
703
707
  },
704
708
  async disable(userKey, code) {
705
709
  const disabled = await service.disable(userKey, provider, code)
package/src/seo.ts CHANGED
@@ -155,8 +155,8 @@ export interface SeoHostOptions {
155
155
  cache: PublishedCache
156
156
  /** Whether a visitor who is not signed in would be turned away from a page. */
157
157
  isProtected(content: PublishedContent): Promise<boolean>
158
- /** A document's latest saved version, as the preview renders it. */
159
- draft(key: string, culture: string | null): Promise<DraftModel | undefined>
158
+ /** A document's latest saved version, as the preview renders it, if `principal` may read it. */
159
+ draft(key: string, culture: string | null, principal: Principal): Promise<DraftModel | undefined>
160
160
  }
161
161
 
162
162
  export interface SeoHost {
@@ -311,11 +311,11 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
311
311
  return false
312
312
  }
313
313
 
314
- const preview = async (request: Request): Promise<Response> => {
314
+ const preview = async (request: Request, principal: Principal): Promise<Response> => {
315
315
  const url = new URL(request.url)
316
316
  const key = url.searchParams.get('document') ?? ''
317
317
  if (!UUID.test(key)) return Response.json({ message: 'Choose a page.' }, { status: 400 })
318
- const draft = await options.draft(key, url.searchParams.get('culture') || null)
318
+ const draft = await options.draft(key, url.searchParams.get('culture') || null, principal)
319
319
  if (!draft) return Response.json({ message: 'That page could not be found.' }, { status: 404 })
320
320
  const origin = originOf(request, config)
321
321
  const snapshot = await cache.snapshot()
@@ -338,7 +338,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
338
338
  }
339
339
 
340
340
  const handle: SeoHost['handle'] = async (request, subpath, principal) => {
341
- if (subpath === '/preview' && request.method === 'GET') return preview(request)
341
+ if (subpath === '/preview' && request.method === 'GET') return preview(request, principal)
342
342
  if (subpath !== '/settings') return undefined
343
343
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
344
344
  if (request.method === 'GET') return Response.json(await settings())
package/src/server.ts CHANGED
@@ -11,6 +11,7 @@ import { join } from 'node:path'
11
11
  import { createDeliveryApi, resolveDeliveryApiSettings } from '@crombolo/api-delivery'
12
12
  import {
13
13
  type ClientAddress,
14
+ canReadDocument,
14
15
  createManagementApiRouter,
15
16
  hasSection,
16
17
  type Principal,
@@ -21,6 +22,8 @@ import {
21
22
  cookieNames,
22
23
  createAuthRoutes,
23
24
  expireCookie,
25
+ isSafeMethod,
26
+ isSameOrigin,
24
27
  REDACTED,
25
28
  readCookie,
26
29
  serializeCookie,
@@ -371,6 +374,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
371
374
  backOfficePath: paths.backOfficePath,
372
375
  service: auth,
373
376
  cookies,
377
+ applicationUrl: config.applicationUrl || undefined,
378
+ allowLocalLogin: config.allowLocalLogin,
374
379
  twoFactor: {
375
380
  providersFor: (userKey) => twoFactor.providers(userKey),
376
381
  verify: (userKey, provider, code) =>
@@ -448,8 +453,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
448
453
  async function authenticate(request: Request): Promise<Principal | undefined> {
449
454
  const header = request.headers.get('authorization')
450
455
  const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
451
- const token = bearer && bearer !== REDACTED ? bearer : readCookie(request, names.accessToken)
456
+ const fromCookie = !bearer || bearer === REDACTED
457
+ const token = fromCookie ? readCookie(request, names.accessToken) : bearer
452
458
  if (!token) return undefined
459
+ // The browser sends the cookie wherever the request came from, so a write
460
+ // that relies on it must come from this site; a real bearer token need not.
461
+ if (
462
+ fromCookie &&
463
+ !isSafeMethod(request.method) &&
464
+ !isSameOrigin(request, config.applicationUrl || undefined)
465
+ ) {
466
+ log.warning('Refused a signed-in {method} {path} from another site', {
467
+ method: request.method,
468
+ path: new URL(request.url).pathname,
469
+ })
470
+ return undefined
471
+ }
453
472
 
454
473
  const identity = await auth.resolveAccessToken(token)
455
474
  if (!identity) return undefined
@@ -695,8 +714,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
695
714
  search: (term, options) => new SiteSearch(db).query(term, options),
696
715
  })
697
716
 
698
- /** A document's latest saved version, as preview shows it, in the published tree's context. */
699
- async function draftModel(key: string, requested: string | null) {
717
+ const nodeLookup = createNodeLookup(db)
718
+
719
+ /**
720
+ * A document's latest saved version, as preview shows it, in the published
721
+ * tree's context — or undefined when `principal` may not read it.
722
+ */
723
+ async function draftModel(key: string, requested: string | null, principal: Principal) {
724
+ if (!(await canReadDocument(principal, key, nodeLookup))) return undefined
700
725
  const draft = await loadDraftNode(db, key, {
701
726
  nodeState: schema.nodeState,
702
727
  nodeId: schema.nodeId,
@@ -803,7 +828,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
803
828
  const api = createManagementApiRouter({
804
829
  deps: managementDeps,
805
830
  authenticate,
806
- nodes: createNodeLookup(db),
831
+ nodes: nodeLookup,
807
832
  allowLocalLogin: config.allowLocalLogin,
808
833
  audit: createAuditSink(db),
809
834
  clientAddress,
@@ -1929,13 +1954,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1929
1954
  * draft of the page it resolves to.
1930
1955
  */
1931
1956
  async function renderPreview(request: Request, pathname: string, host: string) {
1932
- if (!readCookie(request, PREVIEW_COOKIE) || !(await authenticate(request))) return undefined
1957
+ if (!readCookie(request, PREVIEW_COOKIE)) return undefined
1958
+ const principal = await authenticate(request)
1959
+ if (!principal) return undefined
1933
1960
  const byKey = /^\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(
1934
1961
  pathname,
1935
1962
  )
1936
1963
  const key = byKey?.[1] ?? (await cache.resolve(host, pathname))?.content.key
1937
1964
  if (!key) return undefined
1938
- const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'))
1965
+ const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
1939
1966
  if (!draft) return undefined
1940
1967
  return renderer.renderModel(draft.content, draft.culture, {
1941
1968
  ...(await pageRequest(request)),
package/src/two-factor.ts CHANGED
@@ -25,7 +25,11 @@ export const MEMBER_TWO_FACTOR_PROVIDER = 'UmbracoMemberAppAuthenticator'
25
25
 
26
26
  export type TwoFactorResult<T = undefined> =
27
27
  | ({ ok: true } & (T extends undefined ? object : { value: T }))
28
- | { ok: false; reason: 'unavailable' | 'invalidCode' | 'notEnabled'; message: string }
28
+ | {
29
+ ok: false
30
+ reason: 'unavailable' | 'invalidCode' | 'notEnabled' | 'alreadyEnabled'
31
+ message: string
32
+ }
29
33
 
30
34
  export class TwoFactorService {
31
35
  #repository: TwoFactorRepository
@@ -69,7 +73,12 @@ export class TwoFactorService {
69
73
  return { ok: true, value: { secret, qrCodeSetupImageUrl: qrCodeDataUrl(uri), otpauthUri: uri } }
70
74
  }
71
75
 
72
- /** Turns the provider on when `code` is right for `secret`; answers with the recovery codes, shown once. */
76
+ /**
77
+ * Turns the provider on when `code` is right for `secret`; answers with the
78
+ * recovery codes, shown once. Refused while it is already on: replacing the
79
+ * authenticator means turning it off first, which asks for the current one, so
80
+ * a stolen session cannot swap in its own.
81
+ */
73
82
  async enable(
74
83
  ownerKey: string,
75
84
  provider: string,
@@ -77,6 +86,12 @@ export class TwoFactorService {
77
86
  code: string,
78
87
  ): Promise<TwoFactorResult<{ recoveryCodes: string[] }>> {
79
88
  if (!this.#key) return this.#unavailable()
89
+ if (await this.#repository.get(ownerKey, provider))
90
+ return {
91
+ ok: false,
92
+ reason: 'alreadyEnabled',
93
+ message: 'Two-factor sign-in is already on. Turn it off first to use another app.',
94
+ }
80
95
  const step = verifyTotp(secret, code)
81
96
  if (step === undefined)
82
97
  return {