Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,21 @@ jobs:
permissions:
contents: read
packages: write
# The actions are pinned to commits, not to tags like @v3: this job may write to the registry
# every instance deploys from, and a tag can be moved to other code. To update an action, take
# the commit of its newer release (shown on its releases page) and adjust the comment.
steps:
- uses: actions/checkout@v5
- uses: docker/setup-buildx-action@v3
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
# The run's own GitHub token may push to the repository's packages: no secret to set up.
- uses: docker/login-action@v3
- uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Same build as the "Build Docker image" job; its cached layers make this quick. Tagged
# "latest" (what fly.toml deploys) and with the commit (to deploy or go back to a fixed version).
- uses: docker/build-push-action@v6
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
with:
context: .
push: true
Expand Down
5 changes: 5 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ it unless `.dockerignore` excludes them).
(`Failure` by its `ApiError`, `NetworkError`); the client never throws except on cancellation.
- Keep business logic (code allocation, validation) out of Ktor routes and Compose UI, in plain
classes that can be unit tested (server: package `server.domain`; routes only map HTTP to it).
- Server database access goes through `db.query { }` (`server/.../db/Query.kt`): a transaction on `Dispatchers.IO`,
so blocking JDBC never runs on a request thread. Repository functions are therefore `suspend`; tests call them in
`runBlocking`.
- Inject `kotlin.time.Clock` wherever "now" matters, so tests can control time.
- Never install Ktor's `CallLogging` or log request paths: they contain invite tokens. The
`Exposed` logger is off because it logs statement values (codes). Don't log exception messages of
Expand All @@ -144,6 +147,8 @@ it unless `.dockerignore` excludes them).
including a concurrency test for rule 1.
- Use `kotlinx-datetime` / `kotlin.time.Instant` for timestamps and store them in UTC.
- Add dependencies through `gradle/libs.versions.toml`, not as inline version strings.
- In CI jobs that can publish or deploy (write permissions, secrets), pin actions to a commit with the version in a
comment (`uses: owner/action@<sha> # v1.2.3`), not to a tag or branch.
- Follow the official Kotlin code style (`kotlin.code.style=official`).
- Keep commits small and focused, with descriptive messages.

Expand Down
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ AVAILABLE ──(user requests code)──────▶ CONSUMED
| Build JDK | Java 21, any vendor (Gradle daemon criteria). Not pinned to Azul so cloud AI sessions can use the preinstalled OpenJDK. |
| API models | Separate KMP module `api` (jvm, js, wasmJs), only kotlinx.serialization. The server doesn't pull in Compose. |
| Admin login | `POST /api/admin/login` with username and password. On success the server creates a session (kept in memory, 12 hours) and sets a random session id as an `HttpOnly`, `SameSite=Strict` cookie (also `Secure` unless `COOKIE_SECURE=false`). Logout ends the session. A server restart logs the admin out. |
| Database access | [Exposed](https://www.jetbrains.com/exposed/) DSL on the SQLite JDBC driver. Migrations are plain SQL versioned with `PRAGMA user_version` (no extra migration library). Timestamps are stored as UTC epoch milliseconds. |
| Database access | [Exposed](https://www.jetbrains.com/exposed/) DSL on the SQLite JDBC driver. Migrations are plain SQL versioned with `PRAGMA user_version` (no extra migration library). Timestamps are stored as UTC epoch milliseconds. The repositories' functions are `suspend` and run their transaction on `Dispatchers.IO` (`db.query { }`): JDBC blocks, and the server has only one or two request threads on a small machine, which also answer the health check. |
| Request bodies | Capped at 64 KB, 2 MB for a batch upload (the largest valid upload is about 1.3 MB), with Ktor's `RequestBodyLimit`. Bodies are read into memory, and login is open to anyone, so without a cap one huge request could exhaust the heap. |
| Atomic hand-out | One SQL statement: `UPDATE promo_code SET consumed_at = ? WHERE consumed_at IS NULL AND id = (SELECT … LIMIT 1) RETURNING code`. Transactions use `BEGIN IMMEDIATE` and a busy timeout, so concurrent writers queue up instead of failing. |
| Expiry | A batch's `expiresAt` is an exact instant (UTC). From that instant on, its remaining codes count as expired. In the admin UI the admin picks a day; the codes are valid until the end of that day (23:59:59) in the admin's browser time zone. |
| API client | `ApiClient` in `shared` (package `client`), on the Ktor client with the browser's `fetch` for JS and Wasm. Every call returns an `ApiResult` (`Success`, `Failure` with status and `ApiError`, `NetworkError`) instead of throwing, so the UI has to handle each case. JSON is parsed leniently (`ignoreUnknownKeys`, `coerceInputValues`), so an older web app keeps working against a newer server. Path segments are encoded including `/`, so an invite token can't change the request path. `webApp/main.kt` creates one client for the page's lifetime and passes it to `App`; it is never closed. On the `jvm` target (previews, tests) there is no default engine, so one must be passed. |
Expand Down Expand Up @@ -153,6 +154,9 @@ proxy), so the web app treats it as a network error: "The server can't be reache
whole truth: a `504` can come after the server handed out the code. The invite page then says the server didn't answer
and that a code may have been handed out without reaching the user (it is lost; the user can request another one).

A request body that can't be read gets `invalid_request` with `400` (malformed JSON), `415` (missing, or not
`application/json`) or `413` (larger than 64 KB, 2 MB for a batch upload).

