-
Notifications
You must be signed in to change notification settings - Fork 0
Add hosted captun.sh safety controls #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
c95c334
Launch hosted captun.sh tunnels
mmkal fa1019f
Add browser tunnel demo
mmkal 9dda262
Polish hosted captun demo
mmkal 4ea175b
Fix npx preview execution
mmkal b6255a5
Refactor tunnel clients around gateway-owned URLs
mmkal 48fc952
Complete gateway-owned addressing task
mmkal ce12906
Record hosted gateway deployment verification
mmkal 8e65b3e
Fail fast on legacy hosted config
mmkal 3a3bb4c
Use portable token comparison
mmkal 3c10091
Add hosted captun.sh safety controls
mmkal 1a924a7
Separate hosted service from deployable worker
mmkal 6a72436
Merge hosted gateway split into hosted safety
mmkal ead1f28
Polish hosted landing page
mmkal 93b12be
Merge remote-tracking branch 'origin/hosted-captun-sh' into mmkal/26/…
mmkal 52d6ecd
Show hosted demo connect timing
mmkal 45b888f
Merge remote-tracking branch 'origin/hosted-captun-sh' into mmkal/26/…
mmkal bd502c3
Fix hosted demo escape source
mmkal d41f629
Merge hosted demo escape fix
mmkal ec3a912
Merge main after hosted launch
mmkal 5232f5a
Share CaptunServerShard with hosted gateway
mmkal c07fc52
Use subclassed shard policy for hosted gateway
mmkal 7c77471
Strip broad hosted tunnel cookies
mmkal dea1872
Reject duplicate broad hosted cookie domains
mmkal 133ffbf
Merge main after runtime adapters
mmkal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| import { DurableObject } from "cloudflare:workers"; | ||
|
|
||
| export type HostedRateLimitEnv = { | ||
| HostedRateLimiter?: DurableObjectNamespace<HostedRateLimiter>; | ||
| HOSTED_RATE_LIMIT_WINDOW_SECONDS?: string; | ||
| HOSTED_CONNECTS_PER_IP_PER_WINDOW?: string; | ||
| HOSTED_REQUESTS_PER_IP_PER_WINDOW?: string; | ||
| HOSTED_REQUESTS_PER_TUNNEL_PER_WINDOW?: string; | ||
| HOSTED_RATE_LIMIT_DISABLED?: string; | ||
| }; | ||
|
|
||
| const DEFAULT_HOSTED_RATE_LIMIT_WINDOW_SECONDS = 60; | ||
| const DEFAULT_HOSTED_CONNECTS_PER_IP_PER_WINDOW = 30; | ||
| const DEFAULT_HOSTED_REQUESTS_PER_IP_PER_WINDOW = 600; | ||
| const DEFAULT_HOSTED_REQUESTS_PER_TUNNEL_PER_WINDOW = 1200; | ||
| const HOSTED_RATE_LIMIT_DIAGNOSTIC_WINDOW_MS = 2_000; | ||
|
|
||
| type HostedRateLimitKind = "connect" | "request"; | ||
|
|
||
| type HostedRateLimitInput = { limit: number; windowSeconds: number }; | ||
|
|
||
| type HostedRateLimitResult = { ok: true } | { ok: false; limit: number; retryAfterSeconds: number }; | ||
|
|
||
| type HostedRateLimitBucket = { | ||
| count: number; | ||
| resetAt: number; | ||
| lastRejectedAt?: number; | ||
| }; | ||
|
|
||
| export class HostedRateLimiter extends DurableObject<HostedRateLimitEnv> { | ||
| private bucket: HostedRateLimitBucket | undefined; | ||
|
|
||
| check(input: HostedRateLimitInput): HostedRateLimitResult { | ||
| const now = Date.now(); | ||
| const bucket = this.activeBucket(now, now + input.windowSeconds * 1000); | ||
| if (bucket.count >= input.limit) { | ||
| bucket.lastRejectedAt = now; | ||
| return { | ||
| ok: false, | ||
| limit: input.limit, | ||
| retryAfterSeconds: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)), | ||
| }; | ||
| } | ||
|
|
||
| bucket.count++; | ||
| return { ok: true }; | ||
| } | ||
|
|
||
| diagnose(input: HostedRateLimitInput): HostedRateLimitResult { | ||
| const now = Date.now(); | ||
| const bucket = this.bucket; | ||
| if ( | ||
| bucket && | ||
| bucket.count >= input.limit && | ||
| bucket.resetAt > now && | ||
| bucket.lastRejectedAt && | ||
| now - bucket.lastRejectedAt <= HOSTED_RATE_LIMIT_DIAGNOSTIC_WINDOW_MS | ||
| ) { | ||
| return { | ||
| ok: false, | ||
| limit: input.limit, | ||
| retryAfterSeconds: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)), | ||
| }; | ||
| } | ||
|
|
||
| return { ok: true }; | ||
| } | ||
|
|
||
| private activeBucket(now: number, resetAt: number): HostedRateLimitBucket { | ||
| if (this.bucket && this.bucket.resetAt > now) return this.bucket; | ||
| const bucket: HostedRateLimitBucket = { count: 0, resetAt }; | ||
| this.bucket = bucket; | ||
| return bucket; | ||
| } | ||
| } | ||
|
|
||
| export async function hostedRateLimitResponse(input: { | ||
| env: HostedRateLimitEnv; | ||
| request: Request; | ||
| tunnelName: string; | ||
| kind: HostedRateLimitKind; | ||
| }): Promise<Response | undefined> { | ||
| if (!input.env.HostedRateLimiter) { | ||
| return hostedRateLimiterMissingResponse(input.env); | ||
| } | ||
|
|
||
| const config = hostedRateLimitConfig(input.env); | ||
| const checks = hostedRateLimitChecks({ | ||
| kind: input.kind, | ||
| clientKey: hostedClientKey(input.request), | ||
| tunnelName: input.tunnelName, | ||
| config, | ||
| }); | ||
| for (const check of checks) { | ||
| const limiter = input.env.HostedRateLimiter.getByName(hostedRateLimiterName(check.key)); | ||
| const result = await limiter.check({ | ||
| limit: check.limit, | ||
| windowSeconds: config.windowSeconds, | ||
| }); | ||
| if (!result.ok) return hostedRateLimitedResponse(result); | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| export async function hostedRateLimitDiagnosticResponse(input: { | ||
| env: HostedRateLimitEnv; | ||
| request: Request; | ||
| tunnelName: string; | ||
| kind: HostedRateLimitKind; | ||
| }): Promise<Response | undefined> { | ||
| if (!input.env.HostedRateLimiter) { | ||
| return hostedRateLimiterMissingResponse(input.env); | ||
| } | ||
|
|
||
| const config = hostedRateLimitConfig(input.env); | ||
| const checks = hostedRateLimitChecks({ | ||
| kind: input.kind, | ||
| clientKey: hostedClientKey(input.request), | ||
| tunnelName: input.tunnelName, | ||
| config, | ||
| }); | ||
| for (const check of checks) { | ||
| const limiter = input.env.HostedRateLimiter.getByName(hostedRateLimiterName(check.key)); | ||
| const result = await limiter.diagnose({ | ||
| limit: check.limit, | ||
| windowSeconds: config.windowSeconds, | ||
| }); | ||
| if (!result.ok) return hostedRateLimitedResponse(result); | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| function hostedRateLimiterMissingResponse(env: HostedRateLimitEnv) { | ||
| if (env.HOSTED_RATE_LIMIT_DISABLED === "1") return undefined; | ||
| return new Response("Hosted rate limiter is not configured\n", { | ||
| status: 503, | ||
| headers: { | ||
| "content-type": "text/plain; charset=utf-8", | ||
| "cache-control": "no-store", | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| function hostedRateLimitedResponse(result: Extract<HostedRateLimitResult, { ok: false }>) { | ||
| return new Response(`Rate limit exceeded. Try again in ${result.retryAfterSeconds}s.\n`, { | ||
| status: 429, | ||
| headers: { | ||
| "content-type": "text/plain; charset=utf-8", | ||
| "cache-control": "no-store", | ||
| "retry-after": String(result.retryAfterSeconds), | ||
| "x-captun-rate-limit": String(result.limit), | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| function hostedClientKey(request: Request) { | ||
| return request.headers.get("cf-connecting-ip") || "unknown"; | ||
| } | ||
|
|
||
| function hostedRateLimitChecks(input: { | ||
| kind: HostedRateLimitKind; | ||
| clientKey: string; | ||
| tunnelName: string; | ||
| config: ReturnType<typeof hostedRateLimitConfig>; | ||
| }) { | ||
| if (input.kind === "connect") { | ||
| return [{ key: `connect:ip:${input.clientKey}`, limit: input.config.connectsPerIp }]; | ||
| } | ||
|
|
||
| return [ | ||
| { key: `request:ip:${input.clientKey}`, limit: input.config.requestsPerIp }, | ||
| { key: `request:tunnel:${input.tunnelName}`, limit: input.config.requestsPerTunnel }, | ||
| ]; | ||
| } | ||
|
|
||
| function hostedRateLimiterName(key: string) { | ||
| let hash = 2166136261; | ||
| for (let index = 0; index < key.length; index++) { | ||
| hash ^= key.charCodeAt(index); | ||
| hash = Math.imul(hash, 16777619); | ||
| } | ||
| return `bucket-${(hash >>> 0).toString(36)}`; | ||
| } | ||
|
|
||
| function hostedRateLimitConfig(env: HostedRateLimitEnv) { | ||
| return { | ||
| windowSeconds: positiveInteger( | ||
| env.HOSTED_RATE_LIMIT_WINDOW_SECONDS, | ||
| DEFAULT_HOSTED_RATE_LIMIT_WINDOW_SECONDS, | ||
| ), | ||
| connectsPerIp: positiveInteger( | ||
| env.HOSTED_CONNECTS_PER_IP_PER_WINDOW, | ||
| DEFAULT_HOSTED_CONNECTS_PER_IP_PER_WINDOW, | ||
| ), | ||
| requestsPerIp: positiveInteger( | ||
| env.HOSTED_REQUESTS_PER_IP_PER_WINDOW, | ||
| DEFAULT_HOSTED_REQUESTS_PER_IP_PER_WINDOW, | ||
| ), | ||
| requestsPerTunnel: positiveInteger( | ||
| env.HOSTED_REQUESTS_PER_TUNNEL_PER_WINDOW, | ||
| DEFAULT_HOSTED_REQUESTS_PER_TUNNEL_PER_WINDOW, | ||
| ), | ||
| }; | ||
| } | ||
|
|
||
| function positiveInteger(value: string | undefined, fallback: number) { | ||
| const parsed = Number(value); | ||
| if (!Number.isInteger(parsed) || parsed < 1) return fallback; | ||
| return parsed; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.