commit d8a606ce46e7a374ef02f5017f52770bcc6007d5 Author: michal Date: Mon Sep 28 23:17:25 2026 +0100 internaluploader: server + docs One-way upload server: authentik SSO pairing (QR + app-initiated deep link), hashed device tokens, streamed sha256-verified uploads into the metube directory as .. Co-Authored-By: Claude Fable 5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dc25bbc --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +thelab-kubernetes-pulumi/ +node_modules/ +dist/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff58647 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# internaluploader + +One-way file drop: an Android app that uploads files into the metube download +directory on nas001 (`/volume1/ss/data`). There is no way to browse, list or +download anything through it — uploads only. + +Every file is stored as `.`, so names +carry nothing, re-uploads are idempotent, and a retried upload can be verified +server-side before it is accepted. + +## Parts + +- `server/` — Node 22 / TypeScript. Runs as a docker container **on nas001** + (Pulumi docker-over-ssh, same pattern as seaweedfs), bind-mounting + `/volume1/ss/data` at `/downloads`. Fronted by the cluster's Cilium ingress + at `https://puploader.ad.itaz.eu` (cert-manager LE cert) and exposed to the + tailnet as its own Tailscale device `puploader` (userspace proxy, SNI + passthrough) — reachable from anywhere on the tailnet, nothing public. +- `android/` — Kotlin app "InternalUploader". No settings screen, no server + address anywhere in the UI. The server URL is baked into the build and can + be replaced by whatever a pairing QR carries. + +## Auth model + +Browser SSO (authentik at `sso.ad.itaz.eu`) is the only identity check; the +app itself never sees a password. + +1. **QR pairing** — open `https://puploader.ad.itaz.eu` in a browser, sign in + through authentik, and the page shows a QR code. Scan it with the app and + the device is paired. The QR carries a single-use pairing code (5 min TTL) + plus the server URL. +2. **In-app SSO (optional path)** — the app opens + `https://puploader.ad.itaz.eu/pair/app` in a Custom Tab; after the same + authentik login the server redirects to `internaluploader://pair?c=` + and the app finishes pairing with the same exchange. + +Pairing exchanges the one-time code for a long-lived **device token** (256-bit +random, stored hashed on the server, `Authorization: Bearer` on every upload). + +## API (server ⇄ app contract) + +QR / deep-link payload (JSON): `{"v":1,"u":"https://puploader.ad.itaz.eu","c":""}` + +| Endpoint | Auth | Behaviour | +|---|---|---| +| `GET /healthz` | none | 200 `ok` | +| `GET /` | browser SSO | pairing page with QR | +| `GET /pair/app` | browser SSO | 302 → `internaluploader://pair?c=` | +| `POST /api/pair` `{"code":"…"}` | pairing code | 200 `{"token":"…","name":""}`; 410 expired/used | +| `HEAD /api/object/.` | bearer | 204 exists / 404 not — lets a retry skip the bytes | +| `PUT /api/upload?name=.` | bearer | body = raw bytes, streamed to a temp file **on the same filesystem**, hash verified, then renamed into `/downloads`. 201 created, 200 already existed, 409 hash mismatch, 413 too large | + +One-way by construction: the only read endpoint takes a full content hash the +caller must already possess. + +## Building + +- Server image: `server/build.sh` (podman build + push to + `mysources.co.uk/michal/internaluploader-server:-`). +- APK: `cd android && JAVA_HOME=/usr/lib/jvm/java-21-openjdk ./gradlew assembleRelease` + (release signing reads `~/.internaluploader/signing.properties`; see + `android/README.md`). Publish to the private F-Droid repo with + `thelab-kubernetes-pulumi/scripts/fdroid/publish.py add `. + +## Deployment + +Declared in `thelab-kubernetes-pulumi` — `deployments/puploader/` plus an +authentik OIDC app (`deployments/authentik/apps/puploader.ts`), a +`k8s-deployments:puploader` config block, and a `puploader` entry in the +worker0 tailscale exposures (two-step: first apply registers the device, then +set `deviceIp` for the Cloudflare A record). diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..3e2dbb4 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +build/ +local.properties +*.keystore +*.p12 +.kotlin/ diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..94ec884 --- /dev/null +++ b/android/README.md @@ -0,0 +1,52 @@ +# InternalUploader — Android app + +Native Kotlin app. Pair once (QR from the browser pairing page, or in-app SSO +via a Custom Tab), then share anything to it — files upload in the background +as `.` and failed uploads retry until they land. No settings +screen; the server address is baked in (`BuildConfig.DEFAULT_SERVER_URL`) and +can be replaced only by what a pairing QR carries. + +## Building + +```sh +JAVA_HOME=~/.jdks/jdk17 ./gradlew assembleRelease +``` + +- Needs an Android SDK at the path in `local.properties` (not committed; + `sdk.dir=$HOME/Android/Sdk`), platform android-36. +- Gradle 8.14.3 (wrapper), AGP 8.11.1, Kotlin 2.1.21. The Gradle daemon needs + JDK 17–24 — the system `java` (25) is too new, hence the explicit + `JAVA_HOME`. +- Output: `app/build/outputs/apk/release/app-release.apk`. + +## Release signing + +`app/build.gradle.kts` reads `~/.internaluploader/signing.properties`: + +```properties +storeFile=/home//.internaluploader/release.p12 +storePassword=… +keyAlias=internaluploader +keyPassword=… +``` + +The PKCS12 keystore was generated with: + +```sh +keytool -genkeypair -keystore ~/.internaluploader/release.p12 -storetype PKCS12 \ + -alias internaluploader -keyalg RSA -keysize 4096 -validity 10000 +``` + +The keystore never enters the repo. If `signing.properties` is missing, the +release build is unsigned (fine for compile checks, not for F-Droid). Keep the +keystore backed up: F-Droid clients pin the app signature, so a lost key means +uninstall/reinstall on every device. + +## Publishing to the private F-Droid repo + +```sh +thelab-kubernetes-pulumi/scripts/fdroid/publish.py add app/build/outputs/apk/release/app-release.apk +``` + +Bump `versionCode`/`versionName` in `app/build.gradle.kts` for every published +build — F-Droid only offers updates on a higher `versionCode`. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..c013234 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,87 @@ +import java.util.Properties + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("com.google.devtools.ksp") +} + +// Release signing is read from ~/.internaluploader/signing.properties so the +// keystore never enters the repo. Absent that file, release builds are simply +// unsigned (still useful for CI compile checks). +val signingProps = Properties().apply { + val f = file("${System.getProperty("user.home")}/.internaluploader/signing.properties") + if (f.exists()) f.inputStream().use { load(it) } +} + +android { + namespace = "eu.itaz.internaluploader" + compileSdk = 36 + + defaultConfig { + applicationId = "eu.itaz.internaluploader" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "1.0.0" + + // The one place the server address exists. Never rendered in the UI; + // a pairing QR can carry a different origin and overrides this. + buildConfigField("String", "DEFAULT_SERVER_URL", "\"https://puploader.ad.itaz.eu\"") + } + + signingConfigs { + if (signingProps.getProperty("storeFile") != null) { + create("release") { + storeFile = file(signingProps.getProperty("storeFile")) + storePassword = signingProps.getProperty("storePassword") + keyAlias = signingProps.getProperty("keyAlias") + keyPassword = signingProps.getProperty("keyPassword") + } + } + } + + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + signingConfig = signingConfigs.findByName("release") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = "17" + } + + buildFeatures { + viewBinding = true + buildConfig = true + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.16.0") + implementation("androidx.appcompat:appcompat:1.7.1") + implementation("com.google.android.material:material:1.12.0") + implementation("androidx.constraintlayout:constraintlayout:2.2.1") + implementation("androidx.recyclerview:recyclerview:1.4.0") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.1") + implementation("androidx.browser:browser:1.8.0") + implementation("androidx.security:security-crypto:1.1.0-alpha06") + + implementation("androidx.work:work-runtime-ktx:2.10.1") + + implementation("androidx.room:room-runtime:2.7.1") + implementation("androidx.room:room-ktx:2.7.1") + ksp("androidx.room:room-compiler:2.7.1") + + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.journeyapps:zxing-android-embedded:4.3.0") + + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..9f5b71f --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,4 @@ +# zxing-android-embedded reflects into CaptureActivity subclasses; keep the +# whole client package rather than chasing individual members. +-keep class com.journeyapps.barcodescanner.** { *; } +-keep class com.google.zxing.** { *; } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..512da86 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/eu/itaz/internaluploader/App.kt b/android/app/src/main/java/eu/itaz/internaluploader/App.kt new file mode 100644 index 0000000..3b82d03 --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/App.kt @@ -0,0 +1,24 @@ +package eu.itaz.internaluploader + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager + +class App : Application() { + + override fun onCreate() { + super.onCreate() + val manager = getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_UPLOADS, + getString(R.string.channel_uploads), + NotificationManager.IMPORTANCE_LOW, + ), + ) + } + + companion object { + const val CHANNEL_UPLOADS = "uploads" + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/MainActivity.kt b/android/app/src/main/java/eu/itaz/internaluploader/MainActivity.kt new file mode 100644 index 0000000..3689134 --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/MainActivity.kt @@ -0,0 +1,214 @@ +package eu.itaz.internaluploader + +import android.Manifest +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.view.Menu +import android.view.MenuItem +import android.view.View +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.browser.customtabs.CustomTabsIntent +import androidx.core.net.toUri +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.LinearLayoutManager +import com.journeyapps.barcodescanner.ScanContract +import com.journeyapps.barcodescanner.ScanOptions +import eu.itaz.internaluploader.data.AppDb +import eu.itaz.internaluploader.data.Status +import eu.itaz.internaluploader.databinding.ActivityMainBinding +import eu.itaz.internaluploader.pairing.PairApi +import eu.itaz.internaluploader.pairing.PairPayload +import eu.itaz.internaluploader.pairing.PairingStore +import eu.itaz.internaluploader.ui.QueueAdapter +import eu.itaz.internaluploader.upload.Enqueuer +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch + +class MainActivity : AppCompatActivity() { + + private lateinit var binding: ActivityMainBinding + private lateinit var store: PairingStore + private val adapter = QueueAdapter() + + private val scanQr = registerForActivityResult(ScanContract()) { result -> + val payload = result.contents?.let(PairPayload.Companion::fromQr) + if (payload == null) { + if (result.contents != null) toast(R.string.pair_qr_invalid) + } else { + completePairing(payload) + } + } + + private val pickFiles = + registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + uris.forEach(::enqueueUri) + } + + private val askNotifications = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + setSupportActionBar(binding.toolbar) + store = PairingStore(this) + + binding.queue.layoutManager = LinearLayoutManager(this) + binding.queue.adapter = adapter + + binding.scanButton.setOnClickListener { startScan() } + binding.ssoButton.setOnClickListener { startAppSso() } + binding.addButton.setOnClickListener { pickFiles.launch(arrayOf("*/*")) } + binding.retryButton.setOnClickListener { + lifecycleScope.launch { Enqueuer.retryFailed(this@MainActivity) } + } + + lifecycleScope.launch { + AppDb.get(this@MainActivity).uploads().observeAll().collectLatest { items -> + adapter.submitList(items) + binding.empty.visibility = + if (items.isEmpty() && store.current() != null) View.VISIBLE else View.GONE + binding.retryButton.visibility = + if (items.any { it.status == Status.FAILED }) View.VISIBLE else View.GONE + } + } + + if (Build.VERSION.SDK_INT >= 33) { + askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS) + } + + render() + handleIntent(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + handleIntent(intent) + } + + private fun handleIntent(intent: Intent) { + when (intent.action) { + Intent.ACTION_VIEW -> { + val code = intent.data?.getQueryParameter("c") + if (code != null) completePairing(PairPayload.fromDeepLinkCode(code)) + } + Intent.ACTION_SEND -> { + sharedUri(intent)?.let(::enqueueUri) + } + Intent.ACTION_SEND_MULTIPLE -> { + sharedUris(intent).forEach(::enqueueUri) + } + } + // A share intent is consumed once; re-delivery on rotation would + // double-queue (dedupe by hash makes that harmless server-side, but + // the queue UI would still show it twice). + intent.action = null + } + + @Suppress("DEPRECATION") + private fun sharedUri(intent: Intent): Uri? = + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + intent.getParcelableExtra(Intent.EXTRA_STREAM) + } + + @Suppress("DEPRECATION") + private fun sharedUris(intent: Intent): List = + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) ?: emptyList() + } else { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) ?: emptyList() + } + + private fun enqueueUri(uri: Uri) { + if (store.current() == null) { + toast(R.string.pair_first) + return + } + lifecycleScope.launch { + try { + Enqueuer.enqueue(this@MainActivity, uri) + } catch (e: Exception) { + Toast.makeText( + this@MainActivity, + getString(R.string.enqueue_failed, e.message ?: ""), + Toast.LENGTH_LONG, + ).show() + } + } + } + + private fun startScan() { + scanQr.launch( + ScanOptions() + .setDesiredBarcodeFormats(ScanOptions.QR_CODE) + .setPrompt(getString(R.string.pair_scan_prompt)) + .setBeepEnabled(false) + .setOrientationLocked(false), + ) + } + + private fun startAppSso() { + CustomTabsIntent.Builder().build() + .launchUrl(this, "${BuildConfig.DEFAULT_SERVER_URL}/pair/app".toUri()) + } + + private fun completePairing(payload: PairPayload) { + lifecycleScope.launch { + try { + store.save(PairApi.pair(payload)) + toast(R.string.pair_success) + } catch (e: Exception) { + Toast.makeText( + this@MainActivity, + getString(R.string.pair_failed, e.message ?: ""), + Toast.LENGTH_LONG, + ).show() + } + render() + } + } + + private fun render() { + val paired = store.current() + binding.pairGroup.visibility = if (paired == null) View.VISIBLE else View.GONE + binding.uploadGroup.visibility = if (paired == null) View.GONE else View.VISIBLE + binding.pairedAs.text = + if (paired == null) "" else getString(R.string.paired_as, paired.name) + invalidateOptionsMenu() + } + + override fun onCreateOptionsMenu(menu: Menu): Boolean { + menuInflater.inflate(R.menu.main_menu, menu) + val paired = store.current() != null + menu.findItem(R.id.action_unpair).isVisible = paired + menu.findItem(R.id.action_clear_finished).isVisible = paired + return true + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean = + when (item.itemId) { + R.id.action_unpair -> { + store.clear() + render() + true + } + R.id.action_clear_finished -> { + lifecycleScope.launch { + AppDb.get(this@MainActivity).uploads().deleteByStatus(Status.DONE) + } + true + } + else -> super.onOptionsItemSelected(item) + } + + private fun toast(resId: Int) { + Toast.makeText(this, resId, Toast.LENGTH_SHORT).show() + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/data/Db.kt b/android/app/src/main/java/eu/itaz/internaluploader/data/Db.kt new file mode 100644 index 0000000..5a07362 --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/data/Db.kt @@ -0,0 +1,75 @@ +package eu.itaz.internaluploader.data + +import android.content.Context +import androidx.room.Dao +import androidx.room.Database +import androidx.room.Entity +import androidx.room.Insert +import androidx.room.PrimaryKey +import androidx.room.Query +import androidx.room.Room +import androidx.room.RoomDatabase +import kotlinx.coroutines.flow.Flow + +object Status { + const val PENDING = "pending" + const val UPLOADING = "uploading" + const val DONE = "done" + const val FAILED = "failed" +} + +@Entity(tableName = "uploads") +data class UploadItem( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + /** What the user shared — display only; never sent to the server. */ + val originalName: String, + /** `.` — the only name the server ever sees. */ + val remoteName: String, + /** Private copy the worker uploads from; survives source URI revocation. */ + val cachePath: String, + val size: Long, + val status: String = Status.PENDING, + val progress: Int = 0, + val error: String? = null, + val createdAt: Long = System.currentTimeMillis(), +) + +@Dao +interface UploadDao { + @Insert + suspend fun insert(item: UploadItem): Long + + @Query("SELECT * FROM uploads ORDER BY createdAt DESC") + fun observeAll(): Flow> + + @Query("SELECT * FROM uploads WHERE id = :id") + suspend fun byId(id: Long): UploadItem? + + @Query("SELECT * FROM uploads WHERE status = :status") + suspend fun byStatus(status: String): List + + @Query("UPDATE uploads SET status = :status, progress = :progress, error = :error WHERE id = :id") + suspend fun setStatus(id: Long, status: String, progress: Int = 0, error: String? = null) + + @Query("DELETE FROM uploads WHERE status = :status") + suspend fun deleteByStatus(status: String) +} + +@Database(entities = [UploadItem::class], version = 1, exportSchema = false) +abstract class AppDb : RoomDatabase() { + abstract fun uploads(): UploadDao + + companion object { + @Volatile + private var instance: AppDb? = null + + fun get(context: Context): AppDb = + instance ?: synchronized(this) { + instance ?: Room.databaseBuilder( + context.applicationContext, + AppDb::class.java, + "internaluploader.db", + ).build().also { instance = it } + } + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/pairing/Pairing.kt b/android/app/src/main/java/eu/itaz/internaluploader/pairing/Pairing.kt new file mode 100644 index 0000000..dc113ae --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/pairing/Pairing.kt @@ -0,0 +1,119 @@ +package eu.itaz.internaluploader.pairing + +import android.content.Context +import android.content.SharedPreferences +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey +import eu.itaz.internaluploader.BuildConfig +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONObject + +data class PairedState(val serverUrl: String, val token: String, val name: String) + +/** + * Device credential store. The server URL lives here too — it arrives inside + * the pairing QR (or is the baked-in default for the in-app SSO path) and is + * deliberately never surfaced anywhere in the UI. + */ +class PairingStore(context: Context) { + + private val prefs: SharedPreferences + + init { + val masterKey = MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build() + prefs = EncryptedSharedPreferences.create( + context, + "pairing", + masterKey, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM, + ) + } + + fun current(): PairedState? { + val url = prefs.getString(KEY_URL, null) ?: return null + val token = prefs.getString(KEY_TOKEN, null) ?: return null + val name = prefs.getString(KEY_NAME, null) ?: return null + return PairedState(url, token, name) + } + + fun save(state: PairedState) { + prefs.edit() + .putString(KEY_URL, state.serverUrl) + .putString(KEY_TOKEN, state.token) + .putString(KEY_NAME, state.name) + .apply() + } + + fun clear() { + prefs.edit().clear().apply() + } + + private companion object { + const val KEY_URL = "serverUrl" + const val KEY_TOKEN = "token" + const val KEY_NAME = "name" + } +} + +/** QR / deep-link payload: {"v":1,"u":"https://…","c":""}. */ +data class PairPayload(val serverUrl: String, val code: String) { + companion object { + fun fromQr(text: String): PairPayload? = try { + val json = JSONObject(text) + if (json.optInt("v") != 1) null + else { + val url = json.optString("u") + val code = json.optString("c") + if (url.startsWith("https://") && code.isNotEmpty()) { + PairPayload(url.trimEnd('/'), code) + } else null + } + } catch (_: Exception) { + null + } + + /** Deep link carries only the code; the origin is the baked-in default. */ + fun fromDeepLinkCode(code: String): PairPayload = + PairPayload(BuildConfig.DEFAULT_SERVER_URL, code) + } +} + +class PairingException(message: String) : Exception(message) + +object PairApi { + + private val client = OkHttpClient() + private val jsonType = "application/json".toMediaType() + + /** Exchange a one-time pairing code for the long-lived device token. */ + suspend fun pair(payload: PairPayload): PairedState = withContext(Dispatchers.IO) { + val body = JSONObject().put("code", payload.code).toString().toRequestBody(jsonType) + val request = Request.Builder() + .url("${payload.serverUrl}/api/pair") + .post(body) + .build() + client.newCall(request).execute().use { response -> + when { + response.isSuccessful -> { + val json = JSONObject(response.body!!.string()) + PairedState( + serverUrl = payload.serverUrl, + token = json.getString("token"), + name = json.getString("name"), + ) + } + response.code == 410 || response.code == 400 -> + throw PairingException("code expired or already used") + else -> throw PairingException("pairing failed (HTTP ${response.code})") + } + } + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/ui/QueueAdapter.kt b/android/app/src/main/java/eu/itaz/internaluploader/ui/QueueAdapter.kt new file mode 100644 index 0000000..c3caba7 --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/ui/QueueAdapter.kt @@ -0,0 +1,51 @@ +package eu.itaz.internaluploader.ui + +import android.text.format.Formatter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView +import eu.itaz.internaluploader.R +import eu.itaz.internaluploader.data.Status +import eu.itaz.internaluploader.data.UploadItem +import eu.itaz.internaluploader.databinding.ItemUploadBinding + +class QueueAdapter : ListAdapter(Diff) { + + class Holder(val binding: ItemUploadBinding) : RecyclerView.ViewHolder(binding.root) + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder = + Holder(ItemUploadBinding.inflate(LayoutInflater.from(parent.context), parent, false)) + + override fun onBindViewHolder(holder: Holder, position: Int) { + val item = getItem(position) + val context = holder.binding.root.context + holder.binding.name.text = item.originalName + holder.binding.size.text = Formatter.formatShortFileSize(context, item.size) + + holder.binding.progress.visibility = + if (item.status == Status.UPLOADING) View.VISIBLE else View.GONE + holder.binding.progress.isIndeterminate = item.progress == 0 + holder.binding.progress.progress = item.progress + + holder.binding.status.text = when (item.status) { + Status.PENDING -> context.getString(R.string.status_pending) + Status.UPLOADING -> context.getString(R.string.status_uploading, item.progress) + Status.DONE -> context.getString(R.string.status_done) + Status.FAILED -> context.getString( + R.string.status_failed, + item.error ?: context.getString(R.string.status_failed_unknown), + ) + else -> item.status + } + holder.binding.check.visibility = + if (item.status == Status.DONE) View.VISIBLE else View.GONE + } + + private object Diff : DiffUtil.ItemCallback() { + override fun areItemsTheSame(a: UploadItem, b: UploadItem) = a.id == b.id + override fun areContentsTheSame(a: UploadItem, b: UploadItem) = a == b + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/upload/CountingFileRequestBody.kt b/android/app/src/main/java/eu/itaz/internaluploader/upload/CountingFileRequestBody.kt new file mode 100644 index 0000000..6715e6c --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/upload/CountingFileRequestBody.kt @@ -0,0 +1,45 @@ +package eu.itaz.internaluploader.upload + +import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody +import okio.BufferedSink +import okio.source +import java.io.File + +/** + * Streams a file as the request body, reporting bytes-sent roughly once per + * second so progress writes don't outnumber the payload reads. + */ +class CountingFileRequestBody( + private val file: File, + private val onProgress: (bytesSent: Long) -> Unit, +) : RequestBody() { + + override fun contentType(): MediaType = "application/octet-stream".toMediaType() + + override fun contentLength(): Long = file.length() + + override fun writeTo(sink: BufferedSink) { + var sent = 0L + var lastReport = 0L + file.source().use { source -> + while (true) { + val read = source.read(sink.buffer, SEGMENT) + if (read < 0) break + sent += read + sink.emitCompleteSegments() + val now = System.currentTimeMillis() + if (now - lastReport >= 1000) { + lastReport = now + onProgress(sent) + } + } + } + onProgress(sent) + } + + private companion object { + const val SEGMENT = 64L * 1024 + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/upload/Enqueuer.kt b/android/app/src/main/java/eu/itaz/internaluploader/upload/Enqueuer.kt new file mode 100644 index 0000000..86db62c --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/upload/Enqueuer.kt @@ -0,0 +1,111 @@ +package eu.itaz.internaluploader.upload + +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import androidx.work.BackoffPolicy +import androidx.work.Constraints +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.workDataOf +import eu.itaz.internaluploader.data.AppDb +import eu.itaz.internaluploader.data.Status +import eu.itaz.internaluploader.data.UploadItem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.security.MessageDigest +import java.util.UUID +import java.util.concurrent.TimeUnit + +object Enqueuer { + + /** + * Copy the shared content into app-private storage while hashing it, so a + * retry never depends on the source URI still being readable, then hand + * the file to WorkManager. + */ + suspend fun enqueue(context: Context, uri: Uri): UploadItem = withContext(Dispatchers.IO) { + val originalName = displayNameOf(context, uri) ?: "unnamed" + + val queueDir = File(context.filesDir, "queue").apply { mkdirs() } + val cacheFile = File(queueDir, UUID.randomUUID().toString()) + + val digest = MessageDigest.getInstance("SHA-256") + var size = 0L + context.contentResolver.openInputStream(uri).use { input -> + requireNotNull(input) { "source stream is gone" } + cacheFile.outputStream().use { output -> + val buffer = ByteArray(1 shl 16) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + output.write(buffer, 0, read) + size += read + } + } + } + + val hash = digest.digest().joinToString("") { "%02x".format(it) } + val ext = originalName.substringAfterLast('.', "").lowercase() + .takeIf { it.isNotEmpty() && it.length <= 16 && it.all { c -> c.isLetterOrDigit() } } + val remoteName = if (ext != null) "$hash.$ext" else hash + + val db = AppDb.get(context) + val item = UploadItem( + originalName = originalName, + remoteName = remoteName, + cachePath = cacheFile.absolutePath, + size = size, + ) + val id = db.uploads().insert(item) + schedule(context, id) + item.copy(id = id) + } + + /** (Re-)schedule the worker for one queue item. */ + fun schedule(context: Context, itemId: Long) { + val request = OneTimeWorkRequestBuilder() + .setInputData(workDataOf(UploadWorker.KEY_ITEM_ID to itemId)) + .setConstraints( + Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(), + ) + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) + .build() + WorkManager.getInstance(context) + .enqueueUniqueWork("upload-$itemId", ExistingWorkPolicy.KEEP, request) + } + + suspend fun retryFailed(context: Context) { + val db = AppDb.get(context) + for (item in db.uploads().byStatus(Status.FAILED)) { + if (File(item.cachePath).exists()) { + db.uploads().setStatus(item.id, Status.PENDING) + // REPLACE: the previous unique work chain for this id has already + // terminated in failure; KEEP would ignore the new request. + val request = OneTimeWorkRequestBuilder() + .setInputData(workDataOf(UploadWorker.KEY_ITEM_ID to item.id)) + .setConstraints( + Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(), + ) + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) + .build() + WorkManager.getInstance(context) + .enqueueUniqueWork("upload-${item.id}", ExistingWorkPolicy.REPLACE, request) + } + } + } + + private fun displayNameOf(context: Context, uri: Uri): String? { + context.contentResolver.query(uri, null, null, null, null)?.use { cursor -> + val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (index >= 0 && cursor.moveToFirst()) { + return cursor.getString(index) + } + } + return uri.lastPathSegment + } +} diff --git a/android/app/src/main/java/eu/itaz/internaluploader/upload/UploadWorker.kt b/android/app/src/main/java/eu/itaz/internaluploader/upload/UploadWorker.kt new file mode 100644 index 0000000..ee798ca --- /dev/null +++ b/android/app/src/main/java/eu/itaz/internaluploader/upload/UploadWorker.kt @@ -0,0 +1,164 @@ +package eu.itaz.internaluploader.upload + +import android.app.Notification +import android.content.Context +import android.content.pm.ServiceInfo +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.work.CoroutineWorker +import androidx.work.ForegroundInfo +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import eu.itaz.internaluploader.App +import eu.itaz.internaluploader.R +import eu.itaz.internaluploader.data.AppDb +import eu.itaz.internaluploader.data.Status +import eu.itaz.internaluploader.data.UploadItem +import eu.itaz.internaluploader.pairing.PairingStore +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.File +import java.io.IOException +import java.util.concurrent.TimeUnit + +class UploadWorker(context: Context, params: WorkerParameters) : + CoroutineWorker(context, params) { + + private val db = AppDb.get(context) + + override suspend fun doWork(): Result { + val itemId = inputData.getLong(KEY_ITEM_ID, -1) + val item = db.uploads().byId(itemId) ?: return Result.failure() + if (item.status == Status.DONE) return Result.success() + + val paired = PairingStore(applicationContext).current() + ?: return permanentFailure(item, applicationContext.getString(R.string.error_not_paired)) + + val file = File(item.cachePath) + if (!file.exists()) { + return permanentFailure(item, applicationContext.getString(R.string.error_cache_gone)) + } + + // Long uploads outlive the default 10-minute background budget; run as + // a dataSync foreground job with visible progress. Starting foreground + // can be refused (e.g. app freshly in background on 12+) — the upload + // itself still proceeds, just without a notification. + runCatching { setForeground(foregroundInfo(item, 0)) } + + db.uploads().setStatus(item.id, Status.UPLOADING) + + return try { + when (val outcome = upload(paired.serverUrl, paired.token, item, file)) { + UploadOutcome.DONE -> { + db.uploads().setStatus(item.id, Status.DONE, progress = 100) + file.delete() + Result.success() + } + UploadOutcome.UNAUTHORIZED -> + permanentFailure(item, applicationContext.getString(R.string.error_unauthorized)) + UploadOutcome.REJECTED -> + permanentFailure(item, applicationContext.getString(R.string.error_rejected)) + is UploadOutcome.TRANSIENT -> { + db.uploads().setStatus(item.id, Status.PENDING, error = outcome.message) + Result.retry() + } + } + } catch (e: IOException) { + db.uploads().setStatus(item.id, Status.PENDING, error = e.message) + Result.retry() + } + } + + private sealed interface UploadOutcome { + data object DONE : UploadOutcome + data object UNAUTHORIZED : UploadOutcome + data object REJECTED : UploadOutcome + data class TRANSIENT(val message: String) : UploadOutcome + } + + private suspend fun upload( + serverUrl: String, + token: String, + item: UploadItem, + file: File, + ): UploadOutcome { + // A retried upload may already have landed: ask before sending bytes. + val head = Request.Builder() + .url("$serverUrl/api/object/${item.remoteName}") + .head() + .header("Authorization", "Bearer $token") + .build() + client.newCall(head).execute().use { response -> + when (response.code) { + 204 -> return UploadOutcome.DONE + 401 -> return UploadOutcome.UNAUTHORIZED + 404 -> Unit // expected: not there yet + else -> return UploadOutcome.TRANSIENT("HEAD ${response.code}") + } + } + + val body = CountingFileRequestBody(file) { sent -> + val percent = if (item.size > 0) ((sent * 100) / item.size).toInt() else 0 + setProgressAsync(workDataOf(KEY_PROGRESS to percent)) + runCatching { + setForegroundAsync(foregroundInfo(item, percent)) + } + // Room write per callback would thrash; CountingFileRequestBody + // already throttles callbacks to ~1/s. + kotlinx.coroutines.runBlocking { + db.uploads().setStatus(item.id, Status.UPLOADING, progress = percent) + } + } + val put = Request.Builder() + .url("$serverUrl/api/upload?name=${item.remoteName}") + .put(body) + .header("Authorization", "Bearer $token") + .build() + client.newCall(put).execute().use { response -> + return when (response.code) { + 200, 201 -> UploadOutcome.DONE + 401 -> UploadOutcome.UNAUTHORIZED + 409, 413, 400 -> UploadOutcome.REJECTED + else -> UploadOutcome.TRANSIENT("PUT ${response.code}") + } + } + } + + private suspend fun permanentFailure(item: UploadItem, message: String): Result { + db.uploads().setStatus(item.id, Status.FAILED, error = message) + return Result.failure() + } + + private fun foregroundInfo(item: UploadItem, percent: Int): ForegroundInfo { + val notification: Notification = + NotificationCompat.Builder(applicationContext, App.CHANNEL_UPLOADS) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(applicationContext.getString(R.string.notification_uploading)) + .setContentText(item.originalName) + .setProgress(100, percent, percent == 0) + .setOngoing(true) + .setOnlyAlertOnce(true) + .build() + return if (Build.VERSION.SDK_INT >= 29) { + ForegroundInfo( + item.id.toInt(), + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, + ) + } else { + ForegroundInfo(item.id.toInt(), notification) + } + } + + companion object { + const val KEY_ITEM_ID = "itemId" + const val KEY_PROGRESS = "progress" + + private val client = OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(2, TimeUnit.MINUTES) + // A multi-GB PUT writes for as long as it writes. + .writeTimeout(0, TimeUnit.MILLISECONDS) + .build() + } +} diff --git a/android/app/src/main/res/drawable/ic_check.xml b/android/app/src/main/res/drawable/ic_check.xml new file mode 100644 index 0000000..571e477 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_check.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..10f1126 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..641af5b --- /dev/null +++ b/android/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..91759c1 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/layout/item_upload.xml b/android/app/src/main/res/layout/item_upload.xml new file mode 100644 index 0000000..4282ffb --- /dev/null +++ b/android/app/src/main/res/layout/item_upload.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + diff --git a/android/app/src/main/res/menu/main_menu.xml b/android/app/src/main/res/menu/main_menu.xml new file mode 100644 index 0000000..ec0adb7 --- /dev/null +++ b/android/app/src/main/res/menu/main_menu.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..a8a8fa5 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..a8a8fa5 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..2921400 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + #2E5AAC + #FFFFFFFF + #2E5AAC + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..1bccacf --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,35 @@ + + InternalUploader + Uploads + + Pair this device to start uploading. Sign in on any browser and scan the code, or sign in right here. + Scan QR code + Sign in + Scan the pairing code from your browser + Not a pairing code + Paired + Pairing failed: %1$s + Pair this device first + Paired as %1$s + + Add files + Retry failed + Nothing queued. Share files to InternalUploader or add them here. + Could not queue file: %1$s + + Waiting… + Uploading… %1$d%% + Uploaded + Failed: %1$s + unknown error + + Uploading + + device is not paired + queued copy is gone + rejected — unpair and pair again + rejected by server + + Unpair + Clear finished + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..cf70af4 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,6 @@ + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..3235c84 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.21" apply false + id("com.google.devtools.ksp") version "2.1.21-2.0.1" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..8f2e28c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# 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="\\\"\\\"" + + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..c194eb2 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "internaluploader" +include(":app") diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..76e7aee --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,37 @@ +# internaluploader-server. Build context is server/. +# +# Registries are fully qualified: podman enforces short-name resolution and +# fails a non-interactive build with "cannot prompt without a TTY" rather than +# choosing one. +FROM docker.io/library/node:22-alpine AS build +WORKDIR /src + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY tsconfig.json tsconfig.test.json ./ +COPY src ./src +COPY test ./test + +# Typecheck and test INSIDE the image build — an image that compiles but fails +# its own tests should not reach a registry. +RUN npm run typecheck +RUN npm test + +RUN npm run build +# Drop devDependencies from what gets copied forward. +RUN npm prune --omit=dev + +FROM docker.io/library/node:22-alpine AS runtime +WORKDIR /app +ENV NODE_ENV=production + +COPY --from=build /src/node_modules ./node_modules +COPY --from=build /src/dist ./dist +COPY --from=build /src/package.json ./package.json + +# uid 1000 — the same uid/gid the metube container writes /downloads with, so +# both apps' files on the share look identical. +USER node +EXPOSE 8080 +CMD ["node", "dist/index.js"] diff --git a/server/build.sh b/server/build.sh new file mode 100755 index 0000000..104136b --- /dev/null +++ b/server/build.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Build and push the server image. Tag = -, matching the +# convention of the other mysources.co.uk images (e.g. authentik-qr-login). +set -euo pipefail +cd "$(dirname "$0")" + +REGISTRY="mysources.co.uk/michal" +NAME="internaluploader-server" +TAG="$(date +%Y%m%d)-$(git rev-parse --short=12 HEAD)" +IMAGE="${REGISTRY}/${NAME}:${TAG}" + +podman build -t "${IMAGE}" . +podman push "${IMAGE}" +echo "pushed ${IMAGE}" diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..8c11a84 --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,1569 @@ +{ + "name": "internaluploader-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "internaluploader-server", + "version": "1.0.0", + "dependencies": { + "cookie-session": "^2.1.0", + "express": "^5.1.0", + "openid-client": "^5.6.5", + "qrcode": "^1.5.4" + }, + "devDependencies": { + "@types/cookie-session": "^2.0.49", + "@types/express": "^5.0.6", + "@types/node": "^22.10.0", + "@types/qrcode": "^1.5.5", + "typescript": "^5.9.3" + }, + "engines": { + "node": "22.x" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cookie-session": { + "version": "2.0.49", + "resolved": "https://registry.npmjs.org/@types/cookie-session/-/cookie-session-2.0.49.tgz", + "integrity": "sha512-4E/bBjlqLhU5l4iGPR+NkVJH593hpNsT4dC3DJDr+ODm6Qpe13kZQVkezRIb+TYDXaBMemS3yLQ+0leba3jlkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express": "*", + "@types/keygrip": "*" + } + }, + "node_modules/@types/express": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", + "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "^2" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/keygrip": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/keygrip/-/keygrip-1.0.6.tgz", + "integrity": "sha512-lZuNAY9xeJt7Bx4t4dx0rYCDqGPW8RXhQZK1td7d4H6E9zYbLoOtjBvfwdTKpsyxQI/2jv+armjX/RW+ZNpXOQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz", + "integrity": "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-session": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/cookie-session/-/cookie-session-2.1.1.tgz", + "integrity": "sha512-ji3kym/XZaFVew1+tIZk5ZLp9Z/fLv9rK1aZmpug0FsgE7Cu3ZDrUdRo7FT9vFjMYfNimrrUHJzywDwT7XEFlg==", + "license": "MIT", + "dependencies": { + "cookies": "0.9.1", + "debug": "3.2.7", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cookies": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.9.1.tgz", + "integrity": "sha512-TG2hpqe4ELx54QER/S3HQ9SRVnQnGBtKUz5bLQWtYAQ+o6GpgMs6sYUvaiJjVxb+UXwhRhAEP3m7LbsIZ77Hmw==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-hash": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/oidc-token-hash": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", + "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==", + "license": "MIT", + "engines": { + "node": "^10.13.0 || >=12.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/openid-client": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", + "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", + "license": "MIT", + "dependencies": { + "jose": "^4.15.9", + "lru-cache": "^6.0.0", + "object-hash": "^2.2.0", + "oidc-token-hash": "^5.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/router/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/send/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..a5920dc --- /dev/null +++ b/server/package.json @@ -0,0 +1,29 @@ +{ + "name": "internaluploader-server", + "version": "1.0.0", + "private": true, + "description": "One-way upload endpoint for the InternalUploader Android app: SSO-paired devices drop files into the metube directory as .. No listing, no download.", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json", + "test": "node --test --experimental-strip-types test/*.test.ts", + "start": "node dist/index.js" + }, + "engines": { + "node": "22.x" + }, + "dependencies": { + "cookie-session": "^2.1.0", + "express": "^5.1.0", + "openid-client": "^5.6.5", + "qrcode": "^1.5.4" + }, + "devDependencies": { + "@types/cookie-session": "^2.0.49", + "@types/express": "^5.0.6", + "@types/node": "^22.10.0", + "@types/qrcode": "^1.5.5", + "typescript": "^5.9.3" + } +} diff --git a/server/src/config.ts b/server/src/config.ts new file mode 100644 index 0000000..34d96cb --- /dev/null +++ b/server/src/config.ts @@ -0,0 +1,50 @@ +/** All configuration is environment variables; the deployment cites each name. */ +export interface Config { + port: number; + /** e.g. https://puploader.ad.itaz.eu — used for the OIDC redirect and QR payload. */ + publicOrigin: string; + oidc: { + issuer: string; + clientId: string; + clientSecret: string; + requiredGroup: string; + }; + cookieSecret: string; + /** Where finished files land — the metube download directory bind mount. */ + downloadsDir: string; + /** Persistent state (device token store). A docker named volume. */ + stateDir: string; + maxUploadBytes: number; + /** Deep-link scheme the Android app registers, for /pair/app. */ + appScheme: string; + pairingCodeTtlSeconds: number; +} + +function required(name: string): string { + const value = process.env[name]; + if (!value) { + throw new Error(`Missing required environment variable ${name}`); + } + return value; +} + +export function loadConfig(): Config { + return { + port: Number(process.env.PU_PORT ?? 8080), + publicOrigin: required("PU_PUBLIC_ORIGIN").replace(/\/$/, ""), + oidc: { + issuer: required("PU_OIDC_ISSUER"), + clientId: required("PU_OIDC_CLIENT_ID"), + clientSecret: required("PU_OIDC_CLIENT_SECRET"), + requiredGroup: required("PU_REQUIRED_GROUP"), + }, + cookieSecret: required("PU_COOKIE_SECRET"), + downloadsDir: process.env.PU_DOWNLOADS_DIR ?? "/downloads", + stateDir: process.env.PU_STATE_DIR ?? "/state", + // 32 GiB default: large enough for any single video, small enough that a + // runaway client cannot fill the volume in one request unnoticed. + maxUploadBytes: Number(process.env.PU_MAX_UPLOAD_BYTES ?? 32 * 1024 ** 3), + appScheme: process.env.PU_APP_SCHEME ?? "internaluploader", + pairingCodeTtlSeconds: Number(process.env.PU_PAIRING_CODE_TTL_SECONDS ?? 300), + }; +} diff --git a/server/src/index.ts b/server/src/index.ts new file mode 100644 index 0000000..93d4312 --- /dev/null +++ b/server/src/index.ts @@ -0,0 +1,178 @@ +import cookieSession from "cookie-session"; +import express, { type NextFunction, type Request, type Response } from "express"; + +import { loadConfig } from "./config.ts"; +import { beginAuth, completeAuth, isAuthorised } from "./oidc.ts"; +import { deniedPage, pairingPage, qrPayload } from "./pages.ts"; +import { TokenStore } from "./tokens.ts"; +import { UploadDir, isValidObjectName } from "./upload.ts"; + +const config = loadConfig(); +const tokens = new TokenStore(config.stateDir, config.pairingCodeTtlSeconds * 1000); +const uploads = new UploadDir(config.downloadsDir, config.maxUploadBytes); + +const app = express(); +app.disable("x-powered-by"); +// TLS terminates at the Cilium ingress; without this `secure` cookies die. +app.set("trust proxy", 1); + +app.use( + cookieSession({ + name: "puploader", + secret: config.cookieSecret, + httpOnly: true, + sameSite: "lax", + secure: true, + maxAge: 8 * 60 * 60 * 1000, + }), +); + +app.get("/healthz", (_req, res) => { + res.type("text/plain").send("ok"); +}); + +/** Browser SSO gate: redirects to authentik when there is no session. */ +function requireBrowserSso(req: Request, res: Response, next: NextFunction): void { + const session = req.session as CookieSessionInterfaces.CookieSessionObject; + if (typeof session.username === "string") { + next(); + return; + } + beginAuth(config) + .then((auth) => { + session.oidcState = auth.state; + session.oidcVerifier = auth.codeVerifier; + session.returnTo = req.path; + res.redirect(auth.url); + }) + .catch(next); +} + +app.get("/oidc/callback", (req, res, next) => { + const session = req.session as CookieSessionInterfaces.CookieSessionObject; + const state = session.oidcState; + const codeVerifier = session.oidcVerifier; + if (typeof state !== "string" || typeof codeVerifier !== "string") { + res.status(400).type("text/plain").send("no login in progress"); + return; + } + completeAuth(config, req, { state, codeVerifier }) + .then((identity) => { + delete session.oidcState; + delete session.oidcVerifier; + if (!isAuthorised(config, identity)) { + res.status(403).type("html").send(deniedPage(identity.username, config.oidc.requiredGroup)); + return; + } + session.username = identity.username; + const returnTo = typeof session.returnTo === "string" ? session.returnTo : "/"; + delete session.returnTo; + res.redirect(returnTo); + }) + .catch(next); +}); + +app.get("/", requireBrowserSso, (req, res, next) => { + const session = req.session as CookieSessionInterfaces.CookieSessionObject; + const username = session.username as string; + const pairing = tokens.issuePairingCode(username); + pairingPage(username, qrPayload(config.publicOrigin, pairing.code), config.pairingCodeTtlSeconds) + .then((html) => res.type("html").send(html)) + .catch(next); +}); + +/** + * App-initiated SSO: the app opens this in a Custom Tab; after the same + * browser login the pairing code goes back through the deep link. The app + * never sees OIDC — the phone's browser does, exactly like the QR path. + */ +app.get("/pair/app", requireBrowserSso, (req, res) => { + const session = req.session as CookieSessionInterfaces.CookieSessionObject; + const pairing = tokens.issuePairingCode(session.username as string); + res.redirect(`${config.appScheme}://pair?c=${pairing.code}`); +}); + +app.post("/api/pair", express.json({ limit: "4kb" }), (req, res) => { + const code = (req.body as { code?: unknown })?.code; + if (typeof code !== "string" || !/^[0-9a-f]{64}$/.test(code)) { + res.status(400).json({ error: "malformed pairing code" }); + return; + } + const redeemed = tokens.redeemPairingCode(code); + if (!redeemed) { + res.status(410).json({ error: "pairing code expired or already used" }); + return; + } + console.log(`paired device #${tokens.deviceCount} for ${redeemed.username}`); + res.json({ token: redeemed.token, name: redeemed.username }); +}); + +/** Bearer gate for the upload API. */ +function requireDeviceToken(req: Request, res: Response, next: NextFunction): void { + const header = req.headers.authorization ?? ""; + const token = header.startsWith("Bearer ") ? header.slice(7) : undefined; + const username = token ? tokens.authenticate(token) : undefined; + if (!username) { + res.status(401).json({ error: "invalid device token" }); + return; + } + res.locals.username = username; + next(); +} + +app.head("/api/object/:name", requireDeviceToken, (req, res) => { + const name = req.params.name; + if (typeof name !== "string" || !isValidObjectName(name)) { + res.status(400).end(); + return; + } + uploads + .exists(name) + .then((exists) => res.status(exists ? 204 : 404).end()) + .catch(() => res.status(500).end()); +}); + +app.put("/api/upload", requireDeviceToken, (req, res, next) => { + const name = req.query.name; + if (typeof name !== "string" || !isValidObjectName(name)) { + res.status(400).json({ error: "name must be ." }); + return; + } + uploads + .receive(name, req) + .then((outcome) => { + switch (outcome.status) { + case "created": + console.log(`stored ${name} for ${res.locals.username}`); + res.status(201).json({ stored: name }); + return; + case "exists": + res.status(200).json({ stored: name, existed: true }); + return; + case "hash-mismatch": + res.status(409).json({ error: "content hash mismatch", actual: outcome.actual }); + return; + case "too-large": + res.status(413).json({ error: "upload exceeds the configured maximum" }); + return; + } + }) + .catch(next); +}); + +// Uniform error surface; the details go to the log, not the client. +app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => { + console.error(error); + if (!res.headersSent) { + res.status(500).json({ error: "internal error" }); + } +}); + +async function main(): Promise { + await uploads.init(); + app.listen(config.port, () => { + console.log(`internaluploader-server listening on :${config.port}`); + }); +} + +void main(); diff --git a/server/src/oidc.ts b/server/src/oidc.ts new file mode 100644 index 0000000..b436101 --- /dev/null +++ b/server/src/oidc.ts @@ -0,0 +1,106 @@ +import type { IncomingMessage } from "node:http"; + +import { Issuer, generators, type Client } from "openid-client"; + +import type { Config } from "./config.ts"; + +let issuerPromise: Promise> | undefined; + +/** Discovery, memoised — but NOT on failure, or one early miss poisons the pod. */ +export async function getIssuer(config: Config): Promise> { + if (!issuerPromise) { + issuerPromise = Issuer.discover(config.oidc.issuer).catch((error: unknown) => { + issuerPromise = undefined; + throw error; + }); + } + return issuerPromise; +} + +export function redirectUri(config: Config): string { + return `${config.publicOrigin}/oidc/callback`; +} + +async function clientFor(config: Config): Promise { + const issuer = await getIssuer(config); + return new issuer.Client({ + client_id: config.oidc.clientId, + client_secret: config.oidc.clientSecret, + redirect_uris: [redirectUri(config)], + response_types: ["code"], + }); +} + +export interface AuthRequest { + url: string; + state: string; + codeVerifier: string; +} + +export async function beginAuth(config: Config): Promise { + const client = await clientFor(config); + const state = generators.state(); + const codeVerifier = generators.codeVerifier(); + + return { + // No `prompt: login` here, deliberately — unlike qr-login, an existing + // authentik session is exactly what we want to reuse: pairing is an + // authorization act, not a step-up authentication. + url: client.authorizationUrl({ + scope: "openid email profile", + state, + code_challenge: generators.codeChallenge(codeVerifier), + code_challenge_method: "S256", + }), + state, + codeVerifier, + }; +} + +export interface Identity { + username: string; + groups: string[]; +} + +export async function completeAuth( + config: Config, + request: IncomingMessage, + expected: { state: string; codeVerifier: string }, +): Promise { + const client = await clientFor(config); + const uri = redirectUri(config); + const tokenSet = await client.callback(uri, client.callbackParams(request), { + state: expected.state, + code_verifier: expected.codeVerifier, + }); + + const claims = tokenSet.claims(); + const groups = Array.isArray(claims.groups) + ? claims.groups.filter((g): g is string => typeof g === "string") + : undefined; + + // Fail closed, and say which failure it is. An absent claim means the + // provider is missing its scope mapping; treating that as "no groups" would + // lock everyone out silently, and as "allow" would let everyone in silently. + if (groups === undefined) { + throw new Error( + "ID token carries no `groups` claim — the authentik provider is missing " + + "the profile scope mapping, so membership cannot be checked", + ); + } + + const username = + typeof claims.preferred_username === "string" ? claims.preferred_username : undefined; + if (!username) { + throw new Error( + "ID token carries no `preferred_username` claim — uploads could not be " + + "attributed to a user", + ); + } + + return { username, groups }; +} + +export function isAuthorised(config: Config, identity: Identity): boolean { + return identity.groups.includes(config.oidc.requiredGroup); +} diff --git a/server/src/pages.ts b/server/src/pages.ts new file mode 100644 index 0000000..0e3621f --- /dev/null +++ b/server/src/pages.ts @@ -0,0 +1,73 @@ +import { toDataURL } from "qrcode"; + +export interface QrPayload { + v: 1; + u: string; + c: string; +} + +export function qrPayload(publicOrigin: string, code: string): string { + const payload: QrPayload = { v: 1, u: publicOrigin, c: code }; + return JSON.stringify(payload); +} + +/** + * The whole UI: one page with a QR code. Deliberately says nothing about + * where files go or how to reach the server — the QR carries everything the + * app needs, and this page is already behind SSO. + */ +export async function pairingPage( + username: string, + payload: string, + ttlSeconds: number, +): Promise { + const qrDataUri = await toDataURL(payload, { margin: 1, width: 320 }); + return ` + + + + + +InternalUploader — pair a device + + + +

