@fabrika/provider-cloudflare 0.0.1
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 +46 -0
- package/src/authoring.ts +34 -0
- package/src/cli-args.ts +72 -0
- package/src/cli.ts +85 -0
- package/src/codec.ts +79 -0
- package/src/collaborators.ts +104 -0
- package/src/command.ts +108 -0
- package/src/control.ts +231 -0
- package/src/index.ts +26 -0
- package/src/plan.ts +92 -0
- package/src/provider.ts +253 -0
- package/src/proxy-worker.ts +190 -0
- package/src/proxy.ts +70 -0
- package/src/schema.ts +13 -0
- package/src/wrangler.jsonc +29 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { parseProxyManifestJson, type ProxyApp, type ProxyManifest } from '@fabrika/proxy-contract'
|
|
2
|
+
import type { IamGateway, ProxyLogger, VerifyService } from '@fabrika/proxy-core'
|
|
3
|
+
import {
|
|
4
|
+
CLIENT_ADDRESS_HEADER,
|
|
5
|
+
consoleLogger,
|
|
6
|
+
createVerifyService,
|
|
7
|
+
DEFAULT_VERIFY_PATH,
|
|
8
|
+
FORWARDED_HOST_HEADER,
|
|
9
|
+
FORWARDED_METHOD_HEADER,
|
|
10
|
+
FORWARDED_PROTO_HEADER,
|
|
11
|
+
FORWARDED_URI_HEADER,
|
|
12
|
+
MemoryTokenCache,
|
|
13
|
+
PROXY_TOKEN_HEADER,
|
|
14
|
+
REQUEST_ID_HEADER,
|
|
15
|
+
stripFabrikaCookies,
|
|
16
|
+
UNTRUSTED_FORWARD_HEADERS,
|
|
17
|
+
} from '@fabrika/proxy-core'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Cloudflare's managed client address — this composition's answer to "who is the client".
|
|
21
|
+
*
|
|
22
|
+
* The edge writes it on every request it forwards and replaces a caller-supplied one, which is what
|
|
23
|
+
* makes it usable as a limiter key and is why a Worker has no need of `X-Forwarded-For`. It stays a
|
|
24
|
+
* LOCAL constant rather than moving into `@fabrika/auth-core`: it is a fact about one provider's edge,
|
|
25
|
+
* and the shared kernel must not name a provider (ADR-0011).
|
|
26
|
+
*
|
|
27
|
+
* Absent — a `wrangler dev`-style local run, or a request arriving over a service binding rather than
|
|
28
|
+
* the edge — means this hop cannot see the client, so nothing is injected and the upstream falls back
|
|
29
|
+
* to its deployment-wide bucket.
|
|
30
|
+
*/
|
|
31
|
+
const CLOUDFLARE_CLIENT_ADDRESS_HEADER = 'CF-Connecting-IP'
|
|
32
|
+
|
|
33
|
+
export interface CloudflareProxyEnv {
|
|
34
|
+
readonly IAM?: unknown
|
|
35
|
+
readonly FABRIKA_PROXY_MANIFEST_JSON?: string
|
|
36
|
+
readonly FABRIKA_IAM_URL?: string
|
|
37
|
+
readonly [binding: string]: unknown
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface WorkerService {
|
|
41
|
+
fetch(request: Request): Promise<Response>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type ProxyFetch = (request: Request) => Promise<Response>
|
|
45
|
+
|
|
46
|
+
const UNAVAILABLE = new Response('proxy unavailable', {
|
|
47
|
+
status: 503,
|
|
48
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
let cached: {
|
|
52
|
+
readonly manifestJson: string
|
|
53
|
+
readonly iam: IamGateway
|
|
54
|
+
readonly issuer: string
|
|
55
|
+
readonly handler: ProxyFetch
|
|
56
|
+
} | undefined
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The issuer in the form the token's `iss` is compared against — `new URL(...).origin`, http(s) only.
|
|
60
|
+
* Null when it is unusable, which must refuse to serve rather than boot: jose compares `iss`
|
|
61
|
+
* byte-for-byte, so an absent or unparseable issuer does not degrade, it fails EVERY verification as
|
|
62
|
+
* if the token were forged. The Bun composition gets this from `readProxyEnv`, which this Worker does
|
|
63
|
+
* not run — the check has to exist on both or the invariant only holds on one provider.
|
|
64
|
+
*/
|
|
65
|
+
function canonicalIssuer(raw: string | undefined): string | null {
|
|
66
|
+
if (raw === undefined || raw.trim() === '') return null
|
|
67
|
+
try {
|
|
68
|
+
const url = new URL(raw.trim())
|
|
69
|
+
return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : null
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Factory exported for Lopata and unit tests; production uses the default Worker fetch below. */
|
|
76
|
+
export function createCloudflareProxyHandler(env: CloudflareProxyEnv, logger: ProxyLogger = consoleLogger): ProxyFetch {
|
|
77
|
+
const manifestJson = env.FABRIKA_PROXY_MANIFEST_JSON ?? ''
|
|
78
|
+
const canonical = canonicalIssuer(env.FABRIKA_IAM_URL)
|
|
79
|
+
if (!isIamGateway(env.IAM) || manifestJson === '' || canonical === null) return () => Promise.resolve(UNAVAILABLE.clone())
|
|
80
|
+
const issuer = canonical
|
|
81
|
+
|
|
82
|
+
const manifest = parseProxyManifestJson(manifestJson)
|
|
83
|
+
if (manifest === null || !validManifest(manifest)) return () => Promise.resolve(UNAVAILABLE.clone())
|
|
84
|
+
|
|
85
|
+
if (cached?.manifestJson === manifestJson && cached.iam === env.IAM && cached.issuer === issuer) {
|
|
86
|
+
return cached.handler
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const verify = createVerifyService({
|
|
90
|
+
manifest,
|
|
91
|
+
iam: env.IAM,
|
|
92
|
+
issuer,
|
|
93
|
+
cache: new MemoryTokenCache(),
|
|
94
|
+
logger,
|
|
95
|
+
})
|
|
96
|
+
const handler = proxyHandler(env, manifest, verify)
|
|
97
|
+
cached = { manifestJson, iam: env.IAM, issuer, handler }
|
|
98
|
+
return handler
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function proxyHandler(env: CloudflareProxyEnv, manifest: ProxyManifest, verify: VerifyService): ProxyFetch {
|
|
102
|
+
return async (request) => {
|
|
103
|
+
const url = new URL(request.url)
|
|
104
|
+
const clientAddress = request.headers.get(CLOUDFLARE_CLIENT_ADDRESS_HEADER)
|
|
105
|
+
const headers = new Headers(request.headers)
|
|
106
|
+
// The same strips the generated Caddy route does: a client may assert neither the injected token,
|
|
107
|
+
// nor the request id that lands in IAM's audit trail, nor the client address an upstream limits
|
|
108
|
+
// on. The first two come back from the decision; the third is re-derived below from the edge.
|
|
109
|
+
stripClientAsserted(headers)
|
|
110
|
+
headers.set(FORWARDED_METHOD_HEADER, request.method)
|
|
111
|
+
headers.set(FORWARDED_URI_HEADER, `${url.pathname}${url.search}`)
|
|
112
|
+
headers.set(FORWARDED_HOST_HEADER, url.host)
|
|
113
|
+
headers.set(FORWARDED_PROTO_HEADER, url.protocol === 'http:' ? 'http' : 'https')
|
|
114
|
+
if (clientAddress !== null && clientAddress !== '') headers.set(CLIENT_ADDRESS_HEADER, clientAddress)
|
|
115
|
+
|
|
116
|
+
const verification = await verify(
|
|
117
|
+
new Request(`https://fabrika-proxy.internal${DEFAULT_VERIFY_PATH}`, {
|
|
118
|
+
method: 'GET',
|
|
119
|
+
headers,
|
|
120
|
+
}),
|
|
121
|
+
)
|
|
122
|
+
if (!verification.ok) return verification
|
|
123
|
+
|
|
124
|
+
const app = findApp(manifest, url)
|
|
125
|
+
if (app === null) return new Response('not found', { status: 404 })
|
|
126
|
+
const upstream = env[app.upstream]
|
|
127
|
+
if (!isWorkerService(upstream)) return UNAVAILABLE.clone()
|
|
128
|
+
|
|
129
|
+
// Built from the ORIGINAL headers, so it is stripped again here — the set above was applied to the
|
|
130
|
+
// verify subrequest, not to this one.
|
|
131
|
+
const upstreamHeaders = new Headers(request.headers)
|
|
132
|
+
stripClientAsserted(upstreamHeaders)
|
|
133
|
+
stripFabrikaCookies(upstreamHeaders)
|
|
134
|
+
if (clientAddress !== null && clientAddress !== '') upstreamHeaders.set(CLIENT_ADDRESS_HEADER, clientAddress)
|
|
135
|
+
const token = verification.headers.get(PROXY_TOKEN_HEADER)
|
|
136
|
+
if (token !== null && token !== '') upstreamHeaders.set(PROXY_TOKEN_HEADER, token)
|
|
137
|
+
const requestId = verification.headers.get(REQUEST_ID_HEADER)
|
|
138
|
+
if (requestId !== null && requestId !== '') upstreamHeaders.set(REQUEST_ID_HEADER, requestId)
|
|
139
|
+
|
|
140
|
+
return upstream.fetch(new Request(request, { headers: upstreamHeaders }))
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Delete every header only this hop may assert, so nothing downstream can read a caller's version. */
|
|
145
|
+
function stripClientAsserted(headers: Headers): void {
|
|
146
|
+
headers.delete(PROXY_TOKEN_HEADER)
|
|
147
|
+
headers.delete(REQUEST_ID_HEADER)
|
|
148
|
+
headers.delete(CLIENT_ADDRESS_HEADER)
|
|
149
|
+
for (const header of UNTRUSTED_FORWARD_HEADERS) headers.delete(header)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function findApp(manifest: ProxyManifest, url: URL): ProxyApp | null {
|
|
153
|
+
const host = url.host.toLowerCase()
|
|
154
|
+
const hostname = url.hostname.toLowerCase()
|
|
155
|
+
return manifest.apps.find((app) => app.hosts.includes(host) || app.hosts.includes(hostname)) ?? null
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function validManifest(manifest: ProxyManifest): boolean {
|
|
159
|
+
const hosts = new Set<string>()
|
|
160
|
+
for (const app of manifest.apps) {
|
|
161
|
+
if (app.upstream === '' || app.hosts.length === 0) return false
|
|
162
|
+
for (const host of app.hosts) {
|
|
163
|
+
if (hosts.has(host)) return false
|
|
164
|
+
hosts.add(host)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return manifest.apps.length > 0
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isIamGateway(value: unknown): value is IamGateway {
|
|
171
|
+
return isObject(value)
|
|
172
|
+
&& typeof value['mintToken'] === 'function'
|
|
173
|
+
&& typeof value['mintFromKey'] === 'function'
|
|
174
|
+
&& typeof value['exchangeAuthCode'] === 'function'
|
|
175
|
+
&& typeof value['getJwks'] === 'function'
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isWorkerService(value: unknown): value is WorkerService {
|
|
179
|
+
return isObject(value) && typeof value['fetch'] === 'function'
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
183
|
+
return typeof value === 'object' && value !== null
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export default {
|
|
187
|
+
fetch(request: Request, env: CloudflareProxyEnv): Promise<Response> {
|
|
188
|
+
return createCloudflareProxyHandler(env)(request)
|
|
189
|
+
},
|
|
190
|
+
}
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { AppGates } from '@fabrika/auth'
|
|
2
|
+
import { encodeProxyManifestJson, type ProxyManifest } from '@fabrika/proxy-contract'
|
|
3
|
+
import { ServiceReference, Worker } from 'oblaka-iac'
|
|
4
|
+
|
|
5
|
+
export interface CloudflareProxyWorkerOptions {
|
|
6
|
+
/** Name of the proxy Worker before the environment prefix is applied by oblaka. */
|
|
7
|
+
readonly name: string
|
|
8
|
+
/** The application Worker. It must not have a public route of its own. */
|
|
9
|
+
readonly app: Worker
|
|
10
|
+
/** IAM application id used to mint and verify the upstream token. */
|
|
11
|
+
readonly appId: string
|
|
12
|
+
/** Host matched by the proxy manifest. Use the public custom domain when one exists. */
|
|
13
|
+
readonly appHost: string
|
|
14
|
+
/** Ordered gate rules evaluated by the shared proxy authorizer. */
|
|
15
|
+
readonly gates: AppGates
|
|
16
|
+
/** Optional Cloudflare custom domain for the proxy Worker. */
|
|
17
|
+
readonly domain?: string
|
|
18
|
+
/** IAM service name. The global default is the platform IAM Worker. */
|
|
19
|
+
readonly iamService?: string
|
|
20
|
+
/** IAM origin used for login redirects and token issuer validation. */
|
|
21
|
+
readonly iamUrl?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Build the Cloudflare side of the accepted proxy topology: the public Worker owns the route and
|
|
26
|
+
* binds the private application Worker. IAM remains a global service binding.
|
|
27
|
+
*/
|
|
28
|
+
export function createCloudflareProxyWorker(options: CloudflareProxyWorkerOptions): Worker {
|
|
29
|
+
if ((options.app.options.routes?.length ?? 0) > 0) {
|
|
30
|
+
throw new Error(`cloudflare proxy app \`${options.app.options.name}\` must not declare public routes`)
|
|
31
|
+
}
|
|
32
|
+
if (options.app.options.workers_dev !== false) {
|
|
33
|
+
throw new Error(`cloudflare proxy app \`${options.app.options.name}\` must disable workers.dev`)
|
|
34
|
+
}
|
|
35
|
+
if (options.appHost.trim() === '') {
|
|
36
|
+
throw new Error('cloudflare proxy appHost must be non-empty')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const local = options.appHost === 'localhost'
|
|
40
|
+
const manifest: ProxyManifest = {
|
|
41
|
+
apps: [{
|
|
42
|
+
id: options.appId,
|
|
43
|
+
hosts: local ? ['localhost', '127.0.0.1'] : [options.appHost],
|
|
44
|
+
upstream: 'APP',
|
|
45
|
+
gates: options.gates,
|
|
46
|
+
// Cloudflare terminates TLS at the edge and a route is always https; only a localhost
|
|
47
|
+
// binding is reached over plain HTTP.
|
|
48
|
+
scheme: local ? 'http' : 'https',
|
|
49
|
+
}],
|
|
50
|
+
}
|
|
51
|
+
const domain = options.domain?.trim()
|
|
52
|
+
|
|
53
|
+
return new Worker({
|
|
54
|
+
dir: import.meta.dir,
|
|
55
|
+
name: options.name,
|
|
56
|
+
main: './proxy-worker.ts',
|
|
57
|
+
compatibility_flags: ['nodejs_compat'],
|
|
58
|
+
compatibility_date: '2025-05-25',
|
|
59
|
+
routes: domain === undefined || domain === '' ? [] : [{ pattern: domain, custom_domain: true }],
|
|
60
|
+
observability: { logs: { enabled: true, invocation_logs: false } },
|
|
61
|
+
vars: {
|
|
62
|
+
FABRIKA_PROXY_MANIFEST_JSON: encodeProxyManifestJson(manifest),
|
|
63
|
+
FABRIKA_IAM_URL: options.iamUrl ?? '',
|
|
64
|
+
},
|
|
65
|
+
bindings: {
|
|
66
|
+
IAM: new ServiceReference(options.iamService ?? 'propustka-worker'),
|
|
67
|
+
APP: options.app,
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { reconcileSchema } from '@fabrika/auth'
|
|
2
|
+
import type { SchemaReconciler } from '@fabrika/provider-contract'
|
|
3
|
+
|
|
4
|
+
/** Default IAM schema reconciler shared by production Cloudflare sessions. */
|
|
5
|
+
export const defaultReconcileSchema: SchemaReconciler = (input) =>
|
|
6
|
+
reconcileSchema({
|
|
7
|
+
url: input.url,
|
|
8
|
+
app: input.app,
|
|
9
|
+
schema: input.schema,
|
|
10
|
+
...(input.returnOrigins === undefined ? {} : { returnOrigins: input.returnOrigins }),
|
|
11
|
+
adminKey: input.adminKey,
|
|
12
|
+
signal: input.signal,
|
|
13
|
+
})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File is auto generated DO NOT EDIT
|
|
3
|
+
*/
|
|
4
|
+
{
|
|
5
|
+
"name": "propustka-example-proxy",
|
|
6
|
+
"main": "./proxy-worker.ts",
|
|
7
|
+
"compatibility_flags": [
|
|
8
|
+
"nodejs_compat"
|
|
9
|
+
],
|
|
10
|
+
"compatibility_date": "2025-05-25",
|
|
11
|
+
"routes": [],
|
|
12
|
+
"observability": {
|
|
13
|
+
"enabled": true
|
|
14
|
+
},
|
|
15
|
+
"vars": {
|
|
16
|
+
"FABRIKA_PROXY_MANIFEST_JSON": "{\"apps\":[{\"id\":\"example-app\",\"hosts\":[\"localhost\",\"127.0.0.1\"],\"upstream\":\"APP\",\"gates\":{\"rules\":[{\"path\":\"/public/*\",\"kind\":\"public\"},{\"path\":\"/*\",\"kind\":\"service\"},{\"path\":\"/*\",\"kind\":\"human\"}]},\"scheme\":\"http\"}]}",
|
|
17
|
+
"FABRIKA_IAM_URL": "http://localhost:18191"
|
|
18
|
+
},
|
|
19
|
+
"services": [
|
|
20
|
+
{
|
|
21
|
+
"binding": "IAM",
|
|
22
|
+
"service": "propustka-worker"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"binding": "APP",
|
|
26
|
+
"service": "propustka-example-app"
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|