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