User endpoints (scoped by the invite token; an unknown token, an unknown batch and a batch of another
app all give the same `404`):

Expand Down Expand Up @@ -501,6 +505,10 @@ every pull request and every push to `main`:
`...:<commit>`. The run's own GitHub token may do that, so there is no secret to set up. Forks don't publish.
CI never deploys: Fly.io instances fetch the image with `fly deploy` (see [Deploying to Fly.io](#deploying-to-flyio)).

The publish job's actions are pinned to commits (`docker/login-action@<commit> # v3.7.0`), not to tags like `@v3`:
it may write to the registry every instance deploys from, and a tag can be moved to other code. To update one, take
the commit of a newer release from the action's releases page. The other jobs can't publish anything and use tags.

The workflow also has a *Run workflow* button (Actions tab, `workflow_dispatch`): it runs the same jobs for a branch
without a new commit, and publishes when run on `main`.

Expand Down Expand Up @@ -537,6 +545,14 @@ Each step is one GitHub issue, one AI conversation and one pull request (see [CL
`RUN find /app/web -name '*.map' -delete` in the runtime stage would drop them, e.g. if the repository becomes private.
- **Suggestion**: rate-limit `POST /api/admin/login` (Ktor `RateLimit` plugin) against password guessing, keyed by Fly.io's `Fly-Client-IP` (`X-Forwarded-For` can be faked).
The invite endpoints could be rate-limited too.
- **Open from the code review after step #7** (fixed there: unreadable bodies answered `500`, blocking database
calls on request threads, no body size limit, unpinned actions in the publish job):
- Logging out while a page request answers `401` keeps the page's state (e.g. pasted codes) for the next login,
because the session then counts as expired instead of logged out.
- Code parsing trims whitespace only. A byte order mark or zero-width space from a CSV or spreadsheet stays in the
code, which then doesn't redeem and doesn't match the same code without it as a duplicate.
- The app page computes its statistics twice per load (`GET /apps/{id}` and `GET /apps/{id}/batches`).
- Every transaction opens a new SQLite connection; a small connection pool would reuse them.
- **Accepted for now** (decided after step #5, no action planned):
- Received codes are lost when the user reloads or closes the invite page (the page says so). Keeping them in
the browser's `localStorage` per invite token would make that safer.
Expand Down
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ ktor-server-auth = { module = "io.ktor:ktor-server-auth", version.ref = "ktor" }
ktor-server-compression = { module = "io.ktor:ktor-server-compression", version.ref = "ktor" }
ktor-server-conditionalHeaders = { module = "io.ktor:ktor-server-conditional-headers", version.ref = "ktor" }
ktor-server-forwardedHeader = { module = "io.ktor:ktor-server-forwarded-header", version.ref = "ktor" }
ktor-server-bodyLimit = { module = "io.ktor:ktor-server-body-limit", version.ref = "ktor" }
ktor-server-testHost = { module = "io.ktor:ktor-server-test-host", version.ref = "ktor" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
Expand Down
1 change: 1 addition & 0 deletions server/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ dependencies {
implementation(libs.ktor.server.compression)
implementation(libs.ktor.server.conditionalHeaders)
implementation(libs.ktor.server.forwardedHeader)
implementation(libs.ktor.server.bodyLimit)
implementation(libs.ktor.serialization.kotlinxJson)
implementation(libs.exposed.core)
implementation(libs.exposed.jdbc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import at.techbee.gplaypromocodeprovider.server.domain.AppRepository
import at.techbee.gplaypromocodeprovider.server.domain.BatchRepository
import at.techbee.gplaypromocodeprovider.server.domain.CodeAllocator
import at.techbee.gplaypromocodeprovider.server.domain.ValidationException
import at.techbee.gplaypromocodeprovider.server.routes.MAX_UPLOAD_BODY_BYTES
import at.techbee.gplaypromocodeprovider.server.routes.adminRoutes
import at.techbee.gplaypromocodeprovider.server.routes.installAdminAuth
import at.techbee.gplaypromocodeprovider.server.routes.respondNotFound
Expand All @@ -16,6 +17,11 @@ import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.BadRequestException
import io.ktor.server.plugins.CannotTransformContentToTypeException
import io.ktor.server.plugins.ContentTransformationException
import io.ktor.server.plugins.PayloadTooLargeException
import io.ktor.server.plugins.UnsupportedMediaTypeException
import io.ktor.server.plugins.bodylimit.RequestBodyLimit
import io.ktor.server.plugins.compression.Compression
import io.ktor.server.plugins.compression.condition
import io.ktor.server.plugins.compression.gzip
Expand All @@ -35,6 +41,9 @@ import java.io.File
import java.sql.SQLException
import kotlin.time.Clock

/** Largest request body accepted, except for batch uploads ([MAX_UPLOAD_BODY_BYTES]). */
const val MAX_REQUEST_BODY_BYTES = 64L * 1024

private val log = LoggerFactory.getLogger("at.techbee.gplaypromocodeprovider.server")

/**
Expand Down Expand Up @@ -69,6 +78,20 @@ fun Application.module(config: ServerConfig, db: Database, clock: Clock = Clock.
exception<BadRequestException> { call, _ ->
call.respond(HttpStatusCode.BadRequest, ErrorResponse(ApiError.INVALID_REQUEST, "Malformed request"))
}
// The body couldn't be read: missing, not JSON, or too large. These aren't BadRequestExceptions;
// without their own handlers they'd end up below as 500 with an error log.
exception<CannotTransformContentToTypeException> { call, _ ->
call.respond(HttpStatusCode.UnsupportedMediaType, ErrorResponse(ApiError.INVALID_REQUEST, "Expected a JSON body"))
}
exception<UnsupportedMediaTypeException> { call, _ ->
call.respond(HttpStatusCode.UnsupportedMediaType, ErrorResponse(ApiError.INVALID_REQUEST, "Expected a JSON body"))
}
exception<PayloadTooLargeException> { call, _ ->
call.respond(HttpStatusCode.PayloadTooLarge, ErrorResponse(ApiError.INVALID_REQUEST, "The request is too large"))
}
exception<ContentTransformationException> { call, _ ->
call.respond(HttpStatusCode.BadRequest, ErrorResponse(ApiError.INVALID_REQUEST, "Malformed request"))
}
exception<Throwable> { call, cause ->
if (cause is SQLException) {
// No message: it can contain the SQL statement including promo codes.
Expand All @@ -82,6 +105,10 @@ fun Application.module(config: ServerConfig, db: Database, clock: Clock = Clock.
installAdminAuth(config, clock)

routing {
// Request bodies are read into memory, so their size is capped, also before anyone has logged
// in, and a huge body can't exhaust the heap. The batch upload allows more (see adminRoutes).
// Installed here, not on the application: Ktor only lets a route override a routing-level install.
install(RequestBodyLimit) { bodyLimit { MAX_REQUEST_BODY_BYTES } }
route("/api") {
// Used by Fly.io's health check: the server is up and answers requests.
get("/health") { call.respondText("ok") }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package at.techbee.gplaypromocodeprovider.server.db

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.JdbcTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.transaction

/**
* Runs [statement] in a transaction on [Dispatchers.IO]. JDBC blocks, possibly for seconds (a large
* upload, or waiting for SQLite's write lock), and must not hold up the server's request threads:
* a small machine has only one or two, which also answer the health check and serve the web app.
* Use this for every database access from request handling.
*/
suspend fun <T> Database.query(statement: JdbcTransaction.() -> T): T =
withContext(Dispatchers.IO) { transaction(db = this@query, statement = statement) }
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package at.techbee.gplaypromocodeprovider.server.domain

import at.techbee.gplaypromocodeprovider.server.db.Apps
import at.techbee.gplaypromocodeprovider.server.db.query
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import org.jetbrains.exposed.v1.jdbc.update
import kotlin.time.Clock

class AppRepository(private val db: Database, private val clock: Clock = Clock.System) {

fun create(input: AppInput): App = transaction(db) {
suspend fun create(input: AppInput): App = db.query {
val token = InviteTokens.generate()
val id = Apps.insert {
it[name] = input.name
Expand All @@ -25,33 +25,34 @@ class AppRepository(private val db: Database, private val clock: Clock = Clock.S
}

/** Returns the updated app, or null if there is no app with this id. */
fun update(id: Long, input: AppInput): App? = transaction(db) {
suspend fun update(id: Long, input: AppInput): App? = db.query {
val updated = Apps.update({ Apps.id eq id }) {
it[name] = input.name
it[packageName] = input.packageName
it[description] = input.description
}
if (updated == 0) null else find(id)
if (updated == 0) null else findById(id)
}

/** Replaces the invite token, which revokes the old invite link. Null if there is no such app. */
fun regenerateInviteToken(id: Long): App? = transaction(db) {
suspend fun regenerateInviteToken(id: Long): App? = db.query {
val updated = Apps.update({ Apps.id eq id }) { it[inviteToken] = InviteTokens.generate() }
if (updated == 0) null else find(id)
if (updated == 0) null else findById(id)
}

fun find(id: Long): App? = transaction(db) {
Apps.selectAll().where { Apps.id eq id }.singleOrNull()?.toApp()
}
suspend fun find(id: Long): App? = db.query { findById(id) }

fun findByInviteToken(token: String): App? = transaction(db) {
suspend fun findByInviteToken(token: String): App? = db.query {
Apps.selectAll().where { Apps.inviteToken eq token }.singleOrNull()?.toApp()
}

fun list(): List<App> = transaction(db) {
suspend fun list(): List<App> = db.query {
Apps.selectAll().orderBy(Apps.name).map { it.toApp() }
}

/** Within a transaction. */
private fun findById(id: Long): App? = Apps.selectAll().where { Apps.id eq id }.singleOrNull()?.toApp()

private fun ResultRow.toApp() = App(
id = this[Apps.id],
name = this[Apps.name],
Expand Down
Loading
Loading