commit 3e95c8f71a8347794e4f7373cee5a3a6cdb14f44 Author: RTAkland Date: Sat Jan 3 04:08:34 2026 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..74fdfe0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.idea/ +.kotlin/ +build/ +.gradle/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd428a4 --- /dev/null +++ b/README.md @@ -0,0 +1,155 @@ +# Kotlin cloudflare worker + +A library to running kotlin/js on cloudflare worker. + +# Get started + +## Setup + +> `kotlinx.coroutines` is required + +```kotlin +plugins { + kotlin("multiplatform") version "2.2.21" +} + +repositories { + mavenCentral() + maven("https://repo.maven.rtast.cn/releases") +} +``` + +```kotlin +// to get latest version of this lib, go to +// https://next.pkg.rtast.cn/#/releases/cn/rtast/kotlin-cfworker/kotlin-cloudflare-worker/ +implementation("cn.rtast.kotlin-cfworker:kotlin-cloudflare-worker:1.0.1") +``` + +## Run app + +```kotlin +kotlin { + js(IR) { + nodejs { + outputModuleName = "kotlin-cloudflare-worker" + binaries.executable() + } + } +} +``` + +> Minimal hello world app + +```kotlin +/** + * DO NOT EDIT THIS FUNCTION + */ +fun main() { + @Suppress("unused_expression") + val eventListener = EventListener { event -> + val dyn = event.asDynamic() + event.asDynamic().respondWith(handleRequest(dyn.request as Request)) + Unit + } + js("addEventListener('fetch', eventListener)") +} + +@JsExport +fun handleRequest(request: Request): Promise = GlobalScope.promise { + val server = WorkerApplication().apply { + route("/") { + respondText("Hello kotlin cloudflare worker") + } + } + return@promise server.handle(request) +} + +``` + +> Before run worker locally, you need to install wrangler and login + +First, create `wrangler.toml` in your root project and configure it + +```toml +name = "kotlin-cloudflare-worker" # any name you want +account_id = "" +workers_dev = false +preview_urls = false +compatibility_date = "2022-08-11" +main = "kotlin-cloudflare-worker.js" # Set this value same as `outputModuleName` +``` + +Then run gradle task `gradlew compileProductionExecutableKotlinJs`, +copy wrangler.toml into `build/compileSync/js/main/productionExecutable/kotlin`, +and run `wrangler dev` command in `build/compileSync/js/main/productionExecutable/kotlin`, + +## Deploy + +Run gradle task, copy wrangler.toml, but use `wrangler deploy` to deploy to cloudflare worker + +# Note + +JavaScript uses a single-threaded execution model. All asynchronous work is ultimately driven by the event loop ( +including Kotlin coroutines on JS). + +Therefore, DO NOT create a CoroutineScope(Dispatchers.Default) or launch CPU-bound coroutines, as there is no real +background thread on JS targets. + +All coroutines run on same event loop thread, and all coroutines not in same event loop will be dropped. + +Example: + +```kotlin +// DO NOT DO THIS +val scope = CoroutineScope(Dispatcher.DEFAULT) + +fun blockingFunction() { + scope.launch { + // this block will never execute + } +} + +// Instead of do this + +fun main() { + @Suppress("unused_expression") + val eventListener = EventListener { event -> + val dyn = event.asDynamic() + event.asDynamic().respondWith(handleRequest(dyn.request as Request)) + Unit + } + js("addEventListener('fetch', eventListener)") +} + +@JsExport +fun handleRequest(request: Request): Promise = GlobalScope.promise { + return Promise.resolve(Response("Hello")) +} +``` + +# Http client + +Cloudflare worker is not a standard nodejs environment, do http requests must +use fetch api(not `window.fetch`, this is browser api), use `cn.rtast.cfworker.client.fetch` instead, + +# ByteArray and ByteBuffer cast + +Kotlin cloudflare worker provided api to mutual conversion, + +```kotlin +import cn.rtast.cfworker.util.toByteArray +import cn.rtast.cfworker.util.toArrayBuffer + +val bb: ByteBuffer = ... +// convert ByteBuffer to ByteArray +val ba: ByteArray = bb.toByteArray() + +// convert ByteArray to ByteBuffer +val bb2: ByteBuffer = ba.toArrayBuffer() +``` + +# Real instance + +https://repo.maven.rtast.cn + +> Yes, it the maven repository but built with kotlin/js with this lib \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..c6f434a --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,37 @@ +plugins { + kotlin("multiplatform") version "2.2.21" + id("maven-publish") +} + +group = "cn.rtast.kotlin-cfworker" +version = "1.0.1" + +repositories { + mavenCentral() +} + +kotlin { + explicitApi() + js(IR) { nodejs { binaries.executable() } } + + sourceSets { + jsMain.dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + } + + commonTest.dependencies { + implementation(kotlin("test")) + } + } +} + +publishing { + repositories { + maven("https://repo.maven.rtast.cn/releases") { + credentials { + username = "RTAkland" + password = System.getenv("PUBLISH_TOKEN") + } + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5492a20 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Jan 03 02:49:25 CST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..95c22d3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "kotlin-cloudflare-worker" \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/CORS.kt b/src/jsMain/kotlin/cn/rtast/cfworker/CORS.kt new file mode 100644 index 0000000..fe8bb9a --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/CORS.kt @@ -0,0 +1,39 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 17:29 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker + +import org.w3c.fetch.ResponseInit + +/** + * Auto add cors response headers + */ +@Suppress("FunctionName") +internal fun WorkerApplication._addCorsHeaders( + init: ResponseInit, + origin: String = "*", + allowedMethods: Set = setOf( + HttpMethod.GET, HttpMethod.POST, + HttpMethod.DELETE, HttpMethod.DELETE, + HttpMethod.OPTIONS + ), +): ResponseInit { + val headers = if (this.corsConfig.enabled) { + val corsHeaders = init.headers ?: js("{}") + corsHeaders["Access-Control-Allow-Origin"] = origin + corsHeaders["Access-Control-Allow-Methods"] = allowedMethods.joinToString(", ") + corsHeaders["Access-Control-Allow-Headers"] = "Content-Type, Authorization" + corsHeaders["Access-Control-Max-Age"] = "86400" + corsHeaders + } else init.headers + return ResponseInit( + headers = headers, + status = init.status, + statusText = init.statusText + ) +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/HttpMethod.kt b/src/jsMain/kotlin/cn/rtast/cfworker/HttpMethod.kt new file mode 100644 index 0000000..b048779 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/HttpMethod.kt @@ -0,0 +1,38 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:02 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker + +import org.w3c.fetch.Request + +/** + * Common http method + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods + */ +public enum class HttpMethod { + GET, + POST, + PUT, + DELETE, + PATCH, + HEAD, + OPTIONS, + TRACE, + CONNECT; + + public companion object { + public fun fromString(method: String): HttpMethod? = + entries.firstOrNull { it.name.equals(method, ignoreCase = true) } + } +} + +/** + * Get parsed http method, if it's not a standard http method return GET + */ +public val Request.httpMethod: HttpMethod + get() = HttpMethod.fromString(this.method) ?: HttpMethod.GET \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/WorkerApplication.kt b/src/jsMain/kotlin/cn/rtast/cfworker/WorkerApplication.kt new file mode 100644 index 0000000..2f50bec --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/WorkerApplication.kt @@ -0,0 +1,77 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:03 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker + +import cn.rtast.cfworker.auth.AuthResult +import cn.rtast.cfworker.auth.packBasicCredential +import cn.rtast.cfworker.auth.packBearerCredential +import cn.rtast.cfworker.auth.provider.BasicAuthenticator +import cn.rtast.cfworker.auth.provider.BearerAuthenticator +import cn.rtast.cfworker.config.CORSConfig +import cn.rtast.cfworker.response.respondEmpty +import cn.rtast.cfworker.response.respondText +import cn.rtast.cfworker.route.type.AbstractRoute +import cn.rtast.cfworker.route.type.RegexRoute +import cn.rtast.cfworker.route.type.StringRoute +import cn.rtast.cfworker.util.decodeBase64String +import org.w3c.dom.url.URL +import org.w3c.fetch.Request +import org.w3c.fetch.Response + +/** + * Kotlin cloudflare worker logic entrypoint class + */ +public class WorkerApplication( + public val corsConfig: CORSConfig = CORSConfig(), +) { + internal val routes: MutableList = mutableListOf() + + public suspend fun handle(request: Request): Response { + val url = URL(request.url) + val path = url.pathname + val method = HttpMethod.fromString(request.method) ?: HttpMethod.GET + if (method == HttpMethod.OPTIONS && corsConfig.enabled) return respondEmpty() + val matchedRoutes = routes.filter { + when (it) { + is StringRoute -> it.path == path + is RegexRoute -> it.path.matches(path) + else -> false + } + } + + if (matchedRoutes.isEmpty()) return respondText("Not Found", 404) + val methodMatchedRoute = matchedRoutes.firstOrNull { method in it.methods } + if (methodMatchedRoute == null) { + val allowMethods = matchedRoutes.flatMap { it.methods }.distinct().joinToString(", ") + val headers: dynamic = js("{}") + headers["Allow"] = allowMethods + return respondText("Method Not Allowed", 405) + } + + val auth = methodMatchedRoute.authenticator + val responsePromise = if (auth != null) { + val credential = when (auth) { + is BasicAuthenticator -> request.headers.get("authorization") + ?.removePrefix("Basic ") + ?.decodeBase64String + ?.packBasicCredential() + + is BearerAuthenticator -> request.headers.get("authorization") + ?.removePrefix("Bearer ") + ?.packBearerCredential() + } + when (auth.authenticate(request, credential)) { + AuthResult.OK -> methodMatchedRoute.handle(request) + AuthResult.UNAUTHORIZED -> respondText("UNAUTHORIZED", 401) + AuthResult.FORBIDDEN -> respondText("FORBIDDEN", 403) + } + } else methodMatchedRoute.handle(request) + return responsePromise + } +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthResult.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthResult.kt new file mode 100644 index 0000000..58c7a87 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthResult.kt @@ -0,0 +1,13 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/25 11:41 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker.auth + +public enum class AuthResult { + OK, UNAUTHORIZED, FORBIDDEN +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthUtil.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthUtil.kt new file mode 100644 index 0000000..637e909 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/AuthUtil.kt @@ -0,0 +1,18 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.auth + +import cn.rtast.cfworker.auth.credentials.BasicCredential +import cn.rtast.cfworker.auth.credentials.BearerCredential + +internal fun String.packBasicCredential(): BasicCredential { + val parts = this.split(":") + return BasicCredential(parts.first(), parts.last()) +} + +internal fun String.packBearerCredential(): BearerCredential = BearerCredential(this) \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BasicCredential.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BasicCredential.kt new file mode 100644 index 0000000..cb87c76 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BasicCredential.kt @@ -0,0 +1,16 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.auth.credentials + +/** + * Basic credential + */ +public data class BasicCredential( + val username: String, + val password: String, +) : HttpCredential \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BearerCredential.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BearerCredential.kt new file mode 100644 index 0000000..86b00b9 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/BearerCredential.kt @@ -0,0 +1,15 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.auth.credentials + +/** + * Bearer credential + */ +public data class BearerCredential( + val token: String, +) : HttpCredential \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/HttpCredential.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/HttpCredential.kt new file mode 100644 index 0000000..e11b71f --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/credentials/HttpCredential.kt @@ -0,0 +1,11 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.auth.credentials + +@Suppress("CLASSNAME") +public sealed interface HttpCredential \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/Authenticator.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/Authenticator.kt new file mode 100644 index 0000000..cc712e6 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/Authenticator.kt @@ -0,0 +1,13 @@ +package cn.rtast.cfworker.auth.provider + +import cn.rtast.cfworker.auth.AuthResult +import cn.rtast.cfworker.auth.credentials.HttpCredential +import org.w3c.fetch.Request + +/** + * An interface for authenticating + * It's sealed + */ +public sealed interface Authenticator { + public suspend fun authenticate(request: Request, credential: C?): AuthResult +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BasicAuthenticator.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BasicAuthenticator.kt new file mode 100644 index 0000000..cd7d80d --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BasicAuthenticator.kt @@ -0,0 +1,13 @@ +package cn.rtast.cfworker.auth.provider + +import cn.rtast.cfworker.auth.AuthResult +import cn.rtast.cfworker.auth.credentials.BasicCredential +import org.w3c.fetch.Request + +/** + * Basic auth provider + * Schema: Basic + */ +public fun interface BasicAuthenticator : Authenticator { + override suspend fun authenticate(request: Request, credential: BasicCredential?): AuthResult +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BearerAuthenticator.kt b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BearerAuthenticator.kt new file mode 100644 index 0000000..034e123 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/auth/provider/BearerAuthenticator.kt @@ -0,0 +1,20 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.auth.provider + +import cn.rtast.cfworker.auth.AuthResult +import cn.rtast.cfworker.auth.credentials.BearerCredential +import org.w3c.fetch.Request + +/** + * Bearer token auth provider + * Schema: Bearer + */ +public fun interface BearerAuthenticator : Authenticator { + override suspend fun authenticate(request: Request, credential: BearerCredential?): AuthResult +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/client/fetch.kt b/src/jsMain/kotlin/cn/rtast/cfworker/client/fetch.kt new file mode 100644 index 0000000..031ee78 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/client/fetch.kt @@ -0,0 +1,17 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.client + +import org.w3c.fetch.RequestInit +import org.w3c.fetch.Response +import kotlin.js.Promise + +public external fun fetch( + input: String, + init: RequestInit = definedExternally, +): Promise \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/config/CORSConfig.kt b/src/jsMain/kotlin/cn/rtast/cfworker/config/CORSConfig.kt new file mode 100644 index 0000000..c0efc04 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/config/CORSConfig.kt @@ -0,0 +1,31 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.config + +import cn.rtast.cfworker.HttpMethod + +public class CORSConfig { + /** + * enabled cors agent + */ + public var enabled: Boolean = true + + /** + * Allowed origin + */ + public var origin: String = "*" + + /** + * Allowed methods + */ + public var allowedMethods: Set = setOf( + HttpMethod.GET, HttpMethod.POST, + HttpMethod.DELETE, HttpMethod.DELETE, + HttpMethod.OPTIONS + ) +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/main.kt b/src/jsMain/kotlin/cn/rtast/cfworker/main.kt new file mode 100644 index 0000000..dea095e --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/main.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +/** + * This file is for internally use + */ + +@file:OptIn(DelicateCoroutinesApi::class, ExperimentalJsExport::class) + +package cn.rtast.cfworker + +import cn.rtast.cfworker.response.respondText +import cn.rtast.cfworker.route.route +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.promise +import org.w3c.dom.events.EventListener +import org.w3c.fetch.Request +import org.w3c.fetch.Response +import kotlin.js.Promise + +public fun main() { + @Suppress("unused_expression") + val eventListener = EventListener { event -> + val dyn = event.asDynamic() + event.asDynamic().respondWith(handleRequest(dyn.request as Request)) + Unit + } + js("addEventListener('fetch', eventListener)") +} + +@JsExport +public fun handleRequest(request: Request): Promise = GlobalScope.promise { + val server = WorkerApplication().apply { + route("/") { + respondText("Hello kotlin cloudflare worker") + } + } + return@promise server.handle(request) +} diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/response/ResponseUtil.kt b/src/jsMain/kotlin/cn/rtast/cfworker/response/ResponseUtil.kt new file mode 100644 index 0000000..a6463a3 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/response/ResponseUtil.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:17 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +@file:Suppress("unused") + +package cn.rtast.cfworker.response + +import cn.rtast.cfworker.WorkerApplication +import cn.rtast.cfworker._addCorsHeaders +import org.khronos.webgl.Uint8Array +import org.w3c.fetch.Response +import org.w3c.fetch.ResponseInit + +public fun WorkerApplication.respondBytes( + bytes: ByteArray, + status: Int = 200, + contentType: String? = null, + headers: Map = mapOf(), +): Response { + val respHeaders: dynamic = js("{}") + headers.forEach { respHeaders[it.key] = it.value } + respHeaders["Content-Type"] = contentType ?: "application/octet-stream" + return Response( + Uint8Array(bytes.toTypedArray()), + _addCorsHeaders( + ResponseInit( + status = status.toShort(), + headers = respHeaders + ) + ) + ) +} + +public fun WorkerApplication.respondStream( + stream: dynamic, + status: Int = 200, + headers: Map = mapOf(), +): Response { + val respHeaders: dynamic = js("{}") + headers.forEach { respHeaders[it.key] = it.value } + return Response( + stream, + _addCorsHeaders( + ResponseInit( + status = status.toShort(), + headers = respHeaders + ) + ) + ) +} + +public fun WorkerApplication.respondEmpty( + status: Int = 204, + headers: Map = mapOf(), +): Response { + val respHeaders: dynamic = js("{}") + headers.forEach { respHeaders[it.key] = it.value } + return Response(null, _addCorsHeaders(ResponseInit(status = status.toShort(), headers = respHeaders))) +} + +public fun WorkerApplication.respondText( + content: String, + status: Int = 200, + headers: Map = mapOf(), +): Response { + val respHeaders: dynamic = js("{}") + headers.forEach { respHeaders[it.key] = it.value } + return Response(content, _addCorsHeaders(ResponseInit(status = status.toShort(), headers = respHeaders))) +} + +public fun WorkerApplication.respondRedirect( + location: String, + status: Int = 302, + headers: Map = mapOf(), +): Response { + val respHeaders: dynamic = js("{}") + headers.forEach { respHeaders[it.key] = it.value } + respHeaders["Location"] = location + return Response( + "Redirecting to $location", + _addCorsHeaders(ResponseInit(status = status.toShort(), headers = respHeaders)) + ) +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteHandler.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteHandler.kt new file mode 100644 index 0000000..d367d24 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteHandler.kt @@ -0,0 +1,14 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/25 11:43 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker.route + +import org.w3c.fetch.Request +import org.w3c.fetch.Response + +public typealias Handler = suspend (Request) -> Response \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteUtil.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteUtil.kt new file mode 100644 index 0000000..4b8071c --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/RouteUtil.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/25 10:49 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +@file:Suppress("unused") + +package cn.rtast.cfworker.route + +import cn.rtast.cfworker.HttpMethod +import cn.rtast.cfworker.WorkerApplication +import cn.rtast.cfworker.auth.credentials.HttpCredential +import cn.rtast.cfworker.auth.provider.Authenticator +import cn.rtast.cfworker.route.type.RegexRoute +import cn.rtast.cfworker.route.type.RouteType +import cn.rtast.cfworker.route.type.StringRoute + +public fun WorkerApplication.route( + path: Regex, + methods: Set = HttpMethod.entries.toSet(), + block: Handler, +): Unit = run { routes.add(RegexRoute(path, block, methods)) } + +public fun WorkerApplication.route( + path: String, + methods: Set = HttpMethod.entries.toSet(), + block: Handler, +): Unit = run { routes.add(StringRoute(path, block, methods)) } + +public fun WorkerApplication.route( + path: String, + methods: Set = HttpMethod.entries.toSet(), + authenticator: Authenticator, + block: Handler, +): Unit = run { routes.add(StringRoute(path, block, methods, type = RouteType.String, authenticator = authenticator)) } + +public fun WorkerApplication.route( + path: Regex, + methods: Set = HttpMethod.entries.toSet(), + authenticator: Authenticator, + block: Handler, +): Unit = run { routes.add(RegexRoute(path, block, methods, type = RouteType.Regex, authenticator = authenticator)) } \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/type/AbstractRoute.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/AbstractRoute.kt new file mode 100644 index 0000000..f32065c --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/AbstractRoute.kt @@ -0,0 +1,45 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:04 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker.route.type + +import cn.rtast.cfworker.HttpMethod +import cn.rtast.cfworker.auth.credentials.HttpCredential +import cn.rtast.cfworker.auth.provider.Authenticator +import cn.rtast.cfworker.route.Handler +import org.w3c.fetch.Request +import org.w3c.fetch.Response + + +internal interface AbstractRoute { + /** + * Route type + */ + val type: RouteType + + /** + * Route code handle block + */ + val block: Handler + + /** + * Allowed http methods + */ + val methods: Set + + /** + * Endpoint authenticator, if null, no auth required + */ + val authenticator: Authenticator? + + /** + * A route handler to process incoming http request + * @see Handler + */ + suspend fun handle(request: Request): Response = block.invoke(request) +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RegexRoute.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RegexRoute.kt new file mode 100644 index 0000000..4c91fc2 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RegexRoute.kt @@ -0,0 +1,22 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:04 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker.route.type + +import cn.rtast.cfworker.HttpMethod +import cn.rtast.cfworker.auth.credentials.HttpCredential +import cn.rtast.cfworker.auth.provider.Authenticator +import cn.rtast.cfworker.route.Handler + +internal data class RegexRoute( + val path: Regex, + override val block: Handler, + override val methods: Set, + override val type: RouteType = RouteType.Regex, + override val authenticator: Authenticator? = null, +) : AbstractRoute \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RouteType.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RouteType.kt new file mode 100644 index 0000000..1c7ed20 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/RouteType.kt @@ -0,0 +1,12 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:05 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + +package cn.rtast.cfworker.route.type + +internal enum class RouteType { + Regex, String +} \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/route/type/StringRoute.kt b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/StringRoute.kt new file mode 100644 index 0000000..fc49d8e --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/route/type/StringRoute.kt @@ -0,0 +1,22 @@ +/* + * Copyright © 2025 RTAkland + * Date: 2025/12/28 01:04 + * Open Source Under Apache-2.0 License + * https://www.apache.org/licenses/LICENSE-2.0 + */ + + +package cn.rtast.cfworker.route.type + +import cn.rtast.cfworker.HttpMethod +import cn.rtast.cfworker.auth.credentials.HttpCredential +import cn.rtast.cfworker.auth.provider.Authenticator +import cn.rtast.cfworker.route.Handler + +internal data class StringRoute( + val path: String, + override val block: Handler, + override val methods: Set, + override val type: RouteType = RouteType.String, + override val authenticator: Authenticator? = null, +) : AbstractRoute \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/util/Base64.kt b/src/jsMain/kotlin/cn/rtast/cfworker/util/Base64.kt new file mode 100644 index 0000000..4236d94 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/util/Base64.kt @@ -0,0 +1,13 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.util + +import kotlin.io.encoding.Base64 + +internal val String.decodeBase64String: String + get() = Base64.decode(this.encodeToByteArray()).decodeToString() \ No newline at end of file diff --git a/src/jsMain/kotlin/cn/rtast/cfworker/util/ByteArray.kt b/src/jsMain/kotlin/cn/rtast/cfworker/util/ByteArray.kt new file mode 100644 index 0000000..e1f0322 --- /dev/null +++ b/src/jsMain/kotlin/cn/rtast/cfworker/util/ByteArray.kt @@ -0,0 +1,23 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package cn.rtast.cfworker.util + +import org.khronos.webgl.ArrayBuffer +import org.khronos.webgl.Int8Array + +/** + * Convert [ArrayBuffer] to [ByteArray] + */ +public fun ArrayBuffer.toByteArray(): ByteArray = + Int8Array(this).unsafeCast() + +/** + * Convert [ByteArray] to [ArrayBuffer] + */ +public fun ByteArray.toArrayBuffer(): ArrayBuffer = + Int8Array(this.toTypedArray()).unsafeCast() \ No newline at end of file diff --git a/src/jsTest/kotlin/test/Test.kt b/src/jsTest/kotlin/test/Test.kt new file mode 100644 index 0000000..b029617 --- /dev/null +++ b/src/jsTest/kotlin/test/Test.kt @@ -0,0 +1,11 @@ +/* + * Copyright © 2026 RTAkland + * Author: RTAkland + * Date: 2026/1/3 + */ + + +package test + +class Test { +} \ No newline at end of file