@fabrika/proxy-core 0.9.0-dev.2 → 0.9.0-dev.20
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 +83 -31
- 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 +1 -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 +23 -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.20",
|
|
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.20",
|
|
52
|
+
"@fabrika/jwks": "0.9.0-dev.20",
|
|
43
53
|
"jose": "^5.9.0",
|
|
44
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
54
|
+
"@fabrika/platform": "0.9.0-dev.20"
|
|
45
55
|
}
|
|
46
56
|
}
|
package/src/authorize.ts
CHANGED
|
@@ -30,17 +30,19 @@ import {
|
|
|
30
30
|
FORM_URLENCODED_TYPE,
|
|
31
31
|
formatEndpointHeader,
|
|
32
32
|
planEndpoint,
|
|
33
|
+
sameOriginTarget,
|
|
33
34
|
satisfies,
|
|
34
35
|
SESSION_COOKIE,
|
|
35
36
|
TOKEN_REFRESH_SKEW_SECONDS,
|
|
36
37
|
type TokenCaller,
|
|
37
38
|
} from '@fabrika/auth-core'
|
|
38
39
|
import { cacheKey, type TokenCache } from './cache'
|
|
39
|
-
import { LOGIN_REDIRECT_PARAM } from './constants'
|
|
40
|
+
import { LOGIN_REDIRECT_PARAM, SIGNOUT_RELEASE_PATH } from './constants'
|
|
40
41
|
import { carriesPlatformKey, readBearer, readCookie } from './credentials'
|
|
41
|
-
import { createHandoffAttempt, type HandoffAttempt, handoffCookieName, setHandoffParams } from './handoff'
|
|
42
|
+
import { createHandoffAttempt, type HandoffAttempt, handoffCookieName, setHandoffParams, unmatchedVerifier } from './handoff'
|
|
42
43
|
import { type DelegationIssuer, type IamGateway, IamUnavailableError } from './iam'
|
|
43
44
|
import {
|
|
45
|
+
audienceOf,
|
|
44
46
|
isApplicationEntry,
|
|
45
47
|
type ManifestEndpointRow,
|
|
46
48
|
type OAuthBearerChallenge,
|
|
@@ -48,6 +50,7 @@ import {
|
|
|
48
50
|
oauthResourceOfRow,
|
|
49
51
|
type ProxyApp,
|
|
50
52
|
} from './manifest'
|
|
53
|
+
import { FETCH_MODE_HEADER } from './pages'
|
|
51
54
|
import { TokenVerifier } from './verifier'
|
|
52
55
|
|
|
53
56
|
/** Every way a request can be refused. Coarse on purpose — these are logged, not returned to clients. */
|
|
@@ -75,8 +78,10 @@ export type DenyReason =
|
|
|
75
78
|
| 'caller_kind'
|
|
76
79
|
/** The token does not satisfy the endpoint's requirement. */
|
|
77
80
|
| 'insufficient_permission'
|
|
78
|
-
/** A session request that is not a `GET
|
|
81
|
+
/** A session request that is not a `GET`, or a sign-out, did not come from the app's own origin. */
|
|
79
82
|
| 'cross_site'
|
|
83
|
+
/** A sign-out's return is absent or not a path on the app's own origin. */
|
|
84
|
+
| 'bad_redirect'
|
|
80
85
|
/** The request's `Content-Type` is not one the endpoint admits. */
|
|
81
86
|
| 'content_type'
|
|
82
87
|
/**
|
|
@@ -111,8 +116,8 @@ export type Decision =
|
|
|
111
116
|
/** The `Access-Control-Allow-Origin` the answer carries: the request's admitted origin, `*`, or none. */
|
|
112
117
|
crossOrigin: string | null
|
|
113
118
|
/**
|
|
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).
|
|
119
|
+
* Whether the request's own `Authorization` reaches the application: on the ops row, and on a webhook row that
|
|
120
|
+
* forwards it unless it carries a platform key. Every other anonymous request loses it (ADR-0022 rule 3).
|
|
116
121
|
*/
|
|
117
122
|
forwardsAuthorization: boolean
|
|
118
123
|
}
|
|
@@ -143,6 +148,11 @@ export type Decision =
|
|
|
143
148
|
* was going — read from the code server-side, never from the request.
|
|
144
149
|
*/
|
|
145
150
|
| { outcome: 'handoff'; status: 302; location: string; session: string; expiresAt: number; handoffState: string }
|
|
151
|
+
/**
|
|
152
|
+
* A same-origin sign-out (ADR-0067 §5): the app session cookie is cleared and the browser goes to IAM's release,
|
|
153
|
+
* which returns it to `location`'s own redirect on this app's origin.
|
|
154
|
+
*/
|
|
155
|
+
| { outcome: 'signout'; status: 302; location: string }
|
|
146
156
|
|
|
147
157
|
/** The original request, reconstructed from what `forward_auth` forwarded. */
|
|
148
158
|
export interface ForwardedRequest {
|
|
@@ -178,13 +188,6 @@ export interface AuthorizerOptions {
|
|
|
178
188
|
delegations?: DelegationIssuer | null
|
|
179
189
|
}
|
|
180
190
|
|
|
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
191
|
/** Fetch metadata the browser writes and page script cannot: `same-origin` only for a request from this origin. */
|
|
189
192
|
const FETCH_SITE_HEADER = 'Sec-Fetch-Site'
|
|
190
193
|
|
|
@@ -415,7 +418,10 @@ export class Authorizer {
|
|
|
415
418
|
if (issuer === undefined || issuer === null) {
|
|
416
419
|
return { ok: true, grant: null }
|
|
417
420
|
}
|
|
418
|
-
const result = await this.callIam(
|
|
421
|
+
const result = await this.callIam(
|
|
422
|
+
'requestDelegation',
|
|
423
|
+
() => issuer.requestDelegation({ app: audienceOf(app), credential: token, requestId, endpoint }),
|
|
424
|
+
)
|
|
419
425
|
return result.ok && result.grant !== ''
|
|
420
426
|
? { ok: true, grant: result.grant }
|
|
421
427
|
: { ok: false, denial: { outcome: 'deny', status: 403, reason: 'delegation_refused' } }
|
|
@@ -431,7 +437,7 @@ export class Authorizer {
|
|
|
431
437
|
if (bearer === null) {
|
|
432
438
|
return { ok: false, denial: { outcome: 'deny', status: 401, reason: 'no_credential', challenge } }
|
|
433
439
|
}
|
|
434
|
-
const verified = await this.verifier.verify(bearer, { kind: 'resource', app: app
|
|
440
|
+
const verified = await this.verifier.verify(bearer, { kind: 'resource', app: audienceOf(app), resource: binding.resource.resource })
|
|
435
441
|
if (!verified.ok) {
|
|
436
442
|
return verified.reason === 'unavailable'
|
|
437
443
|
? { ok: false, denial: { outcome: 'deny', status: 503, reason: 'iam_unavailable' } }
|
|
@@ -457,7 +463,7 @@ export class Authorizer {
|
|
|
457
463
|
const key = cacheKey(app.id, 'key', bearer)
|
|
458
464
|
const cached = this.cache?.get(key)
|
|
459
465
|
if (cached !== undefined && cached.expiresAt - this.now() > TOKEN_REFRESH_SKEW_SECONDS) {
|
|
460
|
-
const verified = await this.verifier.verify(cached.token, app
|
|
466
|
+
const verified = await this.verifier.verify(cached.token, audienceOf(app))
|
|
461
467
|
if (verified.ok) {
|
|
462
468
|
return { ok: true, token: cached.token, claims: verified.claims }
|
|
463
469
|
}
|
|
@@ -471,11 +477,11 @@ export class Authorizer {
|
|
|
471
477
|
this.cache?.delete(key)
|
|
472
478
|
}
|
|
473
479
|
|
|
474
|
-
const minted = await this.callIam('mintFromKey', () => this.options.iam.mintFromKey({ app: app
|
|
480
|
+
const minted = await this.callIam('mintFromKey', () => this.options.iam.mintFromKey({ app: audienceOf(app), key: bearer, requestId }))
|
|
475
481
|
if (!minted.ok) {
|
|
476
482
|
return { ok: false, denial: { outcome: 'deny', status: minted.reason === 'invalid_key' ? 401 : 403, reason: minted.reason } }
|
|
477
483
|
}
|
|
478
|
-
const verified = await this.verifier.verify(minted.token, app
|
|
484
|
+
const verified = await this.verifier.verify(minted.token, audienceOf(app))
|
|
479
485
|
if (!verified.ok) {
|
|
480
486
|
// We just minted it, so a verification miss is a config/clock/key problem — not a client
|
|
481
487
|
// error. Either way: deny.
|
|
@@ -508,7 +514,7 @@ export class Authorizer {
|
|
|
508
514
|
const key = cacheKey(app.id, 'session', session)
|
|
509
515
|
const cached = this.cache?.get(key)
|
|
510
516
|
if (cached !== undefined && cached.expiresAt - now > TOKEN_REFRESH_SKEW_SECONDS) {
|
|
511
|
-
const verified = await this.verifier.verify(cached.token, app
|
|
517
|
+
const verified = await this.verifier.verify(cached.token, audienceOf(app))
|
|
512
518
|
if (verified.ok && verified.claims.ptype === 'user') {
|
|
513
519
|
return { ok: true, token: cached.token, claims: verified.claims }
|
|
514
520
|
}
|
|
@@ -520,13 +526,13 @@ export class Authorizer {
|
|
|
520
526
|
this.cache?.delete(key)
|
|
521
527
|
}
|
|
522
528
|
|
|
523
|
-
const minted = await this.callIam('mintToken', () => this.options.iam.mintToken({ app: app
|
|
529
|
+
const minted = await this.callIam('mintToken', () => this.options.iam.mintToken({ app: audienceOf(app), session, requestId: request.requestId }))
|
|
524
530
|
if (!minted.ok) {
|
|
525
531
|
return minted.reason === 'token_too_large'
|
|
526
532
|
? { ok: false, status: 'refused', reason: minted.reason }
|
|
527
533
|
: { ok: false, status: 'miss', reason: minted.reason }
|
|
528
534
|
}
|
|
529
|
-
const verified = await this.verifier.verify(minted.token, app
|
|
535
|
+
const verified = await this.verifier.verify(minted.token, audienceOf(app))
|
|
530
536
|
if (!verified.ok) {
|
|
531
537
|
// We just minted it, so this is a config/clock/key problem, not a bad session — and if the
|
|
532
538
|
// key set is unreachable it is an incident, not a reason to bounce the browser to login.
|
|
@@ -583,21 +589,58 @@ export class Authorizer {
|
|
|
583
589
|
}
|
|
584
590
|
const cookieName = handoffCookieName(state)
|
|
585
591
|
const verifier = cookieName === null ? null : readCookie(request.headers.get('Cookie'), cookieName)
|
|
592
|
+
// Through `callIam` like every other IAM call, so an unreachable service is a 503 whatever kind
|
|
593
|
+
// of error the injected gateway happened to throw. `authorize`'s outer catch maps the rest.
|
|
594
|
+
const redeem = (presented: string) =>
|
|
595
|
+
this.callIam(
|
|
596
|
+
'exchangeAuthCode',
|
|
597
|
+
() => this.options.iam.exchangeAuthCode({ app: audienceOf(resolved.app), code, verifier: presented, requestId: request.requestId }),
|
|
598
|
+
)
|
|
586
599
|
if (verifier === null) {
|
|
600
|
+
// This browser did not start the sign-in the code belongs to. The code is spent, so whoever started it cannot
|
|
601
|
+
// redeem it from the address this browser shows (ADR-0067 §3).
|
|
602
|
+
await redeem(unmatchedVerifier())
|
|
587
603
|
return { outcome: 'deny', status: 403, reason: 'invalid_session', clearHandoffState: state }
|
|
588
604
|
}
|
|
589
|
-
|
|
590
|
-
//
|
|
591
|
-
|
|
592
|
-
'exchangeAuthCode',
|
|
593
|
-
() => this.options.iam.exchangeAuthCode({ app: resolved.app.id, code, verifier, requestId: request.requestId }),
|
|
594
|
-
)
|
|
595
|
-
if (!result.ok) {
|
|
605
|
+
const result = await redeem(verifier)
|
|
606
|
+
// IAM binds a code to its audience only, which several dev sandbox entries share: the return must be this host.
|
|
607
|
+
if (!result.ok || !returnsToHost(resolved.app, request.url, result.returnUrl)) {
|
|
596
608
|
return { outcome: 'deny', status: 403, reason: 'invalid_session', clearHandoffState: state }
|
|
597
609
|
}
|
|
598
610
|
return { outcome: 'handoff', status: 302, location: result.returnUrl, session: result.session, expiresAt: result.expiresAt, handoffState: state }
|
|
599
611
|
}
|
|
600
612
|
|
|
613
|
+
/**
|
|
614
|
+
* Sign the browser out of this host (ADR-0067 §5). Called for the reserved sign-out path only, BEFORE the endpoint
|
|
615
|
+
* is planned, for any entry and any session. It drops this session's cached token, so the next request re-mints
|
|
616
|
+
* from IAM, which has revoked the session by then or still holds it; the cookie itself is cleared by the response.
|
|
617
|
+
*
|
|
618
|
+
* Admission is `Sec-Fetch-Site: same-origin`, absent included: the request changes state, and another page must not
|
|
619
|
+
* sign a person out, as for a session request that is not a `GET` (ADR-0022 rule 3, step 6).
|
|
620
|
+
*/
|
|
621
|
+
signOut(resolved: ResolvedApp, request: ForwardedRequest): Decision {
|
|
622
|
+
if (request.method !== 'GET') {
|
|
623
|
+
return { outcome: 'deny', status: 403, reason: 'no_endpoint' }
|
|
624
|
+
}
|
|
625
|
+
if (request.headers.get(FETCH_SITE_HEADER) !== 'same-origin') {
|
|
626
|
+
return { outcome: 'deny', status: 403, reason: 'cross_site' }
|
|
627
|
+
}
|
|
628
|
+
const app = resolved.app
|
|
629
|
+
const returnTo = request.url.searchParams.get(LOGIN_REDIRECT_PARAM)
|
|
630
|
+
const target = returnTo === null ? null : sameOriginTarget(new URL(`${app.scheme}://${request.url.host}`).origin, returnTo)
|
|
631
|
+
if (target === null) {
|
|
632
|
+
return { outcome: 'deny', status: 400, reason: 'bad_redirect' }
|
|
633
|
+
}
|
|
634
|
+
const session = readCookie(request.headers.get('Cookie'), SESSION_COOKIE)
|
|
635
|
+
if (session !== null) {
|
|
636
|
+
this.cache?.delete(cacheKey(app.id, 'session', session))
|
|
637
|
+
}
|
|
638
|
+
const release = new URL(SIGNOUT_RELEASE_PATH, this.options.issuer.replace(/\/+$/, ''))
|
|
639
|
+
release.searchParams.set('app', audienceOf(app))
|
|
640
|
+
release.searchParams.set(LOGIN_REDIRECT_PARAM, target)
|
|
641
|
+
return { outcome: 'signout', status: 302, location: release.toString() }
|
|
642
|
+
}
|
|
643
|
+
|
|
601
644
|
private async loginDecision(
|
|
602
645
|
app: ProxyApp,
|
|
603
646
|
request: ForwardedRequest,
|
|
@@ -627,7 +670,7 @@ export class Authorizer {
|
|
|
627
670
|
// does not go through it (the Cloudflare Worker reads its env directly).
|
|
628
671
|
const issuer = this.options.issuer.replace(/\/+$/, '')
|
|
629
672
|
const login = new URL('/auth/login', issuer)
|
|
630
|
-
login.searchParams.set('app', app
|
|
673
|
+
login.searchParams.set('app', audienceOf(app))
|
|
631
674
|
login.searchParams.set(LOGIN_REDIRECT_PARAM, target.toString())
|
|
632
675
|
setHandoffParams(login, handoff)
|
|
633
676
|
return login.toString()
|
|
@@ -647,6 +690,12 @@ function admittedOrigin(app: ProxyApp, row: ManifestEndpointRow, origin: string)
|
|
|
647
690
|
return form === 'environment' && isApplicationEntry(app) && (app.crossOrigins ?? []).includes(origin) ? origin : null
|
|
648
691
|
}
|
|
649
692
|
|
|
693
|
+
/** Whether a redeemed code's return URL is on the host the callback arrived at, and that host is one of the entry's. */
|
|
694
|
+
function returnsToHost(app: ProxyApp, callback: URL, returnUrl: string): boolean {
|
|
695
|
+
const target = URL.canParse(returnUrl) ? new URL(returnUrl) : null
|
|
696
|
+
return target !== null && target.hostname === callback.hostname && app.hosts.includes(target.hostname)
|
|
697
|
+
}
|
|
698
|
+
|
|
650
699
|
function invalidKey(): Denial {
|
|
651
700
|
return { outcome: 'deny', status: 401, reason: 'invalid_key' }
|
|
652
701
|
}
|
|
@@ -738,10 +787,13 @@ function isDocumentNavigation(headers: Headers): boolean {
|
|
|
738
787
|
}
|
|
739
788
|
|
|
740
789
|
/**
|
|
741
|
-
* The `Authorization` of an anonymous request
|
|
742
|
-
*
|
|
790
|
+
* The `Authorization` of an anonymous request goes on only on a `protocol` row, whose receiver authenticates the caller
|
|
791
|
+
* itself (ADR-0069: the ops key reaches framework code only), and on a webhook row that forwards it, never with a
|
|
792
|
+
* platform key. The proxy reads no credential from it either way: no key lookup, no session.
|
|
743
793
|
*/
|
|
744
794
|
function forwardsAuthorization(row: ManifestEndpointRow, request: ForwardedRequest): boolean {
|
|
745
795
|
const authorization = request.headers.get('Authorization')
|
|
746
|
-
|
|
796
|
+
if (authorization === null) return false
|
|
797
|
+
if (row.kind === 'protocol') return true
|
|
798
|
+
return 'authorization' in row && row.authorization === 'forward' && !carriesPlatformKey(authorization, API_KEY_PREFIX)
|
|
747
799
|
}
|
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> {
|
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'
|