Pair a device

+

Signed in as ${escapeHtml(username)}. Scan with the InternalUploader app.

+ pairing QR code + Code is single-use and expires in ${Math.round(ttlSeconds / 60)} minutes. + New code + +`; +} + +export function deniedPage(username: string, group: string): string { + return ` +Not authorised + +

Not authorised

+

${escapeHtml(username)} is not in the ${escapeHtml(group)} group.

+`; +} + +function escapeHtml(value: string): string { + return value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} diff --git a/server/src/tokens.ts b/server/src/tokens.ts new file mode 100644 index 0000000..45f029e --- /dev/null +++ b/server/src/tokens.ts @@ -0,0 +1,126 @@ +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * Pairing codes and device tokens. + * + * Pairing codes are IN MEMORY on purpose: they live five minutes and are spent + * once, so surviving a restart buys nothing — and a restart invalidating any + * outstanding QR is the safe direction. + * + * Device tokens persist, HASHED. The stored file never contains anything a + * reader could replay; the plaintext token exists only in the pairing response + * and on the phone. + */ + +export interface PairingCode { + code: string; + username: string; + expiresAt: number; +} + +export interface DeviceRecord { + /** sha256 hex of the bearer token. */ + tokenHash: string; + username: string; + createdAt: string; + /** Coarse (per-day) so routine uploads do not rewrite the file constantly. */ + lastUsedDay: string; +} + +function sha256Hex(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function today(): string { + return new Date().toISOString().slice(0, 10); +} + +export class TokenStore { + private readonly file: string; + private readonly tmp: string; + private readonly pairingTtlMs: number; + private devices: DeviceRecord[] = []; + private pending = new Map(); + + // No parameter properties: `node --test` runs this file under strip-only + // type stripping, which rejects them. + constructor(stateDir: string, pairingTtlMs: number) { + this.pairingTtlMs = pairingTtlMs; + mkdirSync(stateDir, { recursive: true }); + this.file = join(stateDir, "devices.json"); + this.tmp = join(stateDir, "devices.json.tmp"); + try { + this.devices = JSON.parse(readFileSync(this.file, "utf8")) as DeviceRecord[]; + } catch { + this.devices = []; + } + } + + private persist(): void { + // Write-then-rename so a crash mid-write cannot truncate the live store. + writeFileSync(this.tmp, JSON.stringify(this.devices, null, 2)); + renameSync(this.tmp, this.file); + } + + /** Mint a single-use pairing code for a browser-authenticated user. */ + issuePairingCode(username: string): PairingCode { + this.sweep(); + const entry: PairingCode = { + code: randomBytes(32).toString("hex"), + username, + expiresAt: Date.now() + this.pairingTtlMs, + }; + this.pending.set(entry.code, entry); + return entry; + } + + /** Exchange a pairing code for a device token. Single use, TTL enforced. */ + redeemPairingCode(code: string): { token: string; username: string } | undefined { + this.sweep(); + const entry = this.pending.get(code); + if (!entry) { + return undefined; + } + this.pending.delete(entry.code); + const token = randomBytes(32).toString("base64url"); + this.devices.push({ + tokenHash: sha256Hex(token), + username: entry.username, + createdAt: new Date().toISOString(), + lastUsedDay: today(), + }); + this.persist(); + return { token, username: entry.username }; + } + + /** Bearer-token check. Returns the owning username, or undefined. */ + authenticate(token: string): string | undefined { + const hash = Buffer.from(sha256Hex(token), "hex"); + for (const device of this.devices) { + const stored = Buffer.from(device.tokenHash, "hex"); + if (stored.length === hash.length && timingSafeEqual(stored, hash)) { + if (device.lastUsedDay !== today()) { + device.lastUsedDay = today(); + this.persist(); + } + return device.username; + } + } + return undefined; + } + + get deviceCount(): number { + return this.devices.length; + } + + private sweep(): void { + const now = Date.now(); + for (const [code, entry] of this.pending) { + if (entry.expiresAt <= now) { + this.pending.delete(code); + } + } + } +} diff --git a/server/src/upload.ts b/server/src/upload.ts new file mode 100644 index 0000000..2a93891 --- /dev/null +++ b/server/src/upload.ts @@ -0,0 +1,118 @@ +import { createHash, randomUUID } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { mkdir, rename, stat, unlink } from "node:fs/promises"; +import { join } from "node:path"; +import type { Readable } from "node:stream"; + +/** + * `<64 hex sha256>` plus an optional short, lowercase, alphanumeric extension. + * Everything else is rejected before any filesystem call — the name is the only + * client-controlled thing that ever reaches a path. + */ +const NAME_PATTERN = /^[0-9a-f]{64}(\.[a-z0-9]{1,16})?$/; + +export function isValidObjectName(name: string): boolean { + return NAME_PATTERN.test(name); +} + +export function hashOf(name: string): string { + return name.slice(0, 64); +} + +export type UploadOutcome = + | { status: "created" } + | { status: "exists" } + | { status: "hash-mismatch"; actual: string } + | { status: "too-large" }; + +export class UploadDir { + private readonly downloadsDir: string; + private readonly maxBytes: number; + private readonly tmpDir: string; + + // No parameter properties: `node --test` runs this file under strip-only + // type stripping, which rejects them. + constructor(downloadsDir: string, maxBytes: number) { + this.downloadsDir = downloadsDir; + this.maxBytes = maxBytes; + // Same filesystem as the destination, or the final rename stops being + // atomic and a half-written file could be seen with its final name. + this.tmpDir = join(downloadsDir, ".internaluploader-tmp"); + } + + async init(): Promise { + await mkdir(this.tmpDir, { recursive: true }); + } + + async exists(name: string): Promise { + try { + await stat(join(this.downloadsDir, name)); + return true; + } catch { + return false; + } + } + + /** + * Stream a request body to disk, verify its sha256 matches the declared + * name, and only then rename it into the downloads directory. Idempotent: + * a name that already exists is reported without touching anything. + */ + async receive(name: string, body: Readable): Promise { + if (await this.exists(name)) { + return { status: "exists" }; + } + + const tmpPath = join(this.tmpDir, randomUUID()); + const hash = createHash("sha256"); + let received = 0; + + try { + await new Promise((resolve, reject) => { + const out = createWriteStream(tmpPath, { flags: "wx", mode: 0o644 }); + body.on("data", (chunk: Buffer) => { + received += chunk.length; + if (received > this.maxBytes) { + body.destroy(); + out.destroy(); + reject(new TooLargeError()); + return; + } + hash.update(chunk); + }); + body.on("error", reject); + out.on("error", reject); + out.on("finish", resolve); + body.pipe(out); + }); + + const actual = hash.digest("hex"); + if (actual !== hashOf(name)) { + await unlink(tmpPath); + return { status: "hash-mismatch", actual }; + } + + // Lost race with a concurrent identical upload: same content, so the + // file already on disk is exactly what this request carried. + if (await this.exists(name)) { + await unlink(tmpPath); + return { status: "exists" }; + } + + await rename(tmpPath, join(this.downloadsDir, name)); + return { status: "created" }; + } catch (error) { + await unlink(tmpPath).catch(() => {}); + if (error instanceof TooLargeError) { + return { status: "too-large" }; + } + throw error; + } + } +} + +class TooLargeError extends Error { + constructor() { + super("upload exceeds the configured maximum"); + } +} diff --git a/server/test/tokens.test.ts b/server/test/tokens.test.ts new file mode 100644 index 0000000..8109b39 --- /dev/null +++ b/server/test/tokens.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { mkdtempSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +import { TokenStore } from "../src/tokens.ts"; + +test("pairing code round-trip mints a working device token", async () => { + const dir = mkdtempSync(join(tmpdir(), "tokens-")); + const store = new TokenStore(dir, 60_000); + + const pairing = store.issuePairingCode("michal"); + assert.match(pairing.code, /^[0-9a-f]{64}$/); + + const redeemed = store.redeemPairingCode(pairing.code); + assert.ok(redeemed); + assert.equal(redeemed.username, "michal"); + + // Single use. + assert.equal(store.redeemPairingCode(pairing.code), undefined); + + // The token authenticates, wrong tokens do not. + assert.equal(store.authenticate(redeemed.token), "michal"); + assert.equal(store.authenticate("not-a-token"), undefined); + + // Nothing on disk contains the plaintext token. + const persisted = await readFile(join(dir, "devices.json"), "utf8"); + assert.ok(!persisted.includes(redeemed.token)); + + // A fresh store reads the same devices back. + const reloaded = new TokenStore(dir, 60_000); + assert.equal(reloaded.authenticate(redeemed.token), "michal"); +}); + +test("expired pairing codes are refused", () => { + const dir = mkdtempSync(join(tmpdir(), "tokens-")); + const store = new TokenStore(dir, -1); // already expired at issue time + const pairing = store.issuePairingCode("michal"); + assert.equal(store.redeemPairingCode(pairing.code), undefined); +}); diff --git a/server/test/upload.test.ts b/server/test/upload.test.ts new file mode 100644 index 0000000..c229f2a --- /dev/null +++ b/server/test/upload.test.ts @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { createHash, randomBytes } from "node:crypto"; +import { mkdtempSync } from "node:fs"; +import { readFile, readdir, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Readable } from "node:stream"; +import { test } from "node:test"; + +import { UploadDir, hashOf, isValidObjectName } from "../src/upload.ts"; + +test("object name validation", () => { + const hash = "a".repeat(64); + assert.ok(isValidObjectName(hash)); + assert.ok(isValidObjectName(`${hash}.mp4`)); + assert.ok(isValidObjectName(`${hash}.webm`)); + assert.ok(!isValidObjectName(`${hash}.`)); + assert.ok(!isValidObjectName(`${hash}.MP4`), "uppercase extension"); + assert.ok(!isValidObjectName(`${hash}.m p4`), "space in extension"); + assert.ok(!isValidObjectName(`../../etc/passwd`), "traversal"); + assert.ok(!isValidObjectName(`${"a".repeat(63)}.mp4`), "short hash"); + assert.ok(!isValidObjectName(`${hash}.${"x".repeat(17)}`), "long extension"); + assert.equal(hashOf(`${hash}.mp4`), hash); +}); + +function payload(bytes: Buffer): { name: string; body: Readable } { + const digest = createHash("sha256").update(bytes).digest("hex"); + return { name: `${digest}.bin`, body: Readable.from([bytes]) }; +} + +test("receive stores a verified upload and is idempotent", async () => { + const dir = mkdtempSync(join(tmpdir(), "uploads-")); + const uploads = new UploadDir(dir, 1024 * 1024); + await uploads.init(); + + const bytes = randomBytes(4096); + const { name, body } = payload(bytes); + + assert.deepEqual(await uploads.receive(name, body), { status: "created" }); + assert.deepEqual(await readFile(join(dir, name)), bytes); + assert.ok(await uploads.exists(name)); + + const again = await uploads.receive(name, Readable.from([bytes])); + assert.deepEqual(again, { status: "exists" }); + + // The temp dir holds no leftovers either way. + assert.deepEqual(await readdir(join(dir, ".internaluploader-tmp")), []); +}); + +test("receive rejects a body that does not match its name", async () => { + const dir = mkdtempSync(join(tmpdir(), "uploads-")); + const uploads = new UploadDir(dir, 1024 * 1024); + await uploads.init(); + + const name = `${"0".repeat(64)}.bin`; + const outcome = await uploads.receive(name, Readable.from([randomBytes(16)])); + assert.equal(outcome.status, "hash-mismatch"); + await assert.rejects(stat(join(dir, name))); + assert.deepEqual(await readdir(join(dir, ".internaluploader-tmp")), []); +}); + +test("receive enforces the size ceiling", async () => { + const dir = mkdtempSync(join(tmpdir(), "uploads-")); + const uploads = new UploadDir(dir, 1000); + await uploads.init(); + + const bytes = randomBytes(4096); + const { name, body } = payload(bytes); + const outcome = await uploads.receive(name, body); + assert.equal(outcome.status, "too-large"); + assert.deepEqual(await readdir(join(dir, ".internaluploader-tmp")), []); +}); diff --git a/server/tsconfig.json b/server/tsconfig.json new file mode 100644 index 0000000..0119687 --- /dev/null +++ b/server/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "commonjs", + "moduleResolution": "node", + "lib": ["ES2023"], + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": false, + "sourceMap": false, + + // Relative imports carry `.ts` and TypeScript rewrites them to `.js` on + // emit. This is what lets the SAME source run two ways: compiled to + // dist/ for the image, and under Node's strip-only type stripping for + // `node --test`, which resolves imports by their real filename. Without it + // any src module that imports another src module is untestable. + "allowImportingTsExtensions": true, + "rewriteRelativeImportExtensions": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", "test"] +} diff --git a/server/tsconfig.test.json b/server/tsconfig.test.json new file mode 100644 index 0000000..279b740 --- /dev/null +++ b/server/tsconfig.test.json @@ -0,0 +1,13 @@ +{ + // The tests run under Node's type stripping, which resolves imports by their + // real filename — hence the `.ts` extensions in the test sources. The build + // tsconfig cannot allow those, so tests get their own noEmit config. + // Without this the test files would be the one surface nothing checks. + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "allowImportingTsExtensions": true, + "rootDir": "." + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}