@fabrika/proxy-core 0.9.0-dev.2 → 0.9.0-dev.21
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 -5
- package/src/authorize.ts +105 -33
- package/src/brand.ts +121 -0
- package/src/cache.ts +0 -0
- package/src/constants.ts +9 -0
- package/src/handoff.ts +8 -0
- package/src/headers.ts +24 -6
- package/src/iam.ts +3 -1
- package/src/index.ts +4 -0
- package/src/manifest.ts +210 -12
- package/src/page-style.ts +505 -0
- package/src/pages.ts +150 -0
- package/src/service.ts +49 -48
- package/types/src/authorize.d.ts +27 -3
- package/types/src/brand.d.ts +104 -0
- package/types/src/cache.d.ts +6 -3
- package/types/src/constants.d.ts +7 -0
- package/types/src/handoff.d.ts +5 -0
- package/types/src/headers.d.ts +16 -4
- package/types/src/index.d.ts +3 -1
- package/types/src/manifest.d.ts +2187 -1160
- package/types/src/page-style.d.ts +40 -0
- package/types/src/pages.d.ts +62 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/proxy-core",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.21",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,6 +26,16 @@
|
|
|
26
26
|
"types": "./types/src/manifest.d.ts",
|
|
27
27
|
"default": "./src/manifest.ts"
|
|
28
28
|
},
|
|
29
|
+
"./brand": {
|
|
30
|
+
"bun": "./src/brand.ts",
|
|
31
|
+
"types": "./types/src/brand.d.ts",
|
|
32
|
+
"default": "./src/brand.ts"
|
|
33
|
+
},
|
|
34
|
+
"./page-style": {
|
|
35
|
+
"bun": "./src/page-style.ts",
|
|
36
|
+
"types": "./types/src/page-style.d.ts",
|
|
37
|
+
"default": "./src/page-style.ts"
|
|
38
|
+
},
|
|
29
39
|
"./headers": {
|
|
30
40
|
"bun": "./src/headers.ts",
|
|
31
41
|
"types": "./types/src/headers.d.ts",
|
|
@@ -33,14 +43,14 @@
|
|
|
33
43
|
}
|
|
34
44
|
},
|
|
35
45
|
"scripts": {
|
|
36
|
-
"typecheck": "
|
|
46
|
+
"typecheck": "tsrs --build tsconfig.test.json",
|
|
37
47
|
"test": "bun test"
|
|
38
48
|
},
|
|
39
49
|
"dependencies": {
|
|
40
50
|
"zod": "^3.25.76",
|
|
41
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
42
|
-
"@fabrika/jwks": "0.9.0-dev.
|
|
51
|
+
"@fabrika/auth-core": "0.9.0-dev.21",
|
|
52
|
+
"@fabrika/jwks": "0.9.0-dev.21",
|
|
43
53
|
"jose": "^5.9.0",
|
|
44
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
54
|
+
"@fabrika/platform": "0.9.0-dev.21"
|
|
45
55
|
}
|
|
46
56
|
}
|
package/src/authorize.ts
CHANGED
|
@@ -29,18 +29,24 @@ import {
|
|
|
29
29
|
FORM_MULTIPART_TYPE,
|
|
30
30
|
FORM_URLENCODED_TYPE,
|
|
31
31
|
formatEndpointHeader,
|
|
32
|
+
isLocale,
|
|
33
|
+
type Locale,
|
|
34
|
+
LOCALE_COOKIE,
|
|
35
|
+
LOCALE_PARAM,
|
|
32
36
|
planEndpoint,
|
|
37
|
+
sameOriginTarget,
|
|
33
38
|
satisfies,
|
|
34
39
|
SESSION_COOKIE,
|
|
35
40
|
TOKEN_REFRESH_SKEW_SECONDS,
|
|
36
41
|
type TokenCaller,
|
|
37
42
|
} from '@fabrika/auth-core'
|
|
38
43
|
import { cacheKey, type TokenCache } from './cache'
|
|
39
|
-
import { LOGIN_REDIRECT_PARAM } from './constants'
|
|
44
|
+
import { LOGIN_REDIRECT_PARAM, SIGNOUT_RELEASE_PATH } from './constants'
|
|
40
45
|
import { carriesPlatformKey, readBearer, readCookie } from './credentials'
|
|
41
|
-
import { createHandoffAttempt, type HandoffAttempt, handoffCookieName, setHandoffParams } from './handoff'
|
|
46
|
+
import { createHandoffAttempt, type HandoffAttempt, handoffCookieName, setHandoffParams, unmatchedVerifier } from './handoff'
|
|
42
47
|
import { type DelegationIssuer, type IamGateway, IamUnavailableError } from './iam'
|
|
43
48
|
import {
|
|
49
|
+
audienceOf,
|
|
44
50
|
isApplicationEntry,
|
|
45
51
|
type ManifestEndpointRow,
|
|
46
52
|
type OAuthBearerChallenge,
|
|
@@ -48,6 +54,7 @@ import {
|
|
|
48
54
|
oauthResourceOfRow,
|
|
49
55
|
type ProxyApp,
|
|
50
56
|
} from './manifest'
|
|
57
|
+
import { FETCH_MODE_HEADER } from './pages'
|
|
51
58
|
import { TokenVerifier } from './verifier'
|
|
52
59
|
|
|
53
60
|
/** Every way a request can be refused. Coarse on purpose — these are logged, not returned to clients. */
|
|
@@ -75,8 +82,10 @@ export type DenyReason =
|
|
|
75
82
|
| 'caller_kind'
|
|
76
83
|
/** The token does not satisfy the endpoint's requirement. */
|
|
77
84
|
| 'insufficient_permission'
|
|
78
|
-
/** A session request that is not a `GET
|
|
85
|
+
/** A session request that is not a `GET`, or a sign-out, did not come from the app's own origin. */
|
|
79
86
|
| 'cross_site'
|
|
87
|
+
/** A sign-out's return is absent or not a path on the app's own origin. */
|
|
88
|
+
| 'bad_redirect'
|
|
80
89
|
/** The request's `Content-Type` is not one the endpoint admits. */
|
|
81
90
|
| 'content_type'
|
|
82
91
|
/**
|
|
@@ -111,8 +120,8 @@ export type Decision =
|
|
|
111
120
|
/** The `Access-Control-Allow-Origin` the answer carries: the request's admitted origin, `*`, or none. */
|
|
112
121
|
crossOrigin: string | null
|
|
113
122
|
/**
|
|
114
|
-
* Whether the request's own `Authorization` reaches the application: on
|
|
115
|
-
* carries a platform key. Every other anonymous request loses it (ADR-0022 rule 3).
|
|
123
|
+
* Whether the request's own `Authorization` reaches the application: on the ops row, and on a webhook row that
|
|
124
|
+
* forwards it unless it carries a platform key. Every other anonymous request loses it (ADR-0022 rule 3).
|
|
116
125
|
*/
|
|
117
126
|
forwardsAuthorization: boolean
|
|
118
127
|
}
|
|
@@ -143,6 +152,11 @@ export type Decision =
|
|
|
143
152
|
* was going — read from the code server-side, never from the request.
|
|
144
153
|
*/
|
|
145
154
|
| { outcome: 'handoff'; status: 302; location: string; session: string; expiresAt: number; handoffState: string }
|
|
155
|
+
/**
|
|
156
|
+
* A same-origin sign-out (ADR-0067 §5): the app session cookie is cleared and the browser goes to IAM's release,
|
|
157
|
+
* which returns it to `location`'s own redirect on this app's origin.
|
|
158
|
+
*/
|
|
159
|
+
| { outcome: 'signout'; status: 302; location: string }
|
|
146
160
|
|
|
147
161
|
/** The original request, reconstructed from what `forward_auth` forwarded. */
|
|
148
162
|
export interface ForwardedRequest {
|
|
@@ -178,13 +192,6 @@ export interface AuthorizerOptions {
|
|
|
178
192
|
delegations?: DelegationIssuer | null
|
|
179
193
|
}
|
|
180
194
|
|
|
181
|
-
/**
|
|
182
|
-
* The browser's own description of what issued the request. Read from the FORWARDED headers like
|
|
183
|
-
* everything else a decision depends on — verified against caddy 2.10.2, whose `forward_auth`
|
|
184
|
-
* subrequest carries the original `Sec-Fetch-*` verbatim.
|
|
185
|
-
*/
|
|
186
|
-
const FETCH_MODE_HEADER = 'Sec-Fetch-Mode'
|
|
187
|
-
|
|
188
195
|
/** Fetch metadata the browser writes and page script cannot: `same-origin` only for a request from this origin. */
|
|
189
196
|
const FETCH_SITE_HEADER = 'Sec-Fetch-Site'
|
|
190
197
|
|
|
@@ -415,7 +422,10 @@ export class Authorizer {
|
|
|
415
422
|
if (issuer === undefined || issuer === null) {
|
|
416
423
|
return { ok: true, grant: null }
|
|
417
424
|
}
|
|
418
|
-
const result = await this.callIam(
|
|
425
|
+
const result = await this.callIam(
|
|
426
|
+
'requestDelegation',
|
|
427
|
+
() => issuer.requestDelegation({ app: audienceOf(app), credential: token, requestId, endpoint }),
|
|
428
|
+
)
|
|
419
429
|
return result.ok && result.grant !== ''
|
|
420
430
|
? { ok: true, grant: result.grant }
|
|
421
431
|
: { ok: false, denial: { outcome: 'deny', status: 403, reason: 'delegation_refused' } }
|
|
@@ -431,7 +441,7 @@ export class Authorizer {
|
|
|
431
441
|
if (bearer === null) {
|
|
432
442
|
return { ok: false, denial: { outcome: 'deny', status: 401, reason: 'no_credential', challenge } }
|
|
433
443
|
}
|
|
434
|
-
const verified = await this.verifier.verify(bearer, { kind: 'resource', app: app
|
|
444
|
+
const verified = await this.verifier.verify(bearer, { kind: 'resource', app: audienceOf(app), resource: binding.resource.resource })
|
|
435
445
|
if (!verified.ok) {
|
|
436
446
|
return verified.reason === 'unavailable'
|
|
437
447
|
? { ok: false, denial: { outcome: 'deny', status: 503, reason: 'iam_unavailable' } }
|
|
@@ -457,7 +467,7 @@ export class Authorizer {
|
|
|
457
467
|
const key = cacheKey(app.id, 'key', bearer)
|
|
458
468
|
const cached = this.cache?.get(key)
|
|
459
469
|
if (cached !== undefined && cached.expiresAt - this.now() > TOKEN_REFRESH_SKEW_SECONDS) {
|
|
460
|
-
const verified = await this.verifier.verify(cached.token, app
|
|
470
|
+
const verified = await this.verifier.verify(cached.token, audienceOf(app))
|
|
461
471
|
if (verified.ok) {
|
|
462
472
|
return { ok: true, token: cached.token, claims: verified.claims }
|
|
463
473
|
}
|
|
@@ -471,11 +481,11 @@ export class Authorizer {
|
|
|
471
481
|
this.cache?.delete(key)
|
|
472
482
|
}
|
|
473
483
|
|
|
474
|
-
const minted = await this.callIam('mintFromKey', () => this.options.iam.mintFromKey({ app: app
|
|
484
|
+
const minted = await this.callIam('mintFromKey', () => this.options.iam.mintFromKey({ app: audienceOf(app), key: bearer, requestId }))
|
|
475
485
|
if (!minted.ok) {
|
|
476
486
|
return { ok: false, denial: { outcome: 'deny', status: minted.reason === 'invalid_key' ? 401 : 403, reason: minted.reason } }
|
|
477
487
|
}
|
|
478
|
-
const verified = await this.verifier.verify(minted.token, app
|
|
488
|
+
const verified = await this.verifier.verify(minted.token, audienceOf(app))
|
|
479
489
|
if (!verified.ok) {
|
|
480
490
|
// We just minted it, so a verification miss is a config/clock/key problem — not a client
|
|
481
491
|
// error. Either way: deny.
|
|
@@ -508,7 +518,7 @@ export class Authorizer {
|
|
|
508
518
|
const key = cacheKey(app.id, 'session', session)
|
|
509
519
|
const cached = this.cache?.get(key)
|
|
510
520
|
if (cached !== undefined && cached.expiresAt - now > TOKEN_REFRESH_SKEW_SECONDS) {
|
|
511
|
-
const verified = await this.verifier.verify(cached.token, app
|
|
521
|
+
const verified = await this.verifier.verify(cached.token, audienceOf(app))
|
|
512
522
|
if (verified.ok && verified.claims.ptype === 'user') {
|
|
513
523
|
return { ok: true, token: cached.token, claims: verified.claims }
|
|
514
524
|
}
|
|
@@ -520,13 +530,13 @@ export class Authorizer {
|
|
|
520
530
|
this.cache?.delete(key)
|
|
521
531
|
}
|
|
522
532
|
|
|
523
|
-
const minted = await this.callIam('mintToken', () => this.options.iam.mintToken({ app: app
|
|
533
|
+
const minted = await this.callIam('mintToken', () => this.options.iam.mintToken({ app: audienceOf(app), session, requestId: request.requestId }))
|
|
524
534
|
if (!minted.ok) {
|
|
525
535
|
return minted.reason === 'token_too_large'
|
|
526
536
|
? { ok: false, status: 'refused', reason: minted.reason }
|
|
527
537
|
: { ok: false, status: 'miss', reason: minted.reason }
|
|
528
538
|
}
|
|
529
|
-
const verified = await this.verifier.verify(minted.token, app
|
|
539
|
+
const verified = await this.verifier.verify(minted.token, audienceOf(app))
|
|
530
540
|
if (!verified.ok) {
|
|
531
541
|
// We just minted it, so this is a config/clock/key problem, not a bad session — and if the
|
|
532
542
|
// key set is unreachable it is an incident, not a reason to bounce the browser to login.
|
|
@@ -583,21 +593,58 @@ export class Authorizer {
|
|
|
583
593
|
}
|
|
584
594
|
const cookieName = handoffCookieName(state)
|
|
585
595
|
const verifier = cookieName === null ? null : readCookie(request.headers.get('Cookie'), cookieName)
|
|
596
|
+
// Through `callIam` like every other IAM call, so an unreachable service is a 503 whatever kind
|
|
597
|
+
// of error the injected gateway happened to throw. `authorize`'s outer catch maps the rest.
|
|
598
|
+
const redeem = (presented: string) =>
|
|
599
|
+
this.callIam(
|
|
600
|
+
'exchangeAuthCode',
|
|
601
|
+
() => this.options.iam.exchangeAuthCode({ app: audienceOf(resolved.app), code, verifier: presented, requestId: request.requestId }),
|
|
602
|
+
)
|
|
586
603
|
if (verifier === null) {
|
|
604
|
+
// This browser did not start the sign-in the code belongs to. The code is spent, so whoever started it cannot
|
|
605
|
+
// redeem it from the address this browser shows (ADR-0067 §3).
|
|
606
|
+
await redeem(unmatchedVerifier())
|
|
587
607
|
return { outcome: 'deny', status: 403, reason: 'invalid_session', clearHandoffState: state }
|
|
588
608
|
}
|
|
589
|
-
|
|
590
|
-
//
|
|
591
|
-
|
|
592
|
-
'exchangeAuthCode',
|
|
593
|
-
() => this.options.iam.exchangeAuthCode({ app: resolved.app.id, code, verifier, requestId: request.requestId }),
|
|
594
|
-
)
|
|
595
|
-
if (!result.ok) {
|
|
609
|
+
const result = await redeem(verifier)
|
|
610
|
+
// IAM binds a code to its audience only, which several dev sandbox entries share: the return must be this host.
|
|
611
|
+
if (!result.ok || !returnsToHost(resolved.app, request.url, result.returnUrl)) {
|
|
596
612
|
return { outcome: 'deny', status: 403, reason: 'invalid_session', clearHandoffState: state }
|
|
597
613
|
}
|
|
598
614
|
return { outcome: 'handoff', status: 302, location: result.returnUrl, session: result.session, expiresAt: result.expiresAt, handoffState: state }
|
|
599
615
|
}
|
|
600
616
|
|
|
617
|
+
/**
|
|
618
|
+
* Sign the browser out of this host (ADR-0067 §5). Called for the reserved sign-out path only, BEFORE the endpoint
|
|
619
|
+
* is planned, for any entry and any session. It drops this session's cached token, so the next request re-mints
|
|
620
|
+
* from IAM, which has revoked the session by then or still holds it; the cookie itself is cleared by the response.
|
|
621
|
+
*
|
|
622
|
+
* Admission is `Sec-Fetch-Site: same-origin`, absent included: the request changes state, and another page must not
|
|
623
|
+
* sign a person out, as for a session request that is not a `GET` (ADR-0022 rule 3, step 6).
|
|
624
|
+
*/
|
|
625
|
+
signOut(resolved: ResolvedApp, request: ForwardedRequest): Decision {
|
|
626
|
+
if (request.method !== 'GET') {
|
|
627
|
+
return { outcome: 'deny', status: 403, reason: 'no_endpoint' }
|
|
628
|
+
}
|
|
629
|
+
if (request.headers.get(FETCH_SITE_HEADER) !== 'same-origin') {
|
|
630
|
+
return { outcome: 'deny', status: 403, reason: 'cross_site' }
|
|
631
|
+
}
|
|
632
|
+
const app = resolved.app
|
|
633
|
+
const returnTo = request.url.searchParams.get(LOGIN_REDIRECT_PARAM)
|
|
634
|
+
const target = returnTo === null ? null : sameOriginTarget(new URL(`${app.scheme}://${request.url.host}`).origin, returnTo)
|
|
635
|
+
if (target === null) {
|
|
636
|
+
return { outcome: 'deny', status: 400, reason: 'bad_redirect' }
|
|
637
|
+
}
|
|
638
|
+
const session = readCookie(request.headers.get('Cookie'), SESSION_COOKIE)
|
|
639
|
+
if (session !== null) {
|
|
640
|
+
this.cache?.delete(cacheKey(app.id, 'session', session))
|
|
641
|
+
}
|
|
642
|
+
const release = new URL(SIGNOUT_RELEASE_PATH, this.options.issuer.replace(/\/+$/, ''))
|
|
643
|
+
release.searchParams.set('app', audienceOf(app))
|
|
644
|
+
release.searchParams.set(LOGIN_REDIRECT_PARAM, target)
|
|
645
|
+
return { outcome: 'signout', status: 302, location: release.toString() }
|
|
646
|
+
}
|
|
647
|
+
|
|
601
648
|
private async loginDecision(
|
|
602
649
|
app: ProxyApp,
|
|
603
650
|
request: ForwardedRequest,
|
|
@@ -607,7 +654,7 @@ export class Authorizer {
|
|
|
607
654
|
return {
|
|
608
655
|
outcome: 'login',
|
|
609
656
|
status: isDocumentNavigation(request.headers) ? 302 : 401,
|
|
610
|
-
location: this.loginUrl(app, request.url, handoff),
|
|
657
|
+
location: this.loginUrl(app, request.url, signInLocale(request.headers), handoff),
|
|
611
658
|
reason,
|
|
612
659
|
handoff,
|
|
613
660
|
}
|
|
@@ -619,16 +666,23 @@ export class Authorizer {
|
|
|
619
666
|
* The scheme comes from the MANIFEST, not from the forwarded request: behind a TLS-terminating
|
|
620
667
|
* balancer the proxy is reached over plain HTTP and `X-Forwarded-Proto` says so, which would send
|
|
621
668
|
* the browser back to an `http://` URL for an origin only served over `https://`.
|
|
669
|
+
*
|
|
670
|
+
* `locale` is the language the application left for this browser on its host (`signInLocale`), passed on as IAM's
|
|
671
|
+
* `?locale=` so the first sign-in page speaks it. It picks IAM's words only: the decision, the return URL and the
|
|
672
|
+
* handoff are the same without it.
|
|
622
673
|
*/
|
|
623
|
-
private loginUrl(app: ProxyApp, url: URL, handoff: HandoffAttempt): string {
|
|
674
|
+
private loginUrl(app: ProxyApp, url: URL, locale: Locale | null, handoff: HandoffAttempt): string {
|
|
624
675
|
const target = new URL(url)
|
|
625
676
|
target.protocol = `${app.scheme}:`
|
|
626
677
|
// `readProxyEnv` already reduces the issuer to an origin; this covers a composition root that
|
|
627
678
|
// does not go through it (the Cloudflare Worker reads its env directly).
|
|
628
679
|
const issuer = this.options.issuer.replace(/\/+$/, '')
|
|
629
680
|
const login = new URL('/auth/login', issuer)
|
|
630
|
-
login.searchParams.set('app', app
|
|
681
|
+
login.searchParams.set('app', audienceOf(app))
|
|
631
682
|
login.searchParams.set(LOGIN_REDIRECT_PARAM, target.toString())
|
|
683
|
+
if (locale !== null) {
|
|
684
|
+
login.searchParams.set(LOCALE_PARAM, locale)
|
|
685
|
+
}
|
|
632
686
|
setHandoffParams(login, handoff)
|
|
633
687
|
return login.toString()
|
|
634
688
|
}
|
|
@@ -647,6 +701,21 @@ function admittedOrigin(app: ProxyApp, row: ManifestEndpointRow, origin: string)
|
|
|
647
701
|
return form === 'environment' && isApplicationEntry(app) && (app.crossOrigins ?? []).includes(origin) ? origin : null
|
|
648
702
|
}
|
|
649
703
|
|
|
704
|
+
/**
|
|
705
|
+
* The language an application left for this browser in `LOCALE_COOKIE` on its own host, or null for none or for a
|
|
706
|
+
* value IAM does not speak. A client can set it, which is why it only ever picks words on IAM's sign-in page.
|
|
707
|
+
*/
|
|
708
|
+
function signInLocale(headers: Headers): Locale | null {
|
|
709
|
+
const value = readCookie(headers.get('Cookie'), LOCALE_COOKIE)
|
|
710
|
+
return isLocale(value) ? value : null
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** Whether a redeemed code's return URL is on the host the callback arrived at, and that host is one of the entry's. */
|
|
714
|
+
function returnsToHost(app: ProxyApp, callback: URL, returnUrl: string): boolean {
|
|
715
|
+
const target = URL.canParse(returnUrl) ? new URL(returnUrl) : null
|
|
716
|
+
return target !== null && target.hostname === callback.hostname && app.hosts.includes(target.hostname)
|
|
717
|
+
}
|
|
718
|
+
|
|
650
719
|
function invalidKey(): Denial {
|
|
651
720
|
return { outcome: 'deny', status: 401, reason: 'invalid_key' }
|
|
652
721
|
}
|
|
@@ -738,10 +807,13 @@ function isDocumentNavigation(headers: Headers): boolean {
|
|
|
738
807
|
}
|
|
739
808
|
|
|
740
809
|
/**
|
|
741
|
-
* The `Authorization` of an anonymous request
|
|
742
|
-
*
|
|
810
|
+
* The `Authorization` of an anonymous request goes on only on a `protocol` row, whose receiver authenticates the caller
|
|
811
|
+
* itself (ADR-0069: the ops key reaches framework code only), and on a webhook row that forwards it, never with a
|
|
812
|
+
* platform key. The proxy reads no credential from it either way: no key lookup, no session.
|
|
743
813
|
*/
|
|
744
814
|
function forwardsAuthorization(row: ManifestEndpointRow, request: ForwardedRequest): boolean {
|
|
745
815
|
const authorization = request.headers.get('Authorization')
|
|
746
|
-
|
|
816
|
+
if (authorization === null) return false
|
|
817
|
+
if (row.kind === 'protocol') return true
|
|
818
|
+
return 'authorization' in row && row.authorization === 'forward' && !carriesPlatformKey(authorization, API_KEY_PREFIX)
|
|
747
819
|
}
|
package/src/brand.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client's brand on fabrika's own pages (ADR-0066). An installation serves one client, so its logo is one setting
|
|
3
|
+
* of the installation: IAM keeps it, the console's Settings writes it, and the proxy manifest carries it to the pages the
|
|
4
|
+
* proxy answers with on every application host. A page shows it where it would otherwise draw the fabrika mark.
|
|
5
|
+
*
|
|
6
|
+
* A logo is an image a page embeds as a `data:` URI in an `<img>`, never markup: an SVG in an image runs no script, and
|
|
7
|
+
* a page that carries it loads nothing. Every consumer checks it here, the IAM write, the manifest parser and the
|
|
8
|
+
* console's own pre-check, so a logo that one of them admits passes the others. This module imports zod and nothing
|
|
9
|
+
* else, so the browser can use it.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { z } from 'zod'
|
|
13
|
+
|
|
14
|
+
export const BRAND_IMAGE_TYPES = ['image/png', 'image/webp', 'image/svg+xml'] as const
|
|
15
|
+
|
|
16
|
+
export type BrandImageType = (typeof BRAND_IMAGE_TYPES)[number]
|
|
17
|
+
|
|
18
|
+
/** The most one image may weigh, decoded. A page carries it in every copy Caddy serves, so it stays a logo's size. */
|
|
19
|
+
export const MAX_BRAND_IMAGE_BYTES = 32 * 1024
|
|
20
|
+
|
|
21
|
+
/** One image of the brand: its type and its bytes as canonical base64. */
|
|
22
|
+
export interface BrandImage {
|
|
23
|
+
readonly type: BrandImageType
|
|
24
|
+
readonly base64: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The logo for a light page, and the one for a dark page when the light one would not read there. */
|
|
28
|
+
export interface InstallationBrand {
|
|
29
|
+
readonly light: BrandImage
|
|
30
|
+
readonly dark?: BrandImage
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type BrandImageProblem = 'type' | 'encoding' | 'size' | 'content'
|
|
34
|
+
|
|
35
|
+
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
|
|
36
|
+
const MAX_BASE64_LENGTH = Math.ceil(MAX_BRAND_IMAGE_BYTES / 3) * 4
|
|
37
|
+
|
|
38
|
+
/** Why an image cannot be the brand, or null. The type must be one of three and must be what the bytes are. */
|
|
39
|
+
export function brandImageProblem(image: { readonly type: string; readonly base64: string }): BrandImageProblem | null {
|
|
40
|
+
if (!isBrandImageType(image.type)) return 'type'
|
|
41
|
+
if (image.base64.length === 0 || !BASE64.test(image.base64)) return 'encoding'
|
|
42
|
+
if (image.base64.length > MAX_BASE64_LENGTH) return 'size'
|
|
43
|
+
const bytes = decode(image.base64)
|
|
44
|
+
// Base64 with stray bits in its last character decodes to the same bytes; only the canonical spelling is one image.
|
|
45
|
+
if (bytes === null || brandImageBase64(bytes) !== image.base64) return 'encoding'
|
|
46
|
+
if (bytes.length > MAX_BRAND_IMAGE_BYTES) return 'size'
|
|
47
|
+
return sniff(bytes) === image.type ? null : 'content'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isBrandImageType(value: string): value is BrandImageType {
|
|
51
|
+
return BRAND_IMAGE_TYPES.some((type) => type === value)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const brandImageSchema = z.object({
|
|
55
|
+
type: z.enum(BRAND_IMAGE_TYPES),
|
|
56
|
+
base64: z.string(),
|
|
57
|
+
}).strict().superRefine((image, ctx) => {
|
|
58
|
+
const problem = brandImageProblem(image)
|
|
59
|
+
if (problem !== null) ctx.addIssue({ code: 'custom', message: `not a brand image: ${problem}` })
|
|
60
|
+
}) satisfies z.ZodType<BrandImage, z.ZodTypeDef, unknown>
|
|
61
|
+
|
|
62
|
+
export const installationBrandSchema = z.object({
|
|
63
|
+
light: brandImageSchema,
|
|
64
|
+
dark: brandImageSchema.optional(),
|
|
65
|
+
}).strict() satisfies z.ZodType<InstallationBrand, z.ZodTypeDef, unknown>
|
|
66
|
+
|
|
67
|
+
/** The image as the `src` of an `<img>`. Base64 holds no `{`, so a Caddy `static_response` body keeps it as it is. */
|
|
68
|
+
export function brandImageDataUri(image: BrandImage): string {
|
|
69
|
+
return `data:${image.type};base64,${image.base64}`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What the bytes are, read from their start, never from what the uploader called them. */
|
|
73
|
+
function sniff(bytes: Uint8Array): BrandImageType | null {
|
|
74
|
+
if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'
|
|
75
|
+
if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50])) return 'image/webp'
|
|
76
|
+
return isSvg(bytes) ? 'image/svg+xml' : null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* UTF-8 text whose first element is `<svg`, after an optional byte order mark, an XML declaration, comments and a
|
|
81
|
+
* doctype. An image of type SVG renders inert in an `<img>`, so this only has to stop another kind of file posing as one.
|
|
82
|
+
*/
|
|
83
|
+
function isSvg(bytes: Uint8Array): boolean {
|
|
84
|
+
let text: string
|
|
85
|
+
try {
|
|
86
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
|
|
87
|
+
} catch {
|
|
88
|
+
return false
|
|
89
|
+
}
|
|
90
|
+
let rest = text.replace(/^/, '')
|
|
91
|
+
for (;;) {
|
|
92
|
+
const trimmed = rest.replace(/^\s+/, '')
|
|
93
|
+
const prologue = /^(?:<\?xml[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE\s+svg[^>]*>)/i.exec(trimmed)
|
|
94
|
+
if (prologue === null) return /^<svg[\s>]/.test(trimmed)
|
|
95
|
+
rest = trimmed.slice(prologue[0].length)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function startsWith(bytes: Uint8Array, prefix: readonly number[]): boolean {
|
|
100
|
+
return bytes.length >= prefix.length && prefix.every((byte, index) => bytes[index] === byte)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function decode(base64: string): Uint8Array | null {
|
|
104
|
+
try {
|
|
105
|
+
const binary = atob(base64)
|
|
106
|
+
const bytes = new Uint8Array(binary.length)
|
|
107
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)
|
|
108
|
+
return bytes
|
|
109
|
+
} catch {
|
|
110
|
+
return null
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Canonical base64 of `bytes`, the spelling the check requires. Chunked, so a large file stays within `fromCharCode`'s arguments. */
|
|
115
|
+
export function brandImageBase64(bytes: Uint8Array): string {
|
|
116
|
+
let binary = ''
|
|
117
|
+
for (let start = 0; start < bytes.length; start += 0x8000) {
|
|
118
|
+
binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000))
|
|
119
|
+
}
|
|
120
|
+
return btoa(binary)
|
|
121
|
+
}
|
package/src/cache.ts
CHANGED
|
Binary file
|
package/src/constants.ts
CHANGED
|
@@ -49,6 +49,15 @@ export const APP_QUERY_PARAM = 'app'
|
|
|
49
49
|
*/
|
|
50
50
|
export const LOGIN_REDIRECT_PARAM = 'redirect'
|
|
51
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Reserved on every app host beside the handoff callback, and answered before endpoint selection: it clears the app
|
|
54
|
+
* session and sends the browser to IAM's release (ADR-0067 §5). It takes the return path in `LOGIN_REDIRECT_PARAM`.
|
|
55
|
+
*/
|
|
56
|
+
export const AUTH_SIGNOUT_PATH = '/__fabrika/auth/signout'
|
|
57
|
+
|
|
58
|
+
/** IAM's path that revokes the browser's terminal sessions and returns it to the application (ADR-0067 §5). */
|
|
59
|
+
export const SIGNOUT_RELEASE_PATH = '/auth/terminals/release'
|
|
60
|
+
|
|
52
61
|
/** The JWKS cache TTL and the unknown-`kid` refetch cooldown, owned by the verifier both planes share. */
|
|
53
62
|
export { JWKS_REFETCH_COOLDOWN_SECONDS, JWKS_TTL_SECONDS } from '@fabrika/jwks'
|
|
54
63
|
|
package/src/handoff.ts
CHANGED
|
@@ -15,6 +15,14 @@ export async function createHandoffAttempt(): Promise<HandoffAttempt> {
|
|
|
15
15
|
return { state, verifier, challenge: await handoffChallenge(verifier) }
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* A verifier made for no challenge. IAM consumes a code before it compares the verifier, so redeeming a code with this
|
|
20
|
+
* one only spends the code.
|
|
21
|
+
*/
|
|
22
|
+
export function unmatchedVerifier(): string {
|
|
23
|
+
return randomToken(32)
|
|
24
|
+
}
|
|
25
|
+
|
|
18
26
|
/** S256, matching PKCE: the verifier never rides in a URL or reaches IAM through the browser. */
|
|
19
27
|
export async function handoffChallenge(verifier: string): Promise<string> {
|
|
20
28
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
|
package/src/headers.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// "Response headers"). The proxy sets them on every answer, its own denials included; the framework sets the same
|
|
3
3
|
// definition in-process. Exported as `@fabrika/proxy-core/headers`, which imports nothing at runtime.
|
|
4
4
|
|
|
5
|
-
import type { CspExtensions, EndpointCache } from '@fabrika/auth-core'
|
|
5
|
+
import type { CspExtensions, EndpointCache, EndpointResponse } from '@fabrika/auth-core'
|
|
6
6
|
|
|
7
7
|
/** Every powerful feature off. ADR-0022 lists the same names; change both together. */
|
|
8
8
|
export const PERMISSIONS_POLICY_FEATURES: readonly string[] = [
|
|
@@ -169,6 +169,23 @@ export const BASE_HEADER_POLICY: HeaderPolicy = headerPolicy(NO_CSP_ORIGINS, nul
|
|
|
169
169
|
/** Raster formats a browser only ever renders as an image; every other download, SVG and HTML included, is an attachment. */
|
|
170
170
|
export const INLINE_FILE_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* XML a machine reads (a feed, a sitemap, an import file), shown inline only on a row of an `inline: true` kind
|
|
174
|
+
* (`response: 'inline-file'`). `FILE_TREATMENT`'s sandbox runs none of its script and loads nothing; XHTML and SVG
|
|
175
|
+
* are not among them.
|
|
176
|
+
*/
|
|
177
|
+
export const INLINE_DOCUMENT_TYPES: readonly string[] = ['application/xml', 'text/xml', 'application/rss+xml', 'application/atom+xml']
|
|
178
|
+
|
|
179
|
+
const INLINE_FILE_AND_DOCUMENT_TYPES: readonly string[] = Object.freeze([...INLINE_FILE_TYPES, ...INLINE_DOCUMENT_TYPES])
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The types a row's answer is shown inline as: the inert images, and the XML documents only on an `inline-file` row.
|
|
183
|
+
* One constant per profile, so a composition can group its rows by it.
|
|
184
|
+
*/
|
|
185
|
+
export function inlineFileTypes(response: EndpointResponse | undefined): readonly string[] {
|
|
186
|
+
return response === 'inline-file' ? INLINE_FILE_AND_DOCUMENT_TYPES : INLINE_FILE_TYPES
|
|
187
|
+
}
|
|
188
|
+
|
|
172
189
|
/** What every answer of a download endpoint carries in place of the policy, its errors included. */
|
|
173
190
|
export const FILE_TREATMENT: HeaderPolicy = Object.freeze([
|
|
174
191
|
['X-Content-Type-Options', 'nosniff'],
|
|
@@ -244,8 +261,8 @@ export function applyCrossOriginHeaders(headers: Headers, policy: HeaderPolicy):
|
|
|
244
261
|
}
|
|
245
262
|
|
|
246
263
|
/** `null` and anything but one allowlisted value is an attachment; `Headers` joins repeated fields with `, `, so two never match. */
|
|
247
|
-
export function fileDisposition(contentType: string | null): 'inline' | 'attachment' {
|
|
248
|
-
return contentType !== null &&
|
|
264
|
+
export function fileDisposition(contentType: string | null, inline: readonly string[] = INLINE_FILE_TYPES): 'inline' | 'attachment' {
|
|
265
|
+
return contentType !== null && inline.includes(contentType) ? 'inline' : 'attachment'
|
|
249
266
|
}
|
|
250
267
|
|
|
251
268
|
/** Whatever the handler or an asset server set for these names is replaced; the removed and transport headers are dropped first. */
|
|
@@ -260,12 +277,13 @@ export function applyHeaderPolicy(headers: Headers, policy: HeaderPolicy): void
|
|
|
260
277
|
|
|
261
278
|
/**
|
|
262
279
|
* The file treatment over headers a download already carries: the disposition type follows the `Content-Type`
|
|
263
|
-
* exactly, and the parameters after it (the file name) are kept. The proxy passes `appFileTreatment` of its entry
|
|
280
|
+
* exactly, and the parameters after it (the file name) are kept. The proxy passes `appFileTreatment` of its entry, and
|
|
281
|
+
* `inlineFileTypes` of the row.
|
|
264
282
|
*/
|
|
265
|
-
export function applyFileTreatment(headers: Headers, treatment: HeaderPolicy = FILE_TREATMENT): void {
|
|
283
|
+
export function applyFileTreatment(headers: Headers, treatment: HeaderPolicy = FILE_TREATMENT, inline: readonly string[] = INLINE_FILE_TYPES): void {
|
|
266
284
|
applyHeaderPolicy(headers, treatment)
|
|
267
285
|
const parameters = headers.get('Content-Disposition')?.replace(/^[^;]*/, '') ?? ''
|
|
268
|
-
headers.set('Content-Disposition', `${fileDisposition(headers.get('Content-Type'))}${parameters}`)
|
|
286
|
+
headers.set('Content-Disposition', `${fileDisposition(headers.get('Content-Type'), inline)}${parameters}`)
|
|
269
287
|
}
|
|
270
288
|
|
|
271
289
|
/**
|
package/src/iam.ts
CHANGED
|
@@ -130,7 +130,7 @@ export class HttpIamGateway implements IamGateway, DelegationIssuer {
|
|
|
130
130
|
this.origin = options.origin.replace(/\/+$/, '')
|
|
131
131
|
this.timeoutMs = options.timeoutMs ?? DEFAULT_IAM_TIMEOUT_MS
|
|
132
132
|
this.key = options.key
|
|
133
|
-
this.fetchImpl = options.fetch ?? globalThis.fetch
|
|
133
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis)
|
|
134
134
|
}
|
|
135
135
|
|
|
136
136
|
async mintToken(input: MintTokenInput): Promise<MintTokenResult> {
|
|
@@ -214,6 +214,8 @@ export class HttpIamGateway implements IamGateway, DelegationIssuer {
|
|
|
214
214
|
headers,
|
|
215
215
|
body,
|
|
216
216
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
217
|
+
// The proxy key and the credential in the body must never reach a redirect target; a 3xx is not ok below.
|
|
218
|
+
redirect: 'manual',
|
|
217
219
|
})
|
|
218
220
|
} catch {
|
|
219
221
|
// Deliberately swallow the cause: a fetch error stringifies the request URL and, on some
|
package/src/index.ts
CHANGED
|
@@ -16,6 +16,7 @@ export { cacheKey, MemoryTokenCache } from './cache'
|
|
|
16
16
|
export type { CachedToken, TokenCache } from './cache'
|
|
17
17
|
export {
|
|
18
18
|
APP_QUERY_PARAM,
|
|
19
|
+
AUTH_SIGNOUT_PATH,
|
|
19
20
|
CLIENT_ADDRESS_HEADER,
|
|
20
21
|
DEFAULT_HEALTH_PATH,
|
|
21
22
|
DEFAULT_IAM_TIMEOUT_MS,
|
|
@@ -32,6 +33,7 @@ export {
|
|
|
32
33
|
PREFLIGHT_HEADER,
|
|
33
34
|
PROXY_TOKEN_HEADER,
|
|
34
35
|
REQUEST_ID_HEADER,
|
|
36
|
+
SIGNOUT_RELEASE_PATH,
|
|
35
37
|
UNTRUSTED_FORWARD_HEADERS,
|
|
36
38
|
} from './constants'
|
|
37
39
|
export { carriesPlatformKey, readBearer, readCookie } from './credentials'
|
|
@@ -41,6 +43,8 @@ export type { DelegationIssuer, DelegationRequest, HttpIamGatewayOptions, IamGat
|
|
|
41
43
|
export { consoleLogger, redactPath, redactUrl, silentLogger } from './log'
|
|
42
44
|
export type { LogFields, LogValue, ProxyLogger } from './log'
|
|
43
45
|
export { findOAuthMetadata, OAUTH_METADATA_VERIFY_PATH, oauthMetadataResponse } from './oauth'
|
|
46
|
+
export { errorAnswer, errorPage, FETCH_MODE_HEADER, isPageNavigation, PAGE_CONTENT_TYPE, pageResponse, renderPage } from './pages'
|
|
47
|
+
export type { ErrorPageStatus, PageAction, PageContent } from './pages'
|
|
44
48
|
export { createVerifyService } from './service'
|
|
45
49
|
export type { VerifyService, VerifyServiceConfig } from './service'
|
|
46
50
|
export { TokenVerifier } from './verifier'
|