diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..48354a3 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,101 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000..043df80 --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..58a9e88 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,54 @@ +apply plugin: 'com.android.application' + +android { + namespace "dev.eom.wikideck" + compileSdk rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "dev.eom.wikideck" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation project(':capacitor-android') + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +try { + def servicesJSON = file('google-services.json') + if (servicesJSON.text) { + apply plugin: 'com.google.gms.google-services' + } +} catch(Exception e) { + logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work") +} diff --git a/android/app/capacitor.build.gradle b/android/app/capacitor.build.gradle new file mode 100644 index 0000000..70f93fc --- /dev/null +++ b/android/app/capacitor.build.gradle @@ -0,0 +1,20 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + implementation project(':capacitor-app') + implementation project(':capacitor-browser') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java new file mode 100644 index 0000000..f2c2217 --- /dev/null +++ b/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import android.content.Context; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + assertEquals("com.getcapacitor.app", appContext.getPackageName()); + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d257625 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/dev/eom/wikideck/MainActivity.java b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java new file mode 100644 index 0000000..94c31d3 --- /dev/null +++ b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java @@ -0,0 +1,5 @@ +package dev.eom.wikideck; + +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity {} diff --git a/android/app/src/main/res/drawable-land-hdpi/splash.png b/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 0000000..e31573b Binary files /dev/null and b/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-mdpi/splash.png b/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xhdpi/splash.png b/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 0000000..8077255 Binary files /dev/null and b/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 0000000..14c6c8f Binary files /dev/null and b/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 0000000..244ca25 Binary files /dev/null and b/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-hdpi/splash.png b/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 0000000..74faaa5 Binary files /dev/null and b/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-mdpi/splash.png b/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 0000000..e944f4a Binary files /dev/null and b/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xhdpi/splash.png b/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 0000000..564a82f Binary files /dev/null and b/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 0000000..bfabe68 Binary files /dev/null and b/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 0000000..6929071 Binary files /dev/null and b/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/splash.png b/android/app/src/main/res/drawable/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/android/app/src/main/res/drawable/splash.png differ 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..b5ad138 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.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..036d09b --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file 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..036d09b --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c023e50 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2127973 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..b441f37 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..72905b8 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8ed0605 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..9502e47 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..4d1e077 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..df0f158 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..853db04 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..6cdf97c Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2960cbb Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..8e3093a Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..46de6e2 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..d2ea9ab Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a40d73e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/values/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file 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..b546c98 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + WikiDeck + WikiDeck + dev.eom.wikideck + dev.eom.wikideck + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..be874e5 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..bd0c4d8 --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java new file mode 100644 index 0000000..0297327 --- /dev/null +++ b/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} diff --git a/android/build-debug.sh b/android/build-debug.sh new file mode 100755 index 0000000..a114749 --- /dev/null +++ b/android/build-debug.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Build the WikiDeck debug APK against the private Night-1 testnet. +# Needs ANDROID_HOME and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk +set -eu +cd "$(dirname "$0")/.." +export VITE_WIKIDECK_NETWORK="${VITE_WIKIDECK_NETWORK:-testnet}" +export VITE_WIKIDECK_GENESIS_TIME="${VITE_WIKIDECK_GENESIS_TIME:-1792411200}" +export VITE_NODE_URL="${VITE_NODE_URL:-http://192.168.1.32:3101}" +npm run build +npx cap sync android +cd android && ./gradlew --no-daemon -q assembleDebug +ls -l app/build/outputs/apk/debug/app-debug.apk diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..f1b3b0e --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.7.2' + classpath 'com.google.gms:google-services:4.4.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: "variables.gradle" + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/capacitor.settings.gradle b/android/capacitor.settings.gradle new file mode 100644 index 0000000..fde830c --- /dev/null +++ b/android/capacitor.settings.gradle @@ -0,0 +1,9 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') + +include ':capacitor-app' +project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android') + +include ':capacitor-browser' +project(':capacitor-browser').projectDir = new File('../node_modules/@capacitor/browser/android') diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..2e87c52 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 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..c1d5e01 --- /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.11.1-all.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..f5feea6 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,252 @@ +#!/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 +' "$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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + 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, 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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..9b42019 --- /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=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% 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 b/android/settings.gradle new file mode 100644 index 0000000..3b4431d --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,5 @@ +include ':app' +include ':capacitor-cordova-android-plugins' +project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/') + +apply from: 'capacitor.settings.gradle' \ No newline at end of file diff --git a/android/variables.gradle b/android/variables.gradle new file mode 100644 index 0000000..2c8e408 --- /dev/null +++ b/android/variables.gradle @@ -0,0 +1,16 @@ +ext { + minSdkVersion = 23 + compileSdkVersion = 35 + targetSdkVersion = 35 + androidxActivityVersion = '1.9.2' + androidxAppCompatVersion = '1.7.0' + androidxCoordinatorLayoutVersion = '1.2.0' + androidxCoreVersion = '1.15.0' + androidxFragmentVersion = '1.8.4' + coreSplashScreenVersion = '1.0.1' + androidxWebkitVersion = '1.12.1' + junitVersion = '4.13.2' + androidxJunitVersion = '1.2.1' + androidxEspressoCoreVersion = '3.6.1' + cordovaAndroidVersion = '10.1.1' +} \ No newline at end of file diff --git a/capacitor.config.ts b/capacitor.config.ts new file mode 100644 index 0000000..432a889 --- /dev/null +++ b/capacitor.config.ts @@ -0,0 +1,26 @@ +import type { CapacitorConfig } from '@capacitor/cli'; + +// WikiDeck mobile shell. Build the web UI with the node URL baked in, then sync: +// VITE_WIKIDECK_NETWORK=testnet VITE_WIKIDECK_GENESIS_TIME=1792411200 \ +// VITE_NODE_URL=http://192.168.1.32:3101 npm run build && npx cap sync android +// (see android/build-debug.sh) +const config: CapacitorConfig = { + appId: 'dev.eom.wikideck', + appName: 'WikiDeck', + webDir: 'dist', + server: { + androidScheme: 'https', + // The private testnet node is plain HTTP on the LAN. + cleartext: true, + }, + android: { + // Android 15 (targetSdk 35) draws edge-to-edge; keep the WebView clear of the system bars. + adjustMarginsForEdgeToEdge: 'auto', + }, + plugins: { + // Route fetch through native HTTP: avoids CORS and the node's browser Origin check. + CapacitorHttp: { enabled: true }, + }, +}; + +export default config; diff --git a/deploy/night/README.md b/deploy/night/README.md index ed73676..fa737ca 100644 --- a/deploy/night/README.md +++ b/deploy/night/README.md @@ -13,6 +13,10 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN - It mines to 4 disposable wallets (alice, bob, carol, dave) and writes chain-bound encrypted browser backups to `$STATE_DIR/wallets/`. - It never changes consensus code. Speed comes from the protocol's own testnet parameters: the initial target accepts 1/16 of hashes, and each 10-block retarget at most quadruples the difficulty. - Each template costs several Wikipedia API calls, and Wikipedia rate-limits our egress IP. The miner therefore paces templates (`MIN_GAP`, default 45 s) and backs off exponentially on failure. +- `compose.lan.yaml` also sets, per node: + - `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed. + - the game-mode env from #22: A = classic and trending, B = draft, C = all three. +- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves. - `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes. Never point this at mainnet or the live `wikideck` namespace. diff --git a/deploy/night/autodeploy.sh b/deploy/night/autodeploy.sh new file mode 100755 index 0000000..3d994ea --- /dev/null +++ b/deploy/night/autodeploy.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# sim-testnet: keep the wikideck-night testnet on the integration branch head. +# Run from the root of a *dedicated* checkout (e.g. a detached git worktree): it checks out +# each new head of $BRANCH and runs `deploy/night/testnet.sh rolling` (ledgers persist in the volumes): +# nodes restart one at a time, and deploys wait (up to FORCE_AFTER) while matches or lobbies are live, +# because lobbies are in memory and a restart ends games in progress. +# Head detection uses the public Gitea API, which also works where SSH auth isn't available. +set -u +BRANCH=${BRANCH:-night/2026-11-16} +API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck} +INTERVAL=${INTERVAL:-180} +LOG=${LOG:-/tmp/wikideck-night-autodeploy.log} +FORCE_AFTER=${FORCE_AFTER:-900} # defer while matches/lobbies are live, but at most this many seconds +deferred_since= +enc=$(printf %s "$BRANCH" | sed 's#/#%2F#g') +while :; do + new=$(node -e "fetch('$API/branches/$enc',{signal:AbortSignal.timeout(15000)}).then(r=>r.json()).then(b=>console.log(b.commit.id)).catch(()=>{})") + cur=$(git rev-parse HEAD) + if [ -z "$new" ]; then echo "WARN branch API failed" + elif [ "$new" != "$cur" ]; then + if ! git fetch -q origin "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH" 2>"$LOG"; then + echo "WARN fetch failed: $(tail -1 "$LOG")" + else + busy=$(deploy/night/testnet.sh busy 2>/dev/null || echo 0) + now=$(date +%s) + if [ "${busy:-0}" -gt 0 ] && { [ -z "$deferred_since" ] || [ $((now - deferred_since)) -lt "$FORCE_AFTER" ]; }; then + [ -z "$deferred_since" ] && { deferred_since=$now; echo "DEFER ${new%"${new#???????}"}: $busy live matches/lobbies"; } + sleep 60; continue + fi + [ -n "$deferred_since" ] && [ "${busy:-0}" -gt 0 ] && echo "FORCE deploy after ${FORCE_AFTER}s ($busy still live)" + deferred_since= + git checkout -q --detach "$new" + echo "DEPLOY start $(git log --oneline -1 | cut -c1-90)" + if deploy/night/testnet.sh rolling >"$LOG" 2>&1; then + sleep 20; echo "DEPLOY ok $(git rev-parse --short HEAD): $(deploy/night/testnet.sh status 2>&1 | tr '\n' ' ')" + else echo "DEPLOY FAILED $(git rev-parse --short HEAD): $(tail -3 "$LOG" | tr '\n' ' ')"; fi + fi + fi + sleep "$INTERVAL" +done diff --git a/deploy/night/testnet.sh b/deploy/night/testnet.sh index e392f4e..4d43f0b 100755 --- a/deploy/night/testnet.sh +++ b/deploy/night/testnet.sh @@ -2,6 +2,8 @@ # sim-testnet: private 3-node testnet fixture for WikiDeck Night 1 (poweredge-r350, LAN only). # Usage (from the repo root): # deploy/night/testnet.sh up build the image from this checkout and (re)start the 3 nodes +# deploy/night/testnet.sh rolling build, then restart node-a, b, c one at a time (waits for /healthz) +# deploy/night/testnet.sh busy print live matches + open lobbies across the 3 nodes # deploy/night/testnet.sh mine N [W] mine N real RandomX blocks with W workers (default 4, max 8) # deploy/night/testnet.sh status tip/height of each node # deploy/night/testnet.sh down stop the nodes (volumes, i.e. the ledgers, are kept) @@ -15,6 +17,21 @@ DC="docker compose -p $P -f compose.testnet.yaml -f deploy/night/compose.lan.yam case "${1:-}" in up) $DC build node-a && $DC up -d --no-build ;; down) $DC down ;; + rolling) + # Never take the whole testnet dark: one node at a time, each must pass /healthz before the next. + $DC build node-a + for n in a b c; do + port=$(( 3100 + $(printf %d "'$n") - 96 )) + $DC up -d --no-build --no-deps node-$n + i=0 + until node -e "fetch('http://$LAN_IP:$port/healthz',{signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"; do + i=$((i+1)); [ $i -ge 60 ] && { echo "node-$n not healthy after 120 s"; exit 1; }; sleep 2 + done + echo "node-$n healthy" + done ;; + busy) + # Sum of liveMatches + openLobbies over all hosted modes on all nodes (unreachable node counts 0). + node -e "Promise.all([3101,3102,3103].map(p=>fetch('http://$LAN_IP:'+p+'/api/game/modes',{signal:AbortSignal.timeout(5000)}).then(r=>r.json()).then(m=>m.modes.reduce((t,x)=>t+(x.stats?.liveMatches??0)+(x.stats?.openLobbies??0),0)).catch(()=>0))).then(v=>console.log(v.reduce((a,b)=>a+b,0)))" ;; mine) mkdir -p "$STATE_DIR" W=${3:-4} @@ -28,5 +45,5 @@ case "${1:-}" in for port in 3101 3102 3103; do docker run --rm --network host wikideck:testnet node -e "fetch('http://$LAN_IP:$port/p2p/status').then(r=>r.json()).then(s=>console.log($port,'blocks',s.size,'tip',s.tip.slice(0,16))).catch(e=>console.log($port,'DOWN',e.message))" done ;; - *) sed -n 2,9p "$0"; exit 1 ;; + *) sed -n 2,11p "$0"; exit 1 ;; esac diff --git a/docs/game/HOSTING.md b/docs/game/HOSTING.md new file mode 100644 index 0000000..73c50ac --- /dev/null +++ b/docs/game/HOSTING.md @@ -0,0 +1,257 @@ +# Hosting WikiDeck game modes + +Anyone running a WikiDeck node can host their own **game modes**: their own twist on the +rules, played with WikiDeck cards on their node, with visible credit for hosting them. +Hosting a popular mode is the night-1 incentive to run a peer. + +- Schema and validator: `shared/game/modes.ts` +- Node API: `server/game/` (mounted at `/api/game` by `server/testnet/http.ts`) +- Example modes: `server/game/modes/*.json` (shipped in the node image) +- Tests: `tests/modes-*.test.ts` + +Everything here is **off-chain**. Hosting a mode never touches blocks, transfers, trades, +validation or NFT ownership. A match never moves or burns a card. + +## 1. Modes are data, never code + +A mode is a JSON document, at most 8 KiB: + +```json +{ + "schema": "wikideck.mode/1", + "id": "trending", + "version": 1, + "name": "Trending", + "description": "Live Wikipedia pageview trends power cards up or down.", + "tags": ["live-data"], + "rules": { "trendUp": 25, "trendDown": -25 }, + "cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true }, + "decks": { "kind": "starter" }, + "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 } +} +``` + +| Field | Meaning | +|---|---| +| `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`#@`). | +| `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. | +| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). | +| `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. | +| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). | +| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | + +The schema is strict: unknown fields are rejected, as are prototype keys +(`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two +levels inside `rules`, more than 48 rule keys, and oversized strings and arrays. A peer +**never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name +a file, a URL, a script or a function. + +## 2. Running your own modes + +Configure modes with environment variables on your node: + +| Variable | Default | Meaning | +|---|---|---| +| `WIKIDECK_MODES` | `classic` | Comma list of built-in ids (`classic`, `trending`, `draft`) and/or paths to `.json` files. `none` hosts nothing (the node still lists its peers' modes). | +| `WIKIDECK_MODES_DIR` | unset | A directory: every `*.json` in it is loaded as a mode. | +| `WIKIDECK_GAME_OPERATOR` | your origin's host | The name shown as **"Hosted by …"**. | +| `WIKIDECK_GAME_NOTE` | unset | A short note shown next to your name, e.g. "EU, best effort". | +| `WIKIDECK_GAME_PEERS` | `WIKIDECK_PEERS` | Peer origins whose modes to list. Use the peers' **public** origins, because players open the peer's own site to play there. | +| `WIKIDECK_GAME_TREND_INTERVAL_MS` | `20000` | Background trend warm-up pace for `trending` modes (minimum 15000). | +| `PUBLIC_ORIGIN` | `http://127.0.0.1:$PORT` | Your node's identity as a host. | + +At most 16 modes per node. A bad mode file stops the node at startup with a readable error, +because rules are validated once with the engine's parser when the node starts. + +Example for the night-1 testnet (three nodes, different modes): + +```yaml +# node-a: the base rules plus Trending +WIKIDECK_MODES: classic,trending +WIKIDECK_GAME_OPERATOR: Testnet A +WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103 +# node-b: the draft +WIKIDECK_MODES: draft +WIKIDECK_GAME_OPERATOR: Testnet B +# node-c: everything, including a custom file +WIKIDECK_MODES: classic,trending,draft,/app/data/modes/blitz.json +``` + +### Writing a new mode + +Start from `server/game/modes/classic.json`, change `id`, `name` and `description`, then +override rules. Some ideas within tonight's rules: + +- **Blitz:** `"rules": { "turns": 4, "energyByTurn": [3, 4, 5, 6] }` +- **On-topic:** `"rules": { "onTopicBonus": [0, 2, 2, 3, 3, 4, 4], "trendUp": 10, "trendDown": -10 }` +- **Slow play:** `"rules": { "turns": 6, "turnSeconds": 40 }` (the engine caps turns × turnSeconds at 240) +- **Big decks:** `"rules": { "deckSize": 16, "maxLoaners": 16 }` with `"decks": { "kind": "draft", "poolSize": 40 }`. + Starter decks are 12 cards, so a non-draft mode with another deck size is rejected at startup. + +Check that a mode parses with `npm test` (the built-in modes are tested), or load it on a +local node: it fails at startup if the engine rejects it. + +## 3. The node API + +Everything is under `/api/game`, behind the node's existing `/api` admission budget and +global rate limit, plus stricter per-route limits. + +| Method | Path | What it does | +|---|---|---| +| GET | `/modes` | **Publish:** this node's host identity, total matches hosted, and each mode with live stats (players online, open lobbies, live matches, matches played, distinct players). | +| GET | `/network/modes` | **Discover:** this node's list plus each configured peer's list, fetched as data. | +| GET | `/hosts/leaderboard` | Hosts ranked by matches hosted (this node plus peers). | +| GET | `/modes/:id/leaderboard` | Per-mode player leaderboard (wins, losses, draws). | +| GET | `/modes/:id/lobbies` | Open lobbies waiting for an opponent. | +| POST | `/modes/:id/lobbies` | Create a lobby: `{ name, secret }` → `{ lobbyId, seat: 0, token }`. | +| POST | `/lobbies/:lobby/join` | Join: `{ name, secret }` → `{ lobbyId, seat: 1, token }`. The match (or draft) starts. | +| GET | `/lobbies/:lobby` | Status. With `Authorization: Bearer `: your `PlayerView` and your `legalActions`. | +| POST | `/lobbies/:lobby/pick` | Draft pick: `{ index }`. | +| POST | `/lobbies/:lobby/actions` | Play: `{ action }`, which must equal one of your `legalActions`. | +| POST | `/lobbies/:lobby/resign` | Resign (or cancel a waiting lobby). | +| GET | `/matches/:matchId` | A finished match record: seed, both decks, the full action log and the result. | + +**Players.** The browser generates a random `secret` once and keeps it in local storage. The +host only ever stores and shows `sha256("wikideck-player:" + secret)` as the player id, so a +leaderboard name can't be claimed by someone else who uses the same display name. Each seat +also gets a fresh bearer token per lobby; only its hash is kept. When eom.dev accounts land +(#7), the player id can come from the account instead. + +**Playing on a peer's mode.** The browser's CSP keeps API calls same-origin, so the lobby +shows peer modes with "Hosted by …" and links to the peer's own site to play there. No node +proxies another node's matches. + +## 4. Credit for hosts + +Every mode shows **"Hosted by <operator>"** (with the node's origin), its player counts, +its own leaderboard, and the node's total matches hosted. `/hosts/leaderboard` ranks nodes by +matches hosted. + +Tonight these numbers are **informational**: each node reports its own counts. See section 6 +for how they could become rewards without trusting the host's word. + +## 5. Security notes + +### Limits + +| Limit | Value | +|---|---| +| Mode document | 8 KiB; 48 rule keys; rule nesting depth 2; strings ≤ 64 chars inside rules | +| Modes per node / per peer response | 16 | +| Peer `/api/game/modes` response | 192 KiB, read with a streaming byte cap; 3 s timeout; no redirects; cached 30 s; at most one refresh in flight | +| Peers | at most 16, operator-configured origins only (HTTPS, or HTTP with `WIKIDECK_ALLOW_PRIVATE_PEERS=1`) | +| Lobbies + matches in memory | 512 per node; `maxConcurrentMatches` per mode; 3 per player | +| Match length | engine bounds (`turns` ≤ 12, turns × turnSeconds ≤ 240 s) plus a hard 2,000-action cap | +| Rate limits per IP | 240/min reads and plays, 60/min lobby create/join/resign, 30/min peer-discovery routes (on top of the node-wide 300/min `/api` limit and the RPC admission budget) | +| Request body | the node's 68 KB JSON limit | +| Wikipedia lookups (`trending`) | background only: one page per 20 s by default (`WIKIDECK_GAME_TREND_INTERVAL_MS`, minimum 15 s), at most 256 queued, never per request | + +### Mode validation + +A mode is rejected at node startup, never handed to the engine half-checked, if: +- it fails the mode schema (section 1), or +- the merged ruleset fails the engine's strict `parseRuleset`, or +- it fails the host-side checks in `server/game/engine-binding.ts`: `distinctStats` requires + `topicCount` 3; every `portalReveal` turn ≤ `turns`; `energyByTurn` has an entry per turn; + `turns × turnSeconds ≤ 240`; `powerByCost` has 7 entries; no keyword whose hidden information + `viewFor` doesn't mask yet (`obscure`) is enabled; or +- its deck policy can't produce legal decks (starter decks illegal under its rules, or a draft + pool smaller than 2 × `deckSize`). + +### Wikipedia load (`verifyStats`) + +Our Wikipedia egress is shared and rate-limited, so tonight the host makes **no Wikipedia +requests in any request or match path**: +- Hosted decks are loaners (starter or drafted), so there are no owned-card stats to verify, + and `verifyStats` never triggers a fetch. +- When owned decks arrive, verification must use the DESIGN §1.10 immutable cache keyed by + `(pageId, revisionId, snapshotMonth)`, with `check: 'unchecked'` and `uncheckedCostCap` as the + normal path when the cache is cold, not a per-card fetch. +- `trending` reads only the background-warmed trend cache (see "Not yet"). + +### Cheating + +- **The client is never trusted.** Each action must deep-equal one of the engine's + `legalActions` for the token's seat, so you can't act for the other seat, play cards you + don't hold, overspend energy or act after the match ends. +- **Hidden information stays on the host.** Each seat only ever receives `viewFor(state, seat)`; + the opponent's hand and staged plays never leave the server. Spectators see status only. +- **Seeds are the host's.** The host picks a random seed when the lobby opens, so players can't + grind for a favourable shuffle. The engine hashes it to 32 bits: fine against players, but + not a secret worth relying on against a host. +- **Stalling:** when a seat runs out of turn time, the host applies the engine's `timeout` + action (auto-commit). After `afkTurns` idle timeouts the engine forfeits that seat. Timeouts + are in the action log, so they replay. A stalled draft pick is made automatically. +- **Sybils and win-trading:** anyone can make a new player id, and two ids controlled by the same + person can feed each other wins. Tonight's leaderboards are for fun. Accounts (#7) or + wallet-signed identities would raise the cost. +- **Card input.** The host builds every deck from shipped engine data (starter decks and the + loaner pool). It never accepts cards, `check` values or pinned stats from client JSON. +- **Card stats.** Card numbers come from the engine's card mapping. Minted stats are self-reported + by the minter (see council-critic in #3); a mode can only pick a mapping preset, not supply numbers. + +### What a malicious host can and can't do + +**Hosted PvP trusts the host.** The host holds both players' hidden plans (hands and queued plays) +and relays them; it decides the seed; and it would be the one to mark card stats as checked or +unchecked (DESIGN §1.10). Nothing tonight lets players verify a match *while* it's being played. +So a host is **trusted for the matches it hosts**, and only those. Play on hosts you trust, and +treat leaderboards on any other host as that host's claims. + +A malicious host **can**: +- lie about its stats, its matches hosted and its leaderboards; +- rig its own matches: pick seeds, peek at hands, or ignore the rules; +- drop or stall your match, or record a false result. + +A malicious host **can't**: +- touch your cards: matches are off-chain, and the host never receives a key or signature; +- run code on other nodes: its modes are inert data, validated with hard limits; +- make other nodes fetch anything except its own `/api/game/modes`, or make them fetch it + in a way that slows them down (byte cap, timeout, cache, single flight); +- publish modes under another node's origin: discovery pins the origin it actually fetched; +- see your player secret: it only receives it once, over its own origin, and stores the hash. + **Use a different secret per host** if you don't trust a host (the UI can derive one per origin). + +**Audit trail.** Every finished match record publishes the seed, both decks and the full action +log, so anyone can re-run it with the engine's `replay(ruleset, decks, seed, actions)` and check +the result. A host that lies about a result can be caught; a host that peeked at hands can't. + +## 6. Proposal: on-chain host rewards (not tonight) + +Rewarding hosts on-chain is a **protocol change**, so it's out of scope for night 1. This is a +proposal for later, to be reviewed like any consensus change. + +**Goal:** pay hosts for matches real players actually played, without trusting the host's count. + +1. **Signed match results.** Both players sign the final result + (`matchId`, `#@`, seed hash, action-log hash, winner) with their wallet + keys. The host signs too. A result needs all three signatures, so a host can't invent matches + or results alone, and players can't deny a match they played. +2. **Replayable evidence.** The record keeps the seed, decks and action log. Anyone can replay it + with the pinned engine version to check the result. Disputes are settled by replay, not by vote. +3. **Batched claims.** Once per epoch, a host submits one transaction committing a Merkle root of + its signed results. A new `hostClaim` transaction type would carry the root and a count. This is + the protocol change: a new transaction type, its validation and its reward rule. +4. **Rewards that resist farming.** A host's reward per epoch grows with the number of **distinct + paired wallets** (not matches), each wallet counts toward at most one host per epoch, wallets + must hold at least one minted card older than N blocks, and the total is a small, capped + share of block rewards. That makes sybil farms cost real mining work. +5. **Challenges.** For a window after a claim, anyone can post a replay that contradicts a + committed result, or proof that a wallet was double-counted. A successful challenge voids + the host's claim for that epoch. + +Open questions: who pays (a share of block rewards versus a fee from players), how to stop +colluding players and hosts from farming one another, and whether the engine version must +be pinned in consensus. + +## Not yet + +- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals + starter decks for it. Playing with your own cards needs a wallet-signed ownership proof + for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and + wallet linking (#7) settle. +- `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend + store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL), + starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This + keeps load on the shared, rate-limited Wikipedia egress tiny: a few dozen pages per 6 hours per node. +- Spectating and rematches. diff --git a/docs/night/IOS.md b/docs/night/IOS.md new file mode 100644 index 0000000..bcacb36 --- /dev/null +++ b/docs/night/IOS.md @@ -0,0 +1,92 @@ +# iOS app and macOS VM (Night 1, mobile-ios, issue #9) + +## Status at a glance +- **macOS VM:** QEMU/KVM on inspiron-3670, OSX-KVM style. Sequoia (15) recovery booted, disk erased (APFS volume `machd`), + licence accepted, and **"Reinstall macOS Sequoia" was downloading the full OS from Apple** over inspiron's Wi-Fi + (installer estimate ~2 h 50 min from 23:33). Per the coordinator, the VM is **shut down cleanly before 01:30** + with the disk kept. See "Progress at shutdown" below for exactly where it got to. +- **No Apple ID** was created or used. Nothing signed in to Apple. +- **iOS Capacitor project:** `ios/` (Capacitor **7.6.x**, Swift Package Manager, no CocoaPods), app id + `dev.eom.wikideck`, URL scheme `dev.eom.wikideck` registered for the SSO redirect. +- **Build script:** `scripts/ios/build-sim.sh` (run inside the VM once Xcode is installed). Not yet run: needs Xcode. + +## Where things are (inspiron-3670, outside git) +| Path | What | +|---|---| +| `~/worker/jobs/macos/boot-macos.sh` | Starts the VM: 8 GB RAM, 4 vCPU, q35, OpenCore, VNC 127.0.0.1:5911, SSH fwd 127.0.0.1:10022 | +| `~/worker/jobs/macos/mac_hdd_ng.qcow2` | 80 GB macOS system disk (keep this) | +| `~/worker/jobs/macos/BaseSystem.img` | Sequoia recovery (3,221,110,784 bytes), converted from macos-fetch's verified `BaseSystem.dmg` | +| `~/worker/jobs/macos/OpenCore-osxkvm.qcow2` | OpenCore bootloader from kholia/OSX-KVM | +| `~/worker/jobs/macos/OVMF_CODE_4M.fd`, `OVMF_VARS.fd` | UEFI firmware and this VM's NVRAM | +| `~/worker/jobs/macos/vnc.sh` | `vncdotool` wrapper (`./vnc.sh capture x.png`, `./vnc.sh type ...`) | +| `~/worker/jobs/macos/guest/provision.sh` | Runs **inside** macOS: Command Line Tools + Node 24 (no Apple ID) | +| `~/worker/jobs/macos/CREDENTIALS.txt` | Local macOS user + password (mode 600, never in git), once the account exists | + +## Start the VM again (resume) +On inspiron-3670: +``` +cd ~/worker/jobs/macos +setsid ./boot-macos.sh > qemu.log 2>&1 < /dev/null & # installer image still attached +# after macOS is fully installed you can detach it: NO_INSTALLER=1 setsid ./boot-macos.sh ... +``` +- In the OpenCore picker pick **`macOS Installer`** / **`machd`** (whichever is offered after the interrupted install; + if only "macOS Base System" shows, the download restarts: pick it → **Reinstall macOS Sequoia** → disk `machd`). +- Clean shutdown from outside: `echo system_powerdown | socat - UNIX-CONNECT:$HOME/worker/jobs/macos/qemu-monitor.sock` + (or `kill $(cat ~/worker/jobs/macos/qemu.pid)` if the guest is hung). + +### See it (VNC through an SSH tunnel from tower-plus) +``` +ssh -N -L 5911:127.0.0.1:5911 eric@inspiron-3670 # on tower-plus +# then open a VNC viewer on tower-plus at localhost:5911 (no VNC password; it is bound to localhost only) +``` +SSH into macOS (after Remote Login is on): `ssh -p 10022 @127.0.0.1` on inspiron, or tunnel `-L 10022:127.0.0.1:10022`. + +Note: the VNC keyboard via `vncdotool` drops Shift (everything types lowercase, `|` becomes `\`). A normal VNC viewer is fine. + +## Eric's checklist from here (~10 min of attention, plus download time) +1. **Finish the install:** start the VM (above), open VNC, let the installer finish (several reboots, pick `machd` / + `macOS Installer` in OpenCore each time if it doesn't auto-boot). +2. **Setup Assistant:** country, *skip* Apple ID ("Set Up Later"), create a local admin user. Put the user and password in + `~/worker/jobs/macos/CREDENTIALS.txt` (`chmod 600`). +3. **Enable SSH:** System Settings → General → Sharing → Remote Login: on. +4. **Prerequisites (no Apple ID):** copy and run the guest script: + ``` + scp -P 10022 ~/worker/jobs/macos/guest/provision.sh @127.0.0.1: + ssh -p 10022 @127.0.0.1 ./provision.sh + ``` +5. **Sign in with your Apple ID and install Xcode** (App Store, or developer.apple.com/download). Launch it once, + accept the licence, install the **iOS platform + a Simulator runtime** when prompted. +6. **Build and run:** + ``` + ssh -p 10022 @127.0.0.1 + git clone -b night/2026-11-16 https://gitea.eom.dev/claude/wikideck.git && cd wikideck + scripts/ios/build-sim.sh # optional arg: simulator name, default "iPhone 16" + ``` + It runs `npm ci`, `npm run build`, `npx cap sync ios`, `xcodebuild` for the simulator (no signing), installs and + launches `dev.eom.wikideck`, and saves a screenshot to `~/wikideck-ios-sim.png`. + +## App notes +- Scaffold (`capacitor.config.ts`, Capacitor deps in `package.json`) is owned by mobile-android (#8); `ios/` builds on it. + Capacitor **7** to match Android (Node 20 on inspiron). +- **Swift Package Manager**, not CocoaPods: `ios/App/CapApp-SPM/Package.swift` is managed by `npx cap sync`; Xcode + resolves `capacitor-swift-pm` itself. No Ruby/CocoaPods needed in the VM. +- **Testnet build:** `build-sim.sh` sets the same defaults as `android/build-debug.sh`: `VITE_WIKIDECK_NETWORK=testnet`, + `VITE_WIKIDECK_GENESIS_TIME=1792411200`, `VITE_NODE_URL=http://192.168.1.32:3101` (override via env). +- **Plain HTTP to the LAN node:** `Info.plist` sets `NSAppTransportSecurity` → `NSAllowsLocalNetworking` (local/IP hosts + only, not arbitrary HTTP), because iOS ATS blocks cleartext by default. From the VM's simulator, 192.168.1.32 is reached + through QEMU's user-mode NAT on inspiron. +- **Plugins:** `@capacitor/app` and `@capacitor/browser` (from #35) are wired into `CapApp-SPM/Package.swift`. +- **Origin check:** mobile-android routes native requests through `CapacitorHttp`, which sends no `Origin` header, so + `server/testnet/http.ts` needs no change. Without it, the iOS WebView origin would be `capacitor://localhost`. +- **SSO (#7):** `Info.plist` registers the `dev.eom.wikideck` URL scheme; redirect `dev.eom.wikideck:/oauth/callback` + returns to the app via `@capacitor/app`'s `appUrlOpen`. + +## Progress at shutdown +_(filled in before 01:25)_ + +## What's verified +- `BaseSystem.dmg` sha256 matches macos-fetch's `SHA256SUMS`; converted `BaseSystem.img` is 3,221,110,784 bytes. +- VM boots on inspiron (KVM, no host `ignore_msrs` change needed): OpenCore → Sequoia recovery → Terminal, Disk Utility. +- Disk erase (APFS) and the installer download started. +- `npx cap add ios --packagemanager SPM` (Capacitor 7.6.10) generates the project on Linux; bundle id `dev.eom.wikideck`. +- **Not verified:** the macOS install finishing, Xcode, `build-sim.sh`, the app in the Simulator. diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..f470299 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,13 @@ +App/build +App/Pods +App/output +App/App/public +DerivedData +xcuserdata + +# Cordova plugins for Capacitor +capacitor-cordova-ios-plugins + +# Generated Config files +App/App/capacitor.config.json +App/App/config.xml diff --git a/ios/App/App.xcodeproj/project.pbxproj b/ios/App/App.xcodeproj/project.pbxproj new file mode 100644 index 0000000..bac2205 --- /dev/null +++ b/ios/App/App.xcodeproj/project.pbxproj @@ -0,0 +1,376 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; + 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; }; + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; }; + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; + 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; + 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 504EC3011FED79650016851F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 504EC2FB1FED79650016851F = { + isa = PBXGroup; + children = ( + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */, + 504EC3061FED79650016851F /* App */, + 504EC3051FED79650016851F /* Products */, + ); + sourceTree = ""; + }; + 504EC3051FED79650016851F /* Products */ = { + isa = PBXGroup; + children = ( + 504EC3041FED79650016851F /* App.app */, + ); + name = Products; + sourceTree = ""; + }; + 504EC3061FED79650016851F /* App */ = { + isa = PBXGroup; + children = ( + 50379B222058CBB4000EE86E /* capacitor.config.json */, + 504EC3071FED79650016851F /* AppDelegate.swift */, + 504EC30B1FED79650016851F /* Main.storyboard */, + 504EC30E1FED79650016851F /* Assets.xcassets */, + 504EC3101FED79650016851F /* LaunchScreen.storyboard */, + 504EC3131FED79650016851F /* Info.plist */, + 2FAD9762203C412B000D30F8 /* config.xml */, + 50B271D01FEDC1A000F3C39B /* public */, + ); + path = App; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 504EC3031FED79650016851F /* App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */; + buildPhases = ( + 504EC3001FED79650016851F /* Sources */, + 504EC3011FED79650016851F /* Frameworks */, + 504EC3021FED79650016851F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = App; + packageProductDependencies = ( + 4D22ABE82AF431CB00220026 /* CapApp-SPM */, + ); + productName = App; + productReference = 504EC3041FED79650016851F /* App.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 504EC2FC1FED79650016851F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 0920; + TargetAttributes = { + 504EC3031FED79650016851F = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 504EC2FB1FED79650016851F; + packageReferences = ( + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */, + ); + productRefGroup = 504EC3051FED79650016851F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 504EC3031FED79650016851F /* App */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 504EC3021FED79650016851F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */, + 50B271D11FEDC1A000F3C39B /* public in Resources */, + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */, + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */, + 504EC30D1FED79650016851F /* Main.storyboard in Resources */, + 2FAD9763203C412B000D30F8 /* config.xml in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 504EC3001FED79650016851F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 504EC30B1FED79650016851F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC30C1FED79650016851F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 504EC3101FED79650016851F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC3111FED79650016851F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 504EC3141FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 504EC3151FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 504EC3171FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; + PRODUCT_BUNDLE_IDENTIFIER = dev.eom.wikideck; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 504EC3181FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = App/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.eom.wikideck; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3141FED79650016851F /* Debug */, + 504EC3151FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3171FED79650016851F /* Debug */, + 504EC3181FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = "CapApp-SPM"; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 4D22ABE82AF431CB00220026 /* CapApp-SPM */ = { + isa = XCSwiftPackageProductDependency; + package = D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */; + productName = "CapApp-SPM"; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 504EC2FC1FED79650016851F /* Project object */; +} diff --git a/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/App/App/AppDelegate.swift b/ios/App/App/AppDelegate.swift new file mode 100644 index 0000000..c3cd83b --- /dev/null +++ b/ios/App/App/AppDelegate.swift @@ -0,0 +1,49 @@ +import UIKit +import Capacitor + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + // Called when the app was launched with a url. Feel free to add additional processing here, + // but if you want the App API to support tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(app, open: url, options: options) + } + + func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { + // Called when the app was launched with an activity, including Universal Links. + // Feel free to add additional processing here, but if you want the App API to support + // tracking app url opens, make sure to keep this call + return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) + } + +} diff --git a/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png b/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png new file mode 100644 index 0000000..adf6ba0 Binary files /dev/null and b/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png differ diff --git a/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..9b7d382 --- /dev/null +++ b/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "AppIcon-512@2x.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/App/App/Assets.xcassets/Contents.json b/ios/App/App/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/ios/App/App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json new file mode 100644 index 0000000..d7d96a6 --- /dev/null +++ b/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "splash-2732x2732-2.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732-1.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png differ diff --git a/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png differ diff --git a/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png differ diff --git a/ios/App/App/Base.lproj/LaunchScreen.storyboard b/ios/App/App/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..e7ae5d7 --- /dev/null +++ b/ios/App/App/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/App/App/Base.lproj/Main.storyboard b/ios/App/App/Base.lproj/Main.storyboard new file mode 100644 index 0000000..b44df7b --- /dev/null +++ b/ios/App/App/Base.lproj/Main.storyboard @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/ios/App/App/Info.plist b/ios/App/App/Info.plist new file mode 100644 index 0000000..39f617f --- /dev/null +++ b/ios/App/App/Info.plist @@ -0,0 +1,67 @@ + + + + + CAPACITOR_DEBUG + $(CAPACITOR_DEBUG) + CFBundleDevelopmentRegion + en + CFBundleDisplayName + WikiDeck + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + CFBundleURLTypes + + + CFBundleURLName + dev.eom.wikideck + CFBundleURLSchemes + + dev.eom.wikideck + + + + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + + diff --git a/ios/App/CapApp-SPM/.gitignore b/ios/App/CapApp-SPM/.gitignore new file mode 100644 index 0000000..3b29812 --- /dev/null +++ b/ios/App/CapApp-SPM/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ +DerivedData/ +.swiftpm/config/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/ios/App/CapApp-SPM/Package.swift b/ios/App/CapApp-SPM/Package.swift new file mode 100644 index 0000000..c50e888 --- /dev/null +++ b/ios/App/CapApp-SPM/Package.swift @@ -0,0 +1,29 @@ +// swift-tools-version: 5.9 +import PackageDescription + +// DO NOT MODIFY THIS FILE - managed by Capacitor CLI commands +let package = Package( + name: "CapApp-SPM", + platforms: [.iOS(.v14)], + products: [ + .library( + name: "CapApp-SPM", + targets: ["CapApp-SPM"]) + ], + dependencies: [ + .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "7.6.10"), + .package(name: "CapacitorApp", path: "../../../node_modules/@capacitor/app"), + .package(name: "CapacitorBrowser", path: "../../../node_modules/@capacitor/browser") + ], + targets: [ + .target( + name: "CapApp-SPM", + dependencies: [ + .product(name: "Capacitor", package: "capacitor-swift-pm"), + .product(name: "Cordova", package: "capacitor-swift-pm"), + .product(name: "CapacitorApp", package: "CapacitorApp"), + .product(name: "CapacitorBrowser", package: "CapacitorBrowser") + ] + ) + ] +) diff --git a/ios/App/CapApp-SPM/README.md b/ios/App/CapApp-SPM/README.md new file mode 100644 index 0000000..5e22a2f --- /dev/null +++ b/ios/App/CapApp-SPM/README.md @@ -0,0 +1,5 @@ +# CapApp-SPM + +This SPM is used to host SPM dependencies for you Capacitor project + +Do not modify the contents of it or there may be unintended consequences. diff --git a/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift b/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift new file mode 100644 index 0000000..945afec --- /dev/null +++ b/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift @@ -0,0 +1 @@ +public let isCapacitorApp = true diff --git a/ios/debug.xcconfig b/ios/debug.xcconfig new file mode 100644 index 0000000..53ce18d --- /dev/null +++ b/ios/debug.xcconfig @@ -0,0 +1 @@ +CAPACITOR_DEBUG = true diff --git a/package-lock.json b/package-lock.json index b5eca26..302991e 100755 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,11 @@ "name": "wikideck", "version": "0.1.0", "dependencies": { + "@capacitor/android": "^7.6.10", + "@capacitor/app": "^7.1.2", + "@capacitor/browser": "^7.0.5", + "@capacitor/core": "^7.6.10", + "@capacitor/ios": "^7.6.10", "express": "^5.1.0", "express-rate-limit": "^8.1.0", "hash-wasm": "^4.12.0", @@ -18,6 +23,7 @@ "zod": "^4.1.0" }, "devDependencies": { + "@capacitor/cli": "^7.6.10", "@types/express": "^5.0.3", "@types/node": "^24.0.0", "@types/react": "^19.1.0", @@ -311,6 +317,97 @@ "node": ">=6.9.0" } }, + "node_modules/@capacitor/android": { + "version": "7.6.10", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-7.6.10.tgz", + "integrity": "sha512-94DBImYZyDA9RnO5ks3MI/j6rRFs1uK5DR2ft/rBIsvsltDT4w1CSuM8U7vKmKEGRmAfP6vH/woJkBF69fZa4A==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^7.6.0" + } + }, + "node_modules/@capacitor/app": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/@capacitor/app/-/app-7.1.2.tgz", + "integrity": "sha512-d4I/oF/PRu4megL7/IGKYfe5j7yzSON1FRFgq6kH+m5kH6g7V+wyjHRLauCzGNjdRx4S+nWOumINds0qcRBtKg==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=7.0.0" + } + }, + "node_modules/@capacitor/browser": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@capacitor/browser/-/browser-7.0.5.tgz", + "integrity": "sha512-YF/kC1m1e6c81X/agtAnYItVlqiQ/nXLG+Q3QXNDuiMoRynqa3Guu8ZaV9kWvqQcHoE2w18xz7WGpPOuh+R1fA==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": ">=7.0.0" + } + }, + "node_modules/@capacitor/cli": { + "version": "7.6.10", + "resolved": "https://registry.npmjs.org/@capacitor/cli/-/cli-7.6.10.tgz", + "integrity": "sha512-8S0h44+339hCJyDw0EWqKz4ivR08tzSY35WzSs49pQ4gNOrGiyKpBUaZc08zlJgvN8yfzMY1pi8QfKDsSn1eHg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/cli-framework-output": "^2.2.8", + "@ionic/utils-subprocess": "^3.0.1", + "@ionic/utils-terminal": "^2.3.5", + "commander": "^12.1.0", + "debug": "^4.4.0", + "env-paths": "^2.2.0", + "fs-extra": "^11.2.0", + "kleur": "^4.1.5", + "native-run": "^2.0.3", + "open": "^8.4.0", + "plist": "^3.1.0", + "prompts": "^2.4.2", + "rimraf": "^6.0.1", + "semver": "^7.6.3", + "tar": "^7.5.3", + "tslib": "^2.8.1", + "xml2js": "^0.6.2" + }, + "bin": { + "cap": "bin/capacitor", + "capacitor": "bin/capacitor" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@capacitor/cli/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@capacitor/core": { + "version": "7.6.10", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-7.6.10.tgz", + "integrity": "sha512-foYHd//t6E3RTELVG8wdkp5jVnmLcHKUurAa9BA8EUSNd2eY0SijCHpfO0bFwYBP5DrCeXwgSFYi3NJw413gtQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@capacitor/ios": { + "version": "7.6.10", + "resolved": "https://registry.npmjs.org/@capacitor/ios/-/ios-7.6.10.tgz", + "integrity": "sha512-iDXt6n6+tQq6fLMgdVNwT7dtgyqGSpGmPx1AGrUJq3YxOqpzqqtY4v4phqhys9PxPSrVyxnWGAL+SEsAHtZLkQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^7.6.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -753,6 +850,174 @@ "node": ">=18" } }, + "node_modules/@ionic/cli-framework-output": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ionic/cli-framework-output/-/cli-framework-output-2.2.8.tgz", + "integrity": "sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-array": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-array/-/utils-array-2.1.6.tgz", + "integrity": "sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-fs/-/utils-fs-3.1.7.tgz", + "integrity": "sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^8.0.0", + "debug": "^4.0.0", + "fs-extra": "^9.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@ionic/utils-object": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-object/-/utils-object-2.1.6.tgz", + "integrity": "sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process": { + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@ionic/utils-process/-/utils-process-2.1.12.tgz", + "integrity": "sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-object": "2.1.6", + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "tree-kill": "^1.2.2", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-stream/-/utils-stream-3.1.7.tgz", + "integrity": "sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-subprocess": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@ionic/utils-subprocess/-/utils-subprocess-3.0.1.tgz", + "integrity": "sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-array": "2.1.6", + "@ionic/utils-fs": "3.1.7", + "@ionic/utils-process": "2.1.12", + "@ionic/utils-stream": "3.1.7", + "@ionic/utils-terminal": "2.3.5", + "cross-spawn": "^7.0.3", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@ionic/utils-terminal/-/utils-terminal-2.3.5.tgz", + "integrity": "sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/slice-ansi": "^4.0.0", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "slice-ansi": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "tslib": "^2.0.1", + "untildify": "^4.0.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -1317,6 +1582,16 @@ "@types/send": "*" } }, + "node_modules/@types/fs-extra": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz", + "integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -1389,6 +1664,13 @@ "@types/node": "*" } }, + "node_modules/@types/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@vitejs/plugin-react": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz", @@ -1410,6 +1692,16 @@ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/@xmldom/xmldom": { + "version": "0.9.12", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz", + "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.6" + } + }, "node_modules/accepts": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", @@ -1449,6 +1741,57 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "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/baseline-browser-mapping": { "version": "2.11.34", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", @@ -1462,6 +1805,16 @@ "node": ">=6.0.0" } }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, "node_modules/body-parser": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", @@ -1486,6 +1839,32 @@ "url": "https://opencollective.com/express" } }, + "node_modules/bplist-parser": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", + "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/browserslist": { "version": "4.29.5", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", @@ -1520,6 +1899,16 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1609,6 +1998,16 @@ "node": ">=8" } }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -1644,6 +2043,16 @@ "dev": true, "license": "MIT" }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/concurrently": { "version": "9.2.5", "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.5.tgz", @@ -1720,6 +2129,21 @@ "node": ">=6.6.0" } }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1744,6 +2168,16 @@ } } }, + "node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1780,6 +2214,19 @@ "dev": true, "license": "ISC" }, + "node_modules/elementtree": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", + "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "sax": "1.1.4" + }, + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -1796,6 +2243,16 @@ "node": ">= 0.8" } }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -1955,6 +2412,16 @@ "express": ">= 4.11" } }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2012,6 +2479,21 @@ "node": ">= 0.8" } }, + "node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2093,6 +2575,24 @@ "node": ">= 0.4" } }, + "node_modules/glob": { + "version": "14.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz", + "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^11.0.5", + "minipass": "^7.1.3", + "path-scurry": "^3.0.0" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2105,6 +2605,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -2199,6 +2706,16 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ini": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", + "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/ip-address": { "version": "10.7.5", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.5.tgz", @@ -2217,6 +2734,22 @@ "node": ">= 0.10" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "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", @@ -2233,6 +2766,26 @@ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "license": "MIT" }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -2266,6 +2819,29 @@ "node": ">=6" } }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -2344,6 +2920,46 @@ "url": "https://opencollective.com/express" } }, + "node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -2369,6 +2985,32 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/native-run": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/native-run/-/native-run-2.1.0.tgz", + "integrity": "sha512-JhEph/fyMwBHmMLiZ1OZX8X92+N1gt5+/ecLtgeRbyDHIyIW7EDt0A3kBZu594y1P4yKDr1CIHe+DDYQ7ZlKjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-fs": "^3.1.7", + "@ionic/utils-terminal": "^2.3.4", + "bplist-parser": "^0.3.2", + "debug": "^4.3.4", + "elementtree": "^0.1.7", + "ini": "^4.1.1", + "plist": "^3.1.0", + "split2": "^4.2.0", + "through2": "^4.0.2", + "tslib": "^2.6.2", + "yauzl": "^2.10.0" + }, + "bin": { + "native-run": "bin/native-run" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/negotiator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", @@ -2432,6 +3074,31 @@ "wrappy": "1" } }, + "node_modules/open": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", + "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -2441,6 +3108,43 @@ "node": ">= 0.8" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/path-to-regexp": { "version": "8.4.2", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", @@ -2451,6 +3155,13 @@ "url": "https://opencollective.com/express" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2471,6 +3182,21 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/plist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", + "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xmldom/xmldom": "^0.9.10", + "base64-js": "^1.5.1", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=10.4.0" + } + }, "node_modules/postcss": { "version": "8.5.32", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", @@ -2500,6 +3226,30 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prompts/node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/proxy-addr": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", @@ -2592,6 +3342,21 @@ "node": ">=0.10.0" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -2602,6 +3367,26 @@ "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.4.tgz", + "integrity": "sha512-Fk3reQDVPZUMbEm7Zwxz03BWQMW3V5buSk9aU8OckTrO8A1nQtbqvYsAantGNermwsIsXcuOBqcoJ3HuMELctw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "glob": "^14.0.3", + "package-json-from-dist": "^1.0.1" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/rollup": { "version": "4.66.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.66.0.tgz", @@ -2674,12 +3459,40 @@ "tslib": "^2.1.0" } }, + "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==", + "dev": true, + "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/sax": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", + "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", + "dev": true, + "license": "ISC" + }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", @@ -2747,6 +3560,29 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/shell-quote": { "version": "1.12.0", "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", @@ -2832,6 +3668,38 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", @@ -2842,6 +3710,16 @@ "node": ">=0.10.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -2851,6 +3729,16 @@ "node": ">= 0.8" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -2895,6 +3783,43 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/tar": { + "version": "7.5.23", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.23.tgz", + "integrity": "sha512-lkukzdoGngZHJZXxW4S/E4Fp9ghTDlyZXrQGRNoJ/LXvDKcXUTq2sg5yQe74po7Voea6n/IN09+wE/QvJMiifA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -2935,7 +3860,6 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, "license": "0BSD" }, "node_modules/tsx": { @@ -2996,6 +3920,16 @@ "dev": true, "license": "MIT" }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -3005,6 +3939,16 @@ "node": ">= 0.8" } }, + "node_modules/untildify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", + "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", @@ -3036,6 +3980,13 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -3120,6 +4071,22 @@ } } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -3144,6 +4111,40 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "dev": true, + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", @@ -3190,6 +4191,17 @@ "node": ">=12" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, "node_modules/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", diff --git a/package.json b/package.json index ef62ab5..9824283 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,11 @@ "test": "node scripts/run-tests.mjs" }, "dependencies": { + "@capacitor/android": "^7.6.10", + "@capacitor/app": "^7.1.2", + "@capacitor/browser": "^7.0.5", + "@capacitor/core": "^7.6.10", + "@capacitor/ios": "^7.6.10", "express": "^5.1.0", "express-rate-limit": "^8.1.0", "hash-wasm": "^4.12.0", @@ -32,6 +37,7 @@ "zod": "^4.1.0" }, "devDependencies": { + "@capacitor/cli": "^7.6.10", "@types/express": "^5.0.3", "@types/node": "^24.0.0", "@types/react": "^19.1.0", diff --git a/scripts/ios/build-sim.sh b/scripts/ios/build-sim.sh new file mode 100755 index 0000000..6150dab --- /dev/null +++ b/scripts/ios/build-sim.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Build WikiDeck for the iOS simulator and launch it. Run INSIDE the macOS VM after Xcode is installed. +# Usage: scripts/ios/build-sim.sh [simulator name, default "iPhone 16"] +set -euo pipefail +cd "$(dirname "$0")/../.." +export PATH="$HOME/node/bin:$PATH" +SIM="${1:-iPhone 16}" +APP_ID=dev.eom.wikideck + +xcode-select -p | grep -q Xcode.app || sudo xcode-select -s /Applications/Xcode.app/Contents/Developer +xcodebuild -version +sudo xcodebuild -license accept 2>/dev/null || true +xcodebuild -runFirstLaunch >/dev/null 2>&1 || true + +npm ci +# Same testnet build settings as android/build-debug.sh (otherwise the app shows MAINNET). +export VITE_WIKIDECK_NETWORK="${VITE_WIKIDECK_NETWORK:-testnet}" +export VITE_WIKIDECK_GENESIS_TIME="${VITE_WIKIDECK_GENESIS_TIME:-1792411200}" +export VITE_NODE_URL="${VITE_NODE_URL:-http://192.168.1.32:3101}" +npm run build +npx cap sync ios + +# Pick the simulator (fall back to the first available iPhone). +UDID=$(xcrun simctl list devices available -j | python3 -c ' +import json,sys; want=sys.argv[1]; d=json.load(sys.stdin)["devices"] +devs=[x for r,l in d.items() if "iOS" in r for x in l] +m=[x for x in devs if x["name"]==want] or [x for x in devs if x["name"].startswith("iPhone")] +print(m[-1]["udid"] if m else "")' "$SIM") +[ -n "$UDID" ] || { echo "No iOS simulator runtime installed. Xcode > Settings > Components > iOS."; exit 1; } + +xcodebuild -project ios/App/App.xcodeproj -scheme App -configuration Debug \ + -sdk iphonesimulator -destination "id=$UDID" -derivedDataPath ios/build \ + CODE_SIGNING_ALLOWED=NO build + +APP=$(find ios/build/Build/Products/Debug-iphonesimulator -maxdepth 1 -name '*.app' | head -1) +xcrun simctl boot "$UDID" 2>/dev/null || true +open -a Simulator +xcrun simctl install "$UDID" "$APP" +xcrun simctl launch "$UDID" "$APP_ID" +sleep 8 +xcrun simctl io "$UDID" screenshot "$HOME/wikideck-ios-sim.png" +echo "Launched $APP_ID on $SIM ($UDID); screenshot: ~/wikideck-ios-sim.png" diff --git a/server/account/README.md b/server/account/README.md index de49bb7..af39324 100644 --- a/server/account/README.md +++ b/server/account/README.md @@ -49,10 +49,14 @@ Signed link message (off-chain, domain-tagged): - The UI is bundled locally, so set `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` before using `src/auth`. That node's POST origin check must allow the app's WebView origin. - Register the URL scheme `dev.eom.wikideck`. - Install `@capacitor/browser` and `@capacitor/app`. -- Add the listener: +- Wire the system browser and the redirect (for example in `src/native.ts`): ```ts - App.addListener('appUrlOpen', ({ url }) => { if (isCallback(url)) void completeLogin(url); }); + import { Browser } from '@capacitor/browser'; + import { completeLogin, isCallback, setNativeBrowser } from './auth/session.ts'; + setNativeBrowser(Browser); + onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); }); ``` + Without `setNativeBrowser`, native login refuses to open (it never falls back to the WebView). ## Known limits - **Logout is local.** Dex publishes no `end_session_endpoint`, so its SSO cookie remains. diff --git a/server/game/config.ts b/server/game/config.ts new file mode 100644 index 0000000..b6393cb --- /dev/null +++ b/server/game/config.ts @@ -0,0 +1,55 @@ +/** + * Operator configuration for hosted modes. Everything comes from the operator's own + * environment and files; nothing here is learned from peers. + * + * WIKIDECK_MODES comma list of built-in mode ids and/or JSON file paths + * (default "classic"; "none" hosts nothing but still discovers) + * WIKIDECK_MODES_DIR optional directory: every *.json in it is a mode + * WIKIDECK_GAME_OPERATOR name shown as "Hosted by ..." (default: the origin's host name) + * WIKIDECK_GAME_NOTE optional short note shown with the host + * WIKIDECK_GAME_PEERS peer origins whose modes to list (default: WIKIDECK_PEERS) + * PUBLIC_ORIGIN this node's public origin (the host identity) + */ +import { readFileSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { HostIdentitySchema, MAX_MODES_PER_NODE, parseModeJson, type HostIdentity, type ModeDocument } from '../../shared/game/modes.ts'; +import { parsePeerOrigins } from './discovery.ts'; + +export const BUILTIN_MODES_DIR = fileURLToPath(new URL('./modes/', import.meta.url)); +export const BUILTIN_MODE_IDS = ['classic', 'trending', 'draft'] as const; + +export function loadModes(env: NodeJS.ProcessEnv = process.env): ModeDocument[] { + const modes: ModeDocument[] = []; + const spec = (env.WIKIDECK_MODES ?? 'classic').trim(); + if (spec !== 'none') for (const item of spec.split(',').map(s => s.trim()).filter(Boolean)) { + if ((BUILTIN_MODE_IDS as readonly string[]).includes(item)) modes.push(readMode(join(BUILTIN_MODES_DIR, `${item}.json`))); + else if (item.endsWith('.json')) modes.push(readMode(resolve(item))); + else throw new Error(`WIKIDECK_MODES: unknown built-in mode "${item.slice(0, 40)}" (use ${BUILTIN_MODE_IDS.join(', ')} or a .json path)`); + } + if (env.WIKIDECK_MODES_DIR) { + const dir = resolve(env.WIKIDECK_MODES_DIR); + for (const f of readdirSync(dir).filter(f => f.endsWith('.json')).sort()) modes.push(readMode(join(dir, f))); + } + if (modes.length > MAX_MODES_PER_NODE) throw new Error(`At most ${MAX_MODES_PER_NODE} modes per node`); + const ids = new Set(); + for (const m of modes) { if (ids.has(m.id)) throw new Error(`Duplicate mode id ${m.id}`); ids.add(m.id); } + return modes; +} + +function readMode(path: string): ModeDocument { + try { return parseModeJson(readFileSync(path, 'utf8')); } + catch (e) { throw new Error(`Invalid mode file ${path}: ${(e as Error).message.slice(0, 300)}`); } +} + +export function hostIdentity(env: NodeJS.ProcessEnv = process.env): HostIdentity { + const origin = new URL(env.PUBLIC_ORIGIN ?? `http://127.0.0.1:${env.PORT ?? 3001}`).origin; + return HostIdentitySchema.parse({ origin, operator: (env.WIKIDECK_GAME_OPERATOR ?? new URL(origin).host).slice(0, 48), + ...(env.WIKIDECK_GAME_NOTE ? { note: env.WIKIDECK_GAME_NOTE.slice(0, 120) } : {}) }); +} + +export function gamePeers(env: NodeJS.ProcessEnv = process.env): string[] { + const self = hostIdentity(env).origin; + return parsePeerOrigins(env.WIKIDECK_GAME_PEERS ?? env.WIKIDECK_PEERS, env.WIKIDECK_ALLOW_PRIVATE_PEERS === '1') + .filter(o => o !== self); +} diff --git a/server/game/discovery.ts b/server/game/discovery.ts new file mode 100644 index 0000000..470531b --- /dev/null +++ b/server/game/discovery.ts @@ -0,0 +1,93 @@ +/** + * Discover the modes of explicitly configured peers. No discovery service, no gossip: + * the operator lists peer origins (WIKIDECK_GAME_PEERS, else WIKIDECK_PEERS). Each peer's + * GET /api/game/modes is fetched with a timeout, a byte cap and no redirects, then parsed + * strictly as data. The fetched origin replaces whatever origin the peer claims. + */ +import { parseModeList, MAX_MODE_LIST_BYTES, type ModeList } from '../../shared/game/modes.ts'; + +export type PeerModes = { origin: string; ok: boolean; error?: string; fetchedAt: number; rejected?: number; list?: ModeList }; +export type Fetcher = (url: string, init: { signal: AbortSignal; redirect: 'error'; headers: Record }) => Promise; + +export function parsePeerOrigins(raw: string | undefined, allowPrivate: boolean): string[] { + const out = new Set(); + for (const text of (raw ?? '').split(',').map(s => s.trim()).filter(Boolean)) { + if (text.length > 256 || !/^https?:\/\/[^/?#\\@\s]+\/?$/i.test(text)) throw new Error(`Invalid game peer origin: ${text.slice(0, 80)}`); + const url = new URL(text); + if (url.protocol !== 'https:' && !(allowPrivate && url.protocol === 'http:')) throw new Error('Game peers must be HTTPS (or HTTP with WIKIDECK_ALLOW_PRIVATE_PEERS=1)'); + out.add(url.origin); + } + if (out.size > 16) throw new Error('At most 16 game peers'); + return [...out]; +} + +export class ModeDiscovery { + private readonly peers: string[]; + private readonly fetcher: Fetcher; + private readonly ttlMs: number; + private readonly timeoutMs: number; + private readonly cache = new Map(); + private inflight: Promise | null = null; + private readonly now: () => number; + + constructor(options: { peers: string[]; fetcher?: Fetcher; ttlMs?: number; timeoutMs?: number; now?: () => number }) { + this.peers = options.peers; + this.fetcher = options.fetcher ?? ((url, init) => fetch(url, init)); + this.ttlMs = options.ttlMs ?? 30_000; + this.timeoutMs = options.timeoutMs ?? 3_000; + this.now = options.now ?? Date.now; + } + + /** Cached peer results; refreshes stale entries at most once concurrently. */ + async all(): Promise { + const now = this.now(); + const stale = this.peers.some(p => { const c = this.cache.get(p); return !c || now - c.fetchedAt > this.ttlMs; }); + if (stale) { + this.inflight ??= Promise.all(this.peers.map(p => this.fetchPeer(p))).finally(() => { this.inflight = null; }); + await this.inflight; + } + return this.peers.map(p => this.cache.get(p)!).filter(Boolean); + } + + private async fetchPeer(origin: string): Promise { + const fetchedAt = this.now(); + let result: PeerModes; + try { + const signal = AbortSignal.timeout(this.timeoutMs); + const res = await this.fetcher(`${origin}/api/game/modes`, { signal, redirect: 'error', headers: { accept: 'application/json' } }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const body = await readCapped(res, MAX_MODE_LIST_BYTES); + const { list, rejected } = parseModeList(body); + // The peer may claim any operator name, but not any origin: we know where we fetched it. + result = { origin, ok: true, fetchedAt, rejected, list: { ...list, host: { ...list.host, origin } } }; + } catch (e) { + const previous = this.cache.get(origin); + result = { origin, ok: false, error: describe(e), fetchedAt, ...(previous?.list ? { list: previous.list } : {}) }; + } + this.cache.set(origin, result); + return result; + } +} + +async function readCapped(res: Response, max: number): Promise { + const declared = Number(res.headers.get('content-length') ?? 0); + if (declared > max) throw new Error('Mode list too large'); + if (!res.body) return ''; + const reader = res.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > max) { await reader.cancel(); throw new Error('Mode list too large'); } + chunks.push(value); + } + return new TextDecoder().decode(Buffer.concat(chunks)); +} + +function describe(e: unknown): string { + const m = e instanceof Error ? e.message : String(e); + return (m.includes('too large') ? 'response too large' : m.includes('abort') || m.includes('timeout') ? 'timeout' + : /^HTTP \d+$/.test(m) ? m : e instanceof SyntaxError ? 'invalid JSON' : 'invalid or unreachable').slice(0, 80); +} diff --git a/server/game/engine-binding.ts b/server/game/engine-binding.ts new file mode 100644 index 0000000..695a994 --- /dev/null +++ b/server/game/engine-binding.ts @@ -0,0 +1,74 @@ +/** Binds the mode host to the real engine through its public API (shared/game/index.ts). */ +import { DEFAULT_RULESET, parseRuleset, starterDeck, loanerCard, STARTER_POOL, validateDeck, createMatch, + legalActions, applyAction, isOver, result, viewFor, Rng, + type Action, type GameCard, type MatchState, type Ruleset } from '../../shared/game/index.ts'; +import type { EnginePort, Seat } from './engine-port.ts'; + +/** + * Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the + * starter pool, one copy per round, never exceeding the ruleset's per-page copy limit. + */ +export function previewPool(rules: Ruleset, seed: string, size: number): GameCard[] { + const rng = Rng.fromSeed(`draft-pool:${seed}`); + const pool: GameCard[] = []; + for (let copy = 0; pool.length < size && copy < rules.maxCopiesPerPage; copy++) { + for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(loanerCard(spec, copy)); } + } + return pool; +} + +/** + * The engine's strict parseRuleset, plus host-side checks that keep a hosted mode playable + * (requested in review on #6). Anything that fails is rejected at startup, never passed on. + */ +export const UNSAFE_KEYWORDS: readonly string[] = ['obscure']; + +export function parseModeRuleset(value: unknown): Ruleset { + const rules = parseRuleset(value); + const problems: string[] = []; + if (rules.distinctStats && rules.topicCount !== 3) problems.push('distinctStats requires topicCount 3'); + if (rules.portalReveal.some(turn => turn > rules.turns)) problems.push('every portalReveal turn must be ≤ turns'); + if (rules.energyByTurn.length < rules.turns) problems.push('energyByTurn needs one entry per turn'); + if (rules.turns * rules.turnSeconds > 240) problems.push('turns × turnSeconds must be ≤ 240'); + if (rules.powerByCost.length !== 7) problems.push('powerByCost needs 7 entries'); + // Keywords whose hidden information viewFor doesn't mask yet would leak cards to the opponent (#6, #27). + for (const id of UNSAFE_KEYWORDS) if ((rules.keywordsEnabled as readonly string[]).includes(id)) problems.push(`keyword "${id}" is not hostable yet (viewFor does not mask it)`); + if (problems.length) throw new Error(`Invalid mode rules: ${problems.join('; ')}`); + return rules; +} + +export const engineBinding: EnginePort = { + defaultRuleset: DEFAULT_RULESET, + parseRuleset: parseModeRuleset, + deckSize: rules => rules.deckSize, + starterDeck: (_rules, seed) => starterDeck(seed), + previewPool, + validateDeck: (rules, cards) => { + const problems = validateDeck(rules, cards); + if (problems.length) throw new Error(problems.slice(0, 3).join('; ')); + }, + cardPower: card => card.power, + withPower: (card, power) => ({ ...card, power: Math.min(30, Math.max(0, power)) }), + cardPageId: card => card.pageId, + cardSummary: card => ({ cardId: card.cardId, title: card.title, pageId: card.pageId, faction: card.faction, + cost: card.cost, power: card.power, home: card.home, trend: card.trend, keyword: card.keyword }), + createMatch: (rules, decks, seed) => createMatch(rules, decks, seed), + legalActions: (state, seat) => legalActions(state, seat), + applyAction: (state, seat: Seat, action) => { + if (action.player !== seat) throw new Error('Action for the wrong seat'); + return applyAction(state, action); + }, + concedeAction: seat => ({ type: 'concede', player: seat }), + timeoutAction: seat => ({ type: 'timeout', player: seat }), + turnSeconds: rules => rules.turnSeconds, + turnOf: state => state.turn, + // DESIGN §1.6: the live trend arrow, frozen at match start, using the ruleset's thresholds. + applyLive: (rules, card, live) => { + const t = live.trendPercent; + const trend = t === null || !Number.isFinite(t) ? 0 : t >= rules.trendUp ? 1 : t <= rules.trendDown ? -1 : 0; + return { ...card, trend }; + }, + isOver, + result: state => { const r = result(state); return { winner: r?.winner ?? null, reason: r?.reason ?? 'complete' }; }, + viewFor: (state, seat) => viewFor(state, seat), +}; diff --git a/server/game/engine-port.ts b/server/game/engine-port.ts new file mode 100644 index 0000000..74b50b7 --- /dev/null +++ b/server/game/engine-port.ts @@ -0,0 +1,43 @@ +/** + * The slice of the engine API (docs/game/ENGINE_API.md) the mode host uses. + * The host is engine-agnostic behind this port: the real binding lives in engine-binding.ts, + * tests use a tiny stub. Card and state values are opaque to the host. + */ +export type Seat = 0 | 1; +export type MatchOutcome = { winner: Seat | null; reason?: string }; + +export interface EnginePort { + readonly defaultRuleset: Rules; + /** Strict engine-side validation of a merged ruleset. Throws on anything invalid. */ + parseRuleset(value: unknown): Rules; + deckSize(rules: Rules): number; + starterDeck(rules: Rules, seed: string): Card[]; + /** Deterministic pool of non-NFT preview cards, for draft modes. */ + previewPool(rules: Rules, seed: string, size: number): Card[]; + /** Throws if the deck is not legal under the rules. */ + validateDeck(rules: Rules, cards: Card[]): void; + cardPower(card: Card): number; + withPower(card: Card, power: number): Card; + /** Wikipedia page id of a card, if it has one (for live/trending mappings). */ + cardPageId(card: Card): number | null; + /** Public, JSON-safe summary shown in a draft pool. */ + cardSummary(card: Card): unknown; + + createMatch(rules: Rules, decks: [Card[], Card[]], seed: string): State; + legalActions(state: State, seat: Seat): Action[]; + applyAction(state: State, seat: Seat, action: Action): State; + /** Optional engine-level concede, so a resignation is part of the replayable action log. */ + concedeAction?(seat: Seat): Action; + /** Optional host-only timeout action, applied when a seat runs out of turn time. */ + timeoutAction?(seat: Seat): Action; + /** Optional per-turn time limit from the ruleset, in seconds. */ + turnSeconds?(rules: Rules): number; + /** Optional current turn number, so the host can time turns rather than actions. */ + turnOf?(state: State): number; + /** Optional: freeze live data onto a card at match start (e.g. a trend arrow). */ + applyLive?(rules: Rules, card: Card, live: { trendPercent: number | null }): Card; + isOver(state: State): boolean; + result(state: State): MatchOutcome; + /** What one seat may see (hides the opponent's hand and staged plays). */ + viewFor(state: State, seat: Seat): unknown; +} diff --git a/server/game/host.ts b/server/game/host.ts new file mode 100644 index 0000000..3ffa3d9 --- /dev/null +++ b/server/game/host.ts @@ -0,0 +1,357 @@ +/** + * Hosts lobbies and matches for this node's modes, with the deterministic engine. + * All state is off-chain and in memory; finished matches go to the MatchStore. + * + * Trust model: the host is authoritative for its own matches. Players are identified by a + * client-held secret (only its SHA-256 is stored or shown) and act through per-seat bearer + * tokens. Every action must equal one of the engine's legalActions for that seat. + */ +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import { isDeepStrictEqual } from 'node:util'; +import { modeKey, resolveRuleset, trendBonus, clampPower, MODE_SCHEMA_VERSION, + type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts'; +import type { EnginePort, Seat } from './engine-port.ts'; +import { MatchStore, type MatchRecord } from './store.ts'; + +export class GameError extends Error { + readonly status: number; + constructor(status: number, message: string) { super(message); this.status = status; } +} + +type Player = { id: string; name: string; tokenHash: Buffer; seen: number }; +type Phase = 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired'; +type Lobby = { + id: string; mode: ModeDocument; rules: unknown; seed: string; createdAt: number; + players: Player[]; phase: Phase; + draft?: { pool: unknown[]; taken: (Seat | null)[]; order: Seat[]; turn: number; deadline: number }; + decks?: [unknown[], unknown[]]; + state?: unknown; actions: { seat: Seat; action: unknown }[]; startedAt?: number; lastMove: number; turnStartedAt?: number; turn?: number; + outcome?: { winner: Seat | null; reason: string }; matchId?: string; +}; +type HostedMode = { mode: ModeDocument; rules: unknown }; + +export type HostOptions = { + identity: HostIdentity; + modes: ModeDocument[]; + engine: EnginePort; + store: MatchStore; + /** Optional live Wikipedia trend lookup for `trending` modes. Failures mean "no bonus". */ + liveData?: (pageId: number) => Promise; + now?: () => number; + /** Node-wide cap on lobbies + matches in memory across all modes. */ + maxLobbies?: number; +}; + +export type SeatTicket = { lobbyId: string; seat: Seat; token: string }; + +const NAME = /^[\p{L}\p{N} _.\-]{1,24}$/u; +const SECRET = /^[A-Za-z0-9_-]{22,128}$/; +const LOBBY_ID = /^[a-f0-9]{24}$/; + +export class ModeHost { + readonly identity: HostIdentity; + private readonly engine: EnginePort; + private readonly store: MatchStore; + private readonly hosted = new Map(); + private readonly lobbies = new Map(); + private readonly liveData?: HostOptions['liveData']; + private readonly now: () => number; + private readonly maxLobbies: number; + + constructor(options: HostOptions) { + this.identity = options.identity; + this.engine = options.engine; + this.store = options.store; + this.liveData = options.liveData; + this.now = options.now ?? Date.now; + this.maxLobbies = options.maxLobbies ?? 512; + for (const mode of options.modes) { + if (this.hosted.has(mode.id)) throw new Error(`Duplicate mode id ${mode.id}`); + // Validate rules once at startup with the engine's own parser: a bad mode fails loudly. + const rules = resolveRuleset(this.engine.defaultRuleset, mode.rules, v => this.engine.parseRuleset(v)); + if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * this.engine.deckSize(rules)) { + throw new Error(`Mode ${mode.id}: draft poolSize must be at least 2 × deck size`); + } + if (mode.decks.kind !== 'draft') { + // Host-dealt starter decks must be legal under the mode's rules, or the mode is unplayable. + try { this.engine.validateDeck(rules, this.engine.starterDeck(rules, 'startup-check')); } + catch (e) { throw new Error(`Mode ${mode.id}: starter decks are illegal under its rules (${(e as Error).message.slice(0, 120)}); use a draft deck policy`); } + } + this.hosted.set(mode.id, { mode, rules }); + } + } + + /** Body of GET /api/game/modes. */ + list(): ModeList { + return { schema: MODE_SCHEMA_VERSION, host: this.identity, matchesHosted: this.store.total, + modes: [...this.hosted.values()].map(h => ({ mode: h.mode, stats: this.stats(h.mode.id) })) }; + } + + stats(modeId: string): ModeStats { + let online = 0, open = 0, live = 0; + for (const l of this.lobbies.values()) { + if (l.mode.id !== modeId) continue; + if (l.phase === 'waiting') open++; + if (l.phase === 'starting' || l.phase === 'drafting' || l.phase === 'playing') live++; + if (l.phase !== 'finished' && l.phase !== 'expired') online += l.players.length; + } + return { playersOnline: online, openLobbies: open, liveMatches: live, + matchesPlayed: this.store.modeMatches(modeId), distinctPlayers: this.store.modePlayers(modeId) }; + } + + leaderboard(modeId: string) { + const h = this.mode(modeId); + return { host: this.identity, mode: { id: h.mode.id, version: h.mode.version, name: h.mode.name }, + key: modeKey(this.identity.origin, h.mode), entries: this.store.leaderboard(modeId) }; + } + + openLobbies(modeId: string) { + this.mode(modeId); + return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting') + .slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt })); + } + + createLobby(modeId: string, player: { name: unknown; secret: unknown }): SeatTicket { + const h = this.mode(modeId); + this.sweep(); + const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired'); + if (active.length >= this.maxLobbies) throw new GameError(503, 'This host is full; try again later.'); + if (active.filter(l => l.mode.id === modeId).length >= h.mode.limits.maxConcurrentMatches) { + throw new GameError(503, 'This mode is at its match limit on this host; try again later.'); + } + const p = this.player(player); + if (active.filter(l => l.players.some(x => x.id === p.player.id)).length >= 3) { + throw new GameError(429, 'Too many open lobbies or matches for this player.'); + } + const id = randomBytes(12).toString('hex'); + const now = this.now(); + this.lobbies.set(id, { id, mode: h.mode, rules: h.rules, seed: randomBytes(16).toString('hex'), createdAt: now, + players: [p.player], phase: 'waiting', actions: [], lastMove: now }); + return { lobbyId: id, seat: 0, token: p.token }; + } + + async join(lobbyId: string, player: { name: unknown; secret: unknown }): Promise { + const l = this.lobby(lobbyId); + this.sweep(); + if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.'); + const p = this.player(player); + if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.'); + l.players.push(p.player); + l.lastMove = this.now(); + // Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check. + l.phase = 'starting'; + if (l.mode.decks.kind === 'draft') this.startDraft(l); + else await this.startMatch(l, [this.engine.starterDeck(l.rules, `${l.seed}:0`), this.engine.starterDeck(l.rules, `${l.seed}:1`)]); + return { lobbyId: l.id, seat: 1, token: p.token }; + } + + /** Public status, plus the seat's private view when a valid token is given. */ + view(lobbyId: string, token?: string) { + const l = this.lobby(lobbyId); + this.sweep(); + const seat = token ? this.seatFor(l, token) : null; + const base = { lobbyId: l.id, phase: l.phase, host: this.identity, + mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name }, + players: l.players.map(p => ({ id: p.id, name: p.name })), seat, matchId: l.matchId ?? null, + outcome: l.outcome ?? null }; + if (l.phase === 'drafting' && l.draft) { + const d = l.draft; + return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: this.engine.cardSummary(c), takenBy: d.taken[i] })), + toPick: d.order[d.turn] ?? null, deadline: d.deadline } }; + } + if ((l.phase === 'playing' || l.phase === 'finished') && l.state !== undefined && seat !== null) { + return { ...base, state: this.engine.viewFor(l.state, seat), + legalActions: l.phase === 'playing' ? this.engine.legalActions(l.state, seat) : [] }; + } + return base; + } + + async pick(lobbyId: string, token: string, index: unknown) { + const l = this.lobby(lobbyId); + const seat = this.requireSeat(l, token); + this.sweep(); + if (l.phase !== 'drafting' || !l.draft) throw new GameError(409, 'Not drafting.'); + if (l.draft.order[l.draft.turn] !== seat) throw new GameError(409, 'Not your pick.'); + if (typeof index !== 'number' || !Number.isInteger(index) || index < 0 || index >= l.draft.pool.length || + l.draft.taken[index] !== null) throw new GameError(400, 'Invalid pick.'); + await this.takePick(l, seat, index); + return this.view(lobbyId, token); + } + + async act(lobbyId: string, token: string, action: unknown) { + const l = this.lobby(lobbyId); + const seat = this.requireSeat(l, token); + this.sweep(); + if (l.phase !== 'playing' || l.state === undefined) throw new GameError(409, 'No match in progress.'); + // The host never trusts a client action: it must be one of the engine's legal actions. + const legal = this.engine.legalActions(l.state, seat); + const chosen = legal.find(a => isDeepStrictEqual(a, action)); + if (chosen === undefined) throw new GameError(400, 'Illegal action.'); + this.apply(l, seat, chosen); + l.players[seat]!.seen = l.lastMove; + return this.view(lobbyId, token); + } + + resign(lobbyId: string, token: string) { + const l = this.lobby(lobbyId); + const seat = this.requireSeat(l, token); + if (l.phase === 'waiting') { l.phase = 'expired'; return this.view(lobbyId, token); } + if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.'); + if (l.phase === 'playing' && l.state !== undefined && this.engine.concedeAction) { + this.apply(l, seat, this.engine.concedeAction(seat), 'resign'); + if ((l.phase as Phase) === 'finished') return this.view(lobbyId, token); + } + this.finish(l, seat === 0 ? 1 : 0, 'resign'); + return this.view(lobbyId, token); + } + + matchRecord(matchId: string): MatchRecord { + if (!/^[a-f0-9]{32}$/.test(matchId)) throw new GameError(400, 'Invalid match id.'); + const r = this.store.get(matchId); + if (!r) throw new GameError(404, 'Match not found on this host.'); + return r; + } + + /** Expire idle lobbies, auto-pick stalled drafts, forfeit stalled matches, drop old lobbies. */ + sweep(): void { + const now = this.now(); + for (const l of this.lobbies.values()) { + if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) l.phase = 'expired'; + else if (l.phase === 'drafting' && l.draft && now > l.draft.deadline) { + // Auto-pick the first free card for whoever is stalling; synchronous, no live data. + const idx = l.draft.taken.indexOf(null); + if (idx >= 0) void this.takePick(l, l.draft.order[l.draft.turn]!, idx).catch(() => { l.phase = 'expired'; }); + } else if (l.phase === 'playing' && l.state !== undefined && now - (l.turnStartedAt ?? l.lastMove) > this.turnMs(l)) { + const waiting = ([0, 1] as Seat[]).filter(s => this.engine.legalActions(l.state, s).length > 0); + if (this.engine.timeoutAction) { + // The engine decides what a timeout means (auto-commit, AFK forfeit); it is logged and replayable. + for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, this.engine.timeoutAction(s)); + l.turnStartedAt = now; + } else if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout'); + else this.finish(l, null, 'abandoned'); + } + if ((l.phase === 'finished' || l.phase === 'expired') && now - l.lastMove > 10 * 60_000) this.lobbies.delete(l.id); + } + } + + private startDraft(l: Lobby) { + if (l.mode.decks.kind !== 'draft') return; + const size = this.engine.deckSize(l.rules); + const pool = this.engine.previewPool(l.rules, `${l.seed}:pool`, l.mode.decks.poolSize); + if (pool.length < 2 * size) throw new GameError(500, 'Engine returned a short draft pool.'); + // Snake order 0,1,1,0,0,1,... with a seed-chosen first picker. + const first: Seat = parseInt(l.seed.slice(0, 2), 16) % 2 === 0 ? 0 : 1; + const order: Seat[] = []; + for (let i = 0; i < 2 * size; i++) order.push(((Math.floor((i + 1) / 2) % 2 === 0 ? first : 1 - first)) as Seat); + l.draft = { pool, taken: pool.map(() => null), order, turn: 0, deadline: this.now() + l.mode.decks.pickSeconds * 1000 }; + l.phase = 'drafting'; + } + + private async takePick(l: Lobby, seat: Seat, index: number) { + const d = l.draft!; + d.taken[index] = seat; + d.turn++; + l.lastMove = this.now(); + if (l.mode.decks.kind === 'draft') d.deadline = this.now() + l.mode.decks.pickSeconds * 1000; + if (d.turn >= d.order.length) { + const decks: [unknown[], unknown[]] = [[], []]; + d.taken.forEach((s, i) => { if (s !== null) decks[s].push(d.pool[i]); }); + await this.startMatch(l, decks); + } + } + + private async startMatch(l: Lobby, decks: [unknown[], unknown[]]) { + const mapped = await Promise.all(decks.map(d => this.mapDeck(l.mode, d))) as [unknown[], unknown[]]; + for (const d of mapped) { + try { this.engine.validateDeck(l.rules, d); } + catch (e) { l.phase = 'expired'; throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); } + } + l.decks = mapped; + l.state = this.engine.createMatch(l.rules, mapped, l.seed); + l.phase = 'playing'; + l.startedAt = l.lastMove = l.turnStartedAt = this.now(); + l.turn = this.engine.turnOf?.(l.state); + delete l.draft; + if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); } + } + + /** Apply the mode's card-mapping preset. Bonus data is looked up once, before the match. */ + private async mapDeck(mode: ModeDocument, deck: unknown[]): Promise { + const mapping = mode.cards; + if (mapping.preset === 'standard' || !this.liveData) return deck; + return Promise.all(deck.map(async card => { + const pageId = this.engine.cardPageId(card); + if (pageId === null) return card; + const live = await this.liveData!(pageId).catch(() => null); + if (!live) return card; + // `live` and `trending`: freeze the live trend arrow onto the card (engine rules decide its effect). + let mapped = this.engine.applyLive ? this.engine.applyLive(this.hosted.get(mode.id)!.rules, card, live) : card; + if (mapping.preset === 'trending') { + const bonus = trendBonus(mapping, live.trendPercent); + if (bonus !== 0) mapped = this.engine.withPower(mapped, clampPower(this.engine.cardPower(mapped) + bonus)); + } + return mapped; + })); + } + + /** Apply an action already known to be legal (or host-issued), log it, and settle the match if over. */ + private apply(l: Lobby, seat: Seat, action: unknown, reason?: string) { + l.state = this.engine.applyAction(l.state, seat, action); + l.actions.push({ seat, action }); + l.lastMove = this.now(); + const turn = this.engine.turnOf?.(l.state); + if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; } + if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); } + else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit'); + } + + /** Turn timer: the engine's own per-turn limit plus a little network grace, else the mode's limit. */ + private turnMs(l: Lobby): number { + const engineSeconds = this.engine.turnSeconds?.(l.rules); + return engineSeconds !== undefined ? (engineSeconds + 5) * 1000 : l.mode.limits.turnSeconds * 1000; + } + + private finish(l: Lobby, winner: Seat | null, reason: string) { + if (l.phase === 'finished' || l.phase === 'expired') return; + l.phase = 'finished'; + l.outcome = { winner, reason }; + l.lastMove = this.now(); + if (!l.decks || l.players.length !== 2) return; // Resigned during draft: no match record. + const matchId = randomBytes(16).toString('hex'); + l.matchId = matchId; + this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, seed: l.seed, rules: l.rules, + players: l.players.map(p => ({ id: p.id, name: p.name })), winner, reason: reason.slice(0, 40), + startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions }); + } + + private mode(modeId: string): HostedMode { + const h = typeof modeId === 'string' ? this.hosted.get(modeId) : undefined; + if (!h) throw new GameError(404, 'Mode not hosted here.'); + return h; + } + private lobby(lobbyId: string): Lobby { + const l = typeof lobbyId === 'string' && LOBBY_ID.test(lobbyId) ? this.lobbies.get(lobbyId) : undefined; + if (!l) throw new GameError(404, 'Lobby not found.'); + return l; + } + private player(input: { name: unknown; secret: unknown }): { player: Player; token: string } { + const name = typeof input.name === 'string' ? input.name.trim() : ''; + if (!NAME.test(name)) throw new GameError(400, 'Name must be 1-24 letters, digits, spaces, _ . or -'); + if (typeof input.secret !== 'string' || !SECRET.test(input.secret)) throw new GameError(400, 'Invalid player secret.'); + const id = createHash('sha256').update(`wikideck-player:${input.secret}`).digest('hex'); + const token = randomBytes(24).toString('base64url'); + return { player: { id, name, tokenHash: hashToken(token), seen: this.now() }, token }; + } + private seatFor(l: Lobby, token: string): Seat | null { + const h = hashToken(token); + const i = l.players.findIndex(p => timingSafeEqual(p.tokenHash, h)); + return i === 0 || i === 1 ? i : null; + } + private requireSeat(l: Lobby, token: string): Seat { + const s = typeof token === 'string' ? this.seatFor(l, token) : null; + if (s === null) throw new GameError(403, 'Not a player in this lobby.'); + return s; + } +} + +function hashToken(token: string): Buffer { return createHash('sha256').update(token).digest(); } diff --git a/server/game/index.ts b/server/game/index.ts new file mode 100644 index 0000000..44d094c --- /dev/null +++ b/server/game/index.ts @@ -0,0 +1,45 @@ +/** + * Entry point for the game-modes API. server/testnet/http.ts mounts it with one line: + * app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment })); + */ +import { join } from 'node:path'; +import type express from 'express'; +import { loadModes, hostIdentity, gamePeers } from './config.ts'; +import { ModeDiscovery } from './discovery.ts'; +import { ModeHost } from './host.ts'; +import { createGameRouter } from './router.ts'; +import { MatchStore } from './store.ts'; +import type { EnginePort } from './engine-port.ts'; +import { TrendCache } from './trends.ts'; + +type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> }; + +export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment; + engine?: EnginePort; env?: NodeJS.ProcessEnv; warmTrends?: boolean }): Promise { + const env = options.env ?? process.env; + const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding; + const modes = loadModes(env); + // Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match. + let trends: TrendCache | undefined; + if (options.enrichment && modes.some(m => m.cards.preset === 'trending')) { + const enrichment = options.enrichment; + // Wikipedia egress is shared and rate-limited: default one page per 20 s (≥ 15 s enforced). + const interval = Number(env.WIKIDECK_GAME_TREND_INTERVAL_MS ?? 20_000); + if (!Number.isSafeInteger(interval) || interval < 15_000 || interval > 3_600_000) throw new Error('WIKIDECK_GAME_TREND_INTERVAL_MS must be 15000..3600000'); + trends = new TrendCache(pageId => enrichment.get(pageId), { intervalMs: interval }); + for (const card of engine.starterDeck(engine.defaultRuleset, 'trend-warmup')) { + const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id); + } + for (const card of engine.previewPool(engine.defaultRuleset, 'trend-warmup', 64)) { + const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id); + } + if (options.warmTrends !== false) trends.start(); + } + const host = new ModeHost({ identity: hostIdentity(env), modes, engine, + store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null), + liveData: trends ? async pageId => trends!.get(pageId) : undefined }); + const discovery = new ModeDiscovery({ peers: gamePeers(env) }); + const timer = setInterval(() => host.sweep(), 5_000); + timer.unref(); + return createGameRouter(host, discovery); +} diff --git a/server/game/modes/classic.json b/server/game/modes/classic.json new file mode 100644 index 0000000..638ffe4 --- /dev/null +++ b/server/game/modes/classic.json @@ -0,0 +1,12 @@ +{ + "schema": "wikideck.mode/1", + "id": "classic", + "version": 1, + "name": "Classic", + "description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.", + "tags": ["base", "starter"], + "rules": {}, + "cards": { "preset": "standard" }, + "decks": { "kind": "starter" }, + "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 } +} diff --git a/server/game/modes/draft.json b/server/game/modes/draft.json new file mode 100644 index 0000000..9026074 --- /dev/null +++ b/server/game/modes/draft.json @@ -0,0 +1,28 @@ +{ + "schema": "wikideck.mode/1", + "id": "draft", + "version": 1, + "name": "Snake Draft", + "description": "Both players snake-draft 10-card decks from one shared, host-seeded pool of 30 preview cards, then play the base rules with a 4-card opening hand. Nobody brings cards, so everyone starts even.", + "tags": [ + "draft", + "no-collection" + ], + "rules": { + "deckSize": 10, + "openingHand": 4 + }, + "cards": { + "preset": "standard" + }, + "decks": { + "kind": "draft", + "poolSize": 30, + "pickSeconds": 30 + }, + "limits": { + "maxConcurrentMatches": 16, + "turnSeconds": 90, + "lobbyMinutes": 15 + } +} diff --git a/server/game/modes/trending.json b/server/game/modes/trending.json new file mode 100644 index 0000000..b8504c6 --- /dev/null +++ b/server/game/modes/trending.json @@ -0,0 +1,29 @@ +{ + "schema": "wikideck.mode/1", + "id": "trending", + "version": 1, + "name": "Trending", + "description": "Live Wikipedia pageview trends matter both ways: cards get the live trend arrow (up at +25%, down at -25%, where the base rules ignore falls), plus +1 power per 25% rise and -1 per 25% fall, capped at 3 either way.", + "tags": [ + "live-data", + "starter" + ], + "rules": { + "trendUp": 25, + "trendDown": -25 + }, + "cards": { + "preset": "trending", + "percentPerPoint": 25, + "maxBonus": 3, + "penalise": true + }, + "decks": { + "kind": "starter" + }, + "limits": { + "maxConcurrentMatches": 32, + "turnSeconds": 90, + "lobbyMinutes": 15 + } +} diff --git a/server/game/router.ts b/server/game/router.ts new file mode 100644 index 0000000..61865b9 --- /dev/null +++ b/server/game/router.ts @@ -0,0 +1,70 @@ +/** + * /api/game routes: publish, discover and host modes. Additive; nothing here reads or writes + * the ledger. Mounted by server/testnet/http.ts via server/game/index.ts. + */ +import express, { type Request, type Response, type NextFunction } from 'express'; +import rateLimit from 'express-rate-limit'; +import type { ModeHost } from './host.ts'; +import { GameError } from './host.ts'; +import type { ModeDiscovery } from './discovery.ts'; + +const limiter = (limit: number) => rateLimit({ windowMs: 60_000, limit, standardHeaders: 'draft-8', legacyHeaders: false }); + +export function createGameRouter(host: ModeHost, discovery: ModeDiscovery): express.Router { + const r = express.Router(); + const reads = limiter(240), writes = limiter(60), plays = limiter(240), network = limiter(30); + const wrap = (fn: (req: Request, res: Response) => unknown) => async (req: Request, res: Response, next: NextFunction) => { + try { const out = await fn(req, res); if (!res.headersSent) res.json(out); } catch (e) { next(e); } + }; + const bearer = (req: Request) => { + const h = req.get('authorization') ?? ''; + return /^Bearer [A-Za-z0-9_-]{16,64}$/.test(h) ? h.slice(7) : ''; + }; + const body = (req: Request) => (req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}) as Record; + + // Publish: this node's modes, host identity, stats. + r.get('/modes', reads, wrap(() => host.list())); + // Discover: this node plus every configured peer, as data. The browser opens a peer's own + // site to play there (CSP keeps API calls same-origin). + r.get('/network/modes', network, wrap(async () => { + const peers = await discovery.all(); + return { self: host.list(), peers: peers.map(p => ({ origin: p.origin, ok: p.ok, error: p.error ?? null, + fetchedAt: p.fetchedAt, rejectedModes: p.rejected ?? 0, list: p.list ?? null })) }; + })); + // Host leaderboard: matches hosted per node (self-reported by peers; see HOSTING.md). + r.get('/hosts/leaderboard', network, wrap(async () => { + const self = host.list(); + const rows = [{ ...summary(self), self: true, reachable: true }]; + for (const p of await discovery.all()) if (p.list) rows.push({ ...summary(p.list), self: false, reachable: p.ok }); + rows.sort((a, b) => b.matchesHosted - a.matchesHosted || a.origin.localeCompare(b.origin)); + return { hosts: rows }; + })); + r.get('/modes/:modeId/leaderboard', reads, wrap(req => host.leaderboard(String(req.params.modeId)))); + r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) }))); + r.post('/modes/:modeId/lobbies', writes, wrap((req, res) => { + const b = body(req); + res.status(201); + return host.createLobby(String(req.params.modeId), { name: b.name, secret: b.secret }); + })); + r.post('/lobbies/:lobbyId/join', writes, wrap(req => { + const b = body(req); + return host.join(String(req.params.lobbyId), { name: b.name, secret: b.secret }); + })); + r.get('/lobbies/:lobbyId', plays, wrap(req => host.view(String(req.params.lobbyId), bearer(req) || undefined))); + r.post('/lobbies/:lobbyId/pick', plays, wrap(req => host.pick(String(req.params.lobbyId), bearer(req), body(req).index))); + r.post('/lobbies/:lobbyId/actions', plays, wrap(req => host.act(String(req.params.lobbyId), bearer(req), body(req).action))); + r.post('/lobbies/:lobbyId/resign', writes, wrap(req => host.resign(String(req.params.lobbyId), bearer(req)))); + // Finished match records: seed, decks and action log, so anyone can replay and audit them. + r.get('/matches/:matchId', reads, wrap(req => host.matchRecord(String(req.params.matchId)))); + + r.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { + if (err instanceof GameError) { res.status(err.status).json({ error: err.message }); return; } + next(err); + }); + return r; +} + +function summary(list: { host: { origin: string; operator: string }; matchesHosted: number; modes: { stats: { playersOnline: number; distinctPlayers: number } }[] }) { + return { origin: list.host.origin, operator: list.host.operator, matchesHosted: list.matchesHosted, + modes: list.modes.length, playersOnline: list.modes.reduce((n, m) => n + m.stats.playersOnline, 0) }; +} diff --git a/server/game/store.ts b/server/game/store.ts new file mode 100644 index 0000000..0aab964 --- /dev/null +++ b/server/game/store.ts @@ -0,0 +1,87 @@ +/** + * Off-chain match records for this node: an append-only JSON-lines file plus in-memory + * aggregates (leaderboards, host totals). Nothing here touches the ledger. + */ +import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { z } from 'zod'; + +export const MatchRecordSchema = z.object({ + matchId: z.string().regex(/^[a-f0-9]{32}$/), + modeId: z.string().max(40), + modeVersion: z.number().int(), + /** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */ + seed: z.string().max(128), + /** The resolved ruleset the match ran under (mode overrides already applied). */ + rules: z.unknown(), + players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24) }).strict()).length(2), + winner: z.union([z.literal(0), z.literal(1), z.null()]), + reason: z.string().max(40), + startedAt: z.number().int(), + endedAt: z.number().int(), + decks: z.array(z.array(z.unknown()).max(64)).length(2), + actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000), +}).strict(); +export type MatchRecord = z.infer; + +export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number }; +type ModeAgg = { matches: number; players: Map }; + +const KEEP_RECENT = 500; + +export class MatchStore { + private readonly file: string | null; + private readonly modes = new Map(); + private readonly recent = new Map(); + private readonly allPlayers = new Set(); + total = 0; + + /** `directory` null keeps records in memory only (tests). */ + constructor(directory: string | null) { + this.file = directory ? join(directory, 'matches.jsonl') : null; + if (!directory || !this.file) return; + mkdirSync(directory, { recursive: true, mode: 0o700 }); + if (!existsSync(this.file)) return; + for (const line of readFileSync(this.file, 'utf8').split('\n')) { + if (!line.trim()) continue; + const parsed = MatchRecordSchema.safeParse(safeJson(line)); + if (parsed.success) this.index(parsed.data); // A torn last line after a crash is skipped. + } + } + + add(record: MatchRecord): void { + const valid = MatchRecordSchema.parse(record); + if (this.file) appendFileSync(this.file, JSON.stringify(valid) + '\n', { mode: 0o600 }); + this.index(valid); + } + + get(matchId: string): MatchRecord | undefined { return this.recent.get(matchId); } + + modeMatches(modeId: string): number { return this.modes.get(modeId)?.matches ?? 0; } + modePlayers(modeId: string): number { return this.modes.get(modeId)?.players.size ?? 0; } + distinctPlayers(): number { return this.allPlayers.size; } + + leaderboard(modeId: string, limit = 20): LeaderboardEntry[] { + const players = [...(this.modes.get(modeId)?.players.values() ?? [])]; + return players.sort((a, b) => b.wins - a.wins || a.losses - b.losses || b.played - a.played || + a.playerId.localeCompare(b.playerId)).slice(0, limit).map(p => ({ ...p })); + } + + private index(r: MatchRecord): void { + this.total++; + const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() }; + this.modes.set(r.modeId, agg); + agg.matches++; + r.players.forEach((p, seat) => { + this.allPlayers.add(p.id); + const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0 }; + e.name = p.name; e.played++; + if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++; + agg.players.set(p.id, e); + }); + this.recent.set(r.matchId, r); + if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!); + } +} + +function safeJson(line: string): unknown { try { return JSON.parse(line); } catch { return null; } } diff --git a/server/game/trends.ts b/server/game/trends.ts new file mode 100644 index 0000000..3da6059 --- /dev/null +++ b/server/game/trends.ts @@ -0,0 +1,58 @@ +/** + * Live pageview trends for `trending` modes, read from cache only at match time. + * Wikipedia egress is shared and rate-limited, so lookups never happen in a request path: + * unknown pages are queued and fetched one at a time, slowly, through the node's existing + * enrichment cache. Until a page is warm, its cards simply get no trend bonus. + */ +import type { LiveCardData } from '../../shared/game/modes.ts'; + +type Source = (pageId: number) => Promise<{ pageviews: { trendPercent: number | null } }>; + +export class TrendCache { + private readonly values = new Map(); + private readonly queue: number[] = []; + private readonly queued = new Set(); + private timer: ReturnType | undefined; + private busy = false; + + private readonly source: Source; + private readonly options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number }; + constructor(source: Source, options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number } = {}) { + this.source = source; this.options = options; + } + + /** Cache-only lookup; schedules a background fetch when missing or stale. */ + get(pageId: number): LiveCardData | null { + const v = this.values.get(pageId); + const now = (this.options.now ?? Date.now)(); + if (!v || now - v.at > (this.options.ttlMs ?? 6 * 3600_000)) this.enqueue(pageId); + return v ? { trendPercent: v.trend } : null; + } + + enqueue(pageId: number): void { + if (!Number.isSafeInteger(pageId) || pageId <= 0 || this.queued.has(pageId) || this.queue.length >= 256) return; + this.queued.add(pageId); this.queue.push(pageId); + } + + start(): void { + if (this.timer) return; + this.timer = setInterval(() => void this.step(), this.options.intervalMs ?? 20_000); + this.timer.unref(); + } + stop(): void { if (this.timer) clearInterval(this.timer); this.timer = undefined; } + + /** Fetch at most one page. Exposed for tests. */ + async step(): Promise { + if (this.busy) return; + const pageId = this.queue.shift(); + if (pageId === undefined) return; + this.busy = true; + try { + const data = await this.source(pageId); + const trend = data.pageviews.trendPercent; + this.values.set(pageId, { trend: typeof trend === 'number' && Number.isFinite(trend) ? trend : null, at: (this.options.now ?? Date.now)() }); + while (this.values.size > (this.options.maxEntries ?? 512)) this.values.delete(this.values.keys().next().value!); + } catch { /* Leave it cold; it is re-queued on a later lookup. */ } + finally { this.queued.delete(pageId); this.busy = false; } + } +} diff --git a/server/testnet/http.ts b/server/testnet/http.ts index 272bde9..be6d366 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -151,6 +151,7 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{ res.status(202).json({id,status:'pending'}); }); app.use('/api/account',createAccountRouter({dataDir})); +app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment})); app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});}); app.use(express.static(resolve(root,'dist'))); app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html'))); diff --git a/shared/game/modes.ts b/shared/game/modes.ts new file mode 100644 index 0000000..67ff582 --- /dev/null +++ b/shared/game/modes.ts @@ -0,0 +1,230 @@ +/** + * Peer-hosted game modes: a mode is DATA, never code. + * + * A mode is a small JSON document: base-rule overrides (applied on top of the engine's + * default `Ruleset` and re-validated by the engine's own ruleset parser), a card-mapping + * preset chosen from a fixed list, a deck policy, limits, and display text. + * A peer never executes, evals or imports anything another peer sends; it only parses + * this schema with hard size limits. See docs/game/HOSTING.md. + * + * No I/O here: shared by the server (host + discovery) and the browser (lobby). + */ +import { z } from 'zod'; + +export const MODE_SCHEMA_VERSION = 'wikideck.mode/1' as const; +/** Upper bound on the JSON size of one mode document, before parsing. */ +export const MAX_MODE_BYTES = 8 * 1024; +/** Upper bound on modes one node may publish (and that discovery accepts from one peer). */ +export const MAX_MODES_PER_NODE = 16; +/** Upper bound on the JSON size of a whole /api/game/modes response read from a peer. */ +export const MAX_MODE_LIST_BYTES = 192 * 1024; + +const slug = z.string().regex(/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/, 'lowercase slug, 3-40 chars'); +/** Plain display text: no control characters, no angle brackets (rendered as text anyway). */ +const text = (max: number) => z.string().trim().min(1).max(max) + .refine(s => !/[\u0000-\u001f\u007f<>]/.test(s), 'plain text only'); + +/** + * Rule overrides: a shallow-ish, bounded JSON object of numbers, booleans, short strings and + * short arrays of those. Its *meaning* is decided by the engine's ruleset schema, which runs + * after the merge (see `resolveRuleset`). This schema only guarantees it is small and inert. + */ +const scalar = z.union([z.number().finite(), z.boolean(), z.string().max(64)]); +const leaf = z.union([scalar, z.array(scalar).max(32)]); +const level2 = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/), leaf) + .refine(o => Object.keys(o).length <= 32, 'too many keys'); +export const RuleOverridesSchema = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/), + z.union([leaf, level2])).refine(o => Object.keys(o).length <= 48, 'too many rule overrides'); +export type RuleOverrides = z.infer; + +/** + * How Wikipedia data becomes card numbers in this mode. A fixed list of presets implemented + * in this file; a mode only picks one and tunes bounded parameters. + * - `standard`: the engine's default mapping from the immutable at-mint snapshot. + * - `live`: the same mapping, but from live current values when available. + * - `trending`: standard, plus a power bonus/penalty from live `pageviews.trendPercent`. + */ +export const CardMappingSchema = z.discriminatedUnion('preset', [ + z.object({ preset: z.literal('standard') }).strict(), + z.object({ preset: z.literal('live') }).strict(), + z.object({ preset: z.literal('trending'), + /** Trend percent per +1 power (e.g. 25 → +25% trend gives +1). */ + percentPerPoint: z.number().int().min(5).max(500).default(25), + /** Clamp on the bonus, in either direction. */ + maxBonus: z.number().int().min(0).max(5).default(3), + /** Whether falling trends reduce power (never below 0). */ + penalise: z.boolean().default(true), + }).strict(), +]); +export type CardMapping = z.infer; + +/** Where match decks come from. Matches never move or burn NFTs, whatever the policy. */ +export const DeckPolicySchema = z.discriminatedUnion('kind', [ + /** Each player brings a deck (starter deck or own cards, validated by the engine). */ + z.object({ kind: z.literal('constructed'), allowStarter: z.boolean().default(true) }).strict(), + /** Host-seeded starter decks only: everyone gets the engine's `starterDeck(seed)`. */ + z.object({ kind: z.literal('starter') }).strict(), + /** Snake draft from a host-seeded pool of non-NFT preview cards. */ + z.object({ kind: z.literal('draft'), + /** Cards in the shared pool; must be at least 2 × the ruleset's deck size. */ + poolSize: z.number().int().min(8).max(64).default(30), + /** Seconds per pick before the host auto-picks the first card. */ + pickSeconds: z.number().int().min(5).max(120).default(30), + }).strict(), +]); +export type DeckPolicy = z.infer; + +export const ModeLimitsSchema = z.object({ + /** Concurrent open lobbies + live matches this mode may hold on the host. */ + maxConcurrentMatches: z.number().int().min(1).max(256).default(32), + /** Seconds a player may take for one action before forfeiting the turn/match. */ + turnSeconds: z.number().int().min(10).max(600).default(90), + /** Lobbies with no opponent expire after this many minutes. */ + lobbyMinutes: z.number().int().min(1).max(120).default(15), +}).strict(); +export type ModeLimits = z.infer; + +/** The mode document an operator writes (and peers publish). */ +export const ModeSchema = z.object({ + schema: z.literal(MODE_SCHEMA_VERSION), + id: slug, + /** Monotonic integer; bump when the rules change so old match records stay attributable. */ + version: z.number().int().min(1).max(1_000_000), + name: text(48), + description: text(400), + tags: z.array(slug).max(5).default([]), + /** Overrides on top of the engine's DEFAULT_RULESET. */ + rules: RuleOverridesSchema.default({}), + cards: CardMappingSchema.default({ preset: 'standard' }), + decks: DeckPolicySchema.default({ kind: 'constructed', allowStarter: true }), + limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15 }), +}).strict(); +export type ModeDocument = z.infer; +export type ModeInput = z.input; + +/** + * The host's identity, configured by the node operator (never taken from a mode file). + * Discovery overwrites `origin` with the URL it actually fetched, so a peer can't + * publish modes in another node's name. + */ +export const HostIdentitySchema = z.object({ + origin: z.string().url().max(256), + operator: text(48), + /** Optional short note, e.g. "EU, best effort". */ + note: text(120).optional(), +}).strict(); +export type HostIdentity = z.infer; + +export const ModeStatsSchema = z.object({ + playersOnline: z.number().int().min(0).max(1_000_000), + openLobbies: z.number().int().min(0).max(1_000_000), + liveMatches: z.number().int().min(0).max(1_000_000), + matchesPlayed: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), + distinctPlayers: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), +}).strict(); +export type ModeStats = z.infer; + +/** One entry of GET /api/game/modes. */ +export const PublishedModeSchema = z.object({ mode: ModeSchema, stats: ModeStatsSchema }).strict(); +export type PublishedMode = z.infer; + +/** Body of GET /api/game/modes. */ +export const ModeListSchema = z.object({ + schema: z.literal(MODE_SCHEMA_VERSION), + host: HostIdentitySchema, + /** Total matches this node has hosted, across all its modes and versions. */ + matchesHosted: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), + modes: z.array(PublishedModeSchema).max(MAX_MODES_PER_NODE), +}).strict(); +export type ModeList = z.infer; + +/** Parse untrusted mode JSON text with a byte limit before JSON.parse. */ +export function parseModeJson(json: string): ModeDocument { + if (byteLength(json) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`); + return parseMode(JSON.parse(json)); +} +export function parseMode(value: unknown): ModeDocument { + assertInertKeys(value); + const mode = ModeSchema.parse(value); + if (byteLength(JSON.stringify(mode)) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`); + return mode; +} +/** Parse an untrusted peer's mode list. Invalid individual modes are dropped, not fatal. */ +export function parseModeList(json: string): { list: ModeList; rejected: number } { + if (byteLength(json) > MAX_MODE_LIST_BYTES) throw new Error('Mode list too large'); + const raw = z.object({ modes: z.array(z.unknown()).max(MAX_MODES_PER_NODE) }).passthrough().parse(JSON.parse(json)); + let rejected = 0; + const modes: PublishedMode[] = []; + for (const entry of raw.modes) { + const parsed = hasForbiddenKeys(entry) ? null : PublishedModeSchema.safeParse(entry); + if (parsed?.success && byteLength(JSON.stringify(parsed.data.mode)) <= MAX_MODE_BYTES) modes.push(parsed.data); + else rejected++; + } + return { list: ModeListSchema.parse({ ...raw, modes }), rejected }; +} + +/** Stable key for a mode on a host: `#@`. */ +export function modeKey(origin: string, mode: Pick): string { + return `${origin}#${mode.id}@${mode.version}`; +} + +const BLOCKED_KEYS = new Set(['__proto__', 'prototype', 'constructor']); +/** + * Merge overrides onto the engine's base ruleset, then validate with the engine's parser. + * Objects merge one level deep; arrays and scalars replace. Unknown keys are left for the + * engine parser to reject (it is strict), so a mode can never smuggle in unchecked rules. + */ +export function resolveRuleset(base: R, overrides: RuleOverrides, parse: (value: unknown) => R): R { + const merged: Record = structuredClone(base) as Record; + for (const [key, value] of Object.entries(overrides)) { + if (BLOCKED_KEYS.has(key)) throw new Error('Forbidden rule key'); + const current = merged[key]; + if (isPlainObject(value) && isPlainObject(current)) { + const inner: Record = { ...current }; + for (const [k, v] of Object.entries(value)) { + if (BLOCKED_KEYS.has(k)) throw new Error('Forbidden rule key'); + inner[k] = v; + } + merged[key] = inner; + } else merged[key] = value; + } + return parse(merged); +} + +/** Live Wikipedia trend data a card mapping may read (subset of PageEnrichment). */ +export type LiveCardData = { trendPercent: number | null }; + +/** + * Apply the mode's card-mapping preset to a card's base power. Pure and bounded. + * `standard`/`live` differ only in which stats the caller fed the engine's card builder. + */ +export function mappedPower(basePower: number, mapping: CardMapping, live?: LiveCardData): number { + if (mapping.preset !== 'trending') return basePower; + return basePower + trendBonus(mapping, live?.trendPercent ?? null); +} +export function trendBonus(mapping: Extract, trendPercent: number | null): number { + if (trendPercent === null || !Number.isFinite(trendPercent)) return 0; + let bonus = Math.trunc(trendPercent / mapping.percentPerPoint); + if (!mapping.penalise) bonus = Math.max(0, bonus); + return Math.max(-mapping.maxBonus, Math.min(mapping.maxBonus, bonus)); +} + +/** Clamp a mapped power the same way regardless of preset: never negative. */ +export function clampPower(power: number): number { return Math.max(0, Math.round(power)); } + +/** Reject prototype-polluting keys anywhere (zod's record() does not check them reliably). */ +function hasForbiddenKeys(value: unknown, depth = 0): boolean { + if (depth > 8 || typeof value !== 'object' || value === null) return depth > 8; + for (const key of Object.keys(value)) { + if (BLOCKED_KEYS.has(key)) return true; + if (hasForbiddenKeys((value as Record)[key], depth + 1)) return true; + } + return false; +} +function assertInertKeys(value: unknown): void { + if (hasForbiddenKeys(value)) throw new Error('Forbidden key in mode document'); +} +function isPlainObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} +function byteLength(s: string): number { return new TextEncoder().encode(s).length; } diff --git a/src/App.tsx b/src/App.tsx index b98fe80..33bca03 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,7 @@ import { LoginButton } from './auth/LoginButton.tsx'; import { TradeDesk } from './TradeDesk.tsx'; import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts'; import { StateClient } from '../shared/rpc-client.ts'; +import { isNativeApp } from './native.ts'; import './App.css'; import './testnet.css'; @@ -186,7 +187,7 @@ export default function App() {
Confirmed ownership{wallet && snapshot ? owned.length : '—'}in your wallet
Proof of work{snapshot?.algorithm ?? 'RandomX'}native CPU mining
-
+ diff --git a/src/auth/session.ts b/src/auth/session.ts index 6de057d..811febd 100644 --- a/src/auth/session.ts +++ b/src/auth/session.ts @@ -44,8 +44,19 @@ export async function pkceChallenge(verifier: string): Promise { return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))); } -type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: { open(o: { url: string }): Promise; close?(): Promise } } }; +type NativeBrowser = { open(o: { url: string }): Promise; close?(): Promise }; +type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: NativeBrowser } }; const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor; +let nativeBrowser: NativeBrowser | undefined; +/** + * Native apps: pass the imported `@capacitor/browser` plugin so login opens in the system + * browser (Custom Tab / SFSafariViewController), never inside the WebView. Example (src/native.ts): + * import { Browser } from '@capacitor/browser'; + * setNativeBrowser(Browser); + * onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); }); + */ +export function setNativeBrowser(browser: NativeBrowser): void { nativeBrowser = browser; } +const browserPlugin = () => nativeBrowser ?? capacitor()?.Plugins?.Browser; export const isNative = () => Boolean(capacitor()?.isNativePlatform?.()); export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; } @@ -77,9 +88,11 @@ export async function login(returnTo = location.pathname + location.search): Pro scope: config.scopes, state: pending.state, nonce: pending.nonce, code_challenge: await pkceChallenge(pending.verifier), code_challenge_method: 'S256' }).toString(); // Capacitor: system browser (never a WebView) + custom-scheme redirect, per RFC 8252. - const browser = capacitor()?.Plugins?.Browser; - if (isNative() && browser) await browser.open({ url: url.toString() }); - else location.assign(url.toString()); + const browser = browserPlugin(); + if (isNative()) { + if (!browser) throw new Error('System browser unavailable: the app must call setNativeBrowser(Browser).'); + await browser.open({ url: url.toString() }); + } else location.assign(url.toString()); } export const isCallback = (url: string) => { @@ -101,7 +114,7 @@ export async function completeLogin(url: string): Promise<{ returnTo: string }> const s = await api('token', { method: 'POST', body: JSON.stringify({ code, codeVerifier: pending.verifier, redirectUri: pending.redirectUri, nonce: pending.nonce }) }); save(s); - if (isNative()) void capacitor()?.Plugins?.Browser?.close?.().catch(() => {}); + if (isNative()) void browserPlugin()?.close?.().catch(() => {}); return { returnTo: pending.returnTo }; } diff --git a/src/main.tsx b/src/main.tsx index 3d89c70..e1c7802 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,3 +1,4 @@ +import './native.ts'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.tsx'; diff --git a/src/native.css b/src/native.css new file mode 100644 index 0000000..6b62bd3 --- /dev/null +++ b/src/native.css @@ -0,0 +1,11 @@ +/* Native app (Capacitor) only: html.native-app is set by src/native.ts. */ +.native-app [hidden] { display: none !important; } +/* RandomX mining is desktop-only: hide the mining pillar on the home page. */ +.native-app .project-pillars > article:first-child { display: none; } +/* Keep content clear of the status bar, notch and gesture bar. */ +.native-app body { + padding-top: env(safe-area-inset-top); + padding-bottom: env(safe-area-inset-bottom); + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); +} diff --git a/src/native.ts b/src/native.ts new file mode 100644 index 0000000..c20bdad --- /dev/null +++ b/src/native.ts @@ -0,0 +1,87 @@ +// Native (Capacitor) app glue. Import this first in main.tsx, before anything that captures `fetch`. +// On the web it does nothing: relative `/api/...` requests keep going to the serving origin. +import { Capacitor } from '@capacitor/core'; +import { App } from '@capacitor/app'; +import './native.css'; + +/** True inside the Android/iOS app shell. Use it to hide desktop-only features such as RandomX mining. */ +export const isNativeApp = (): boolean => Capacitor.isNativePlatform(); + +const NODE_URL_KEY = 'wikideck.nodeUrl'; +/** Private Night-1 testnet node (poweredge-r350, LAN only). */ +export const TESTNET_NODE_URL = 'http://192.168.1.32:3101'; +/** Build-time override, e.g. VITE_NODE_URL=http://192.168.1.32:3102. Only used by the native app. */ +const DEFAULT_NODE_URL: string = import.meta.env.VITE_NODE_URL || TESTNET_NODE_URL; + +const clean = (url: string) => url.trim().replace(/\/+$/, ''); + +/** Base URL of the WikiDeck node the app talks to ('' means same origin). */ +export function nodeUrl(): string { + if (!isNativeApp()) return ''; + try { return clean(localStorage.getItem(NODE_URL_KEY) ?? DEFAULT_NODE_URL); } catch { return clean(DEFAULT_NODE_URL); } +} + +/** Override the node URL at runtime (native only); pass '' to go back to the build default. */ +export function setNodeUrl(url: string): void { + const value = clean(url); + if (value && !/^https?:\/\/[^/]+$/.test(value)) throw new Error('Node URL must look like http(s)://host[:port]'); + if (value) localStorage.setItem(NODE_URL_KEY, value); else localStorage.removeItem(NODE_URL_KEY); +} + +/** Absolute URL for a node path such as `/api/state` or `/auth/callback`. */ +export const nodeHref = (path: string): string => `${nodeUrl()}${path}`; + +// In the app, rewrite relative node requests (`/api/...`, `/auth/...`) to the configured node. +// With CapacitorHttp enabled (capacitor.config.ts) the request then goes through the native HTTP +// stack: no CORS, and no WebView `Origin` header for the node's POST origin check to reject. +if (isNativeApp()) { + // src/auth (sso) reads this to reach the node for /api/account/... calls. + (globalThis as { WIKIDECK_NODE_URL?: string }).WIKIDECK_NODE_URL = nodeUrl(); + document.documentElement.classList.add('native-app', `native-${Capacitor.getPlatform()}`); + const original = globalThis.fetch.bind(globalThis); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (typeof input === 'string' && /^\/(api|auth)\//.test(input)) input = nodeHref(input); + const response = await original(input, init); + // Capacitor's Android HTTP interceptor merges headers, e.g. `content-length: 0, 384`, which the + // RPC client's strict size check rejects. Drop the merged length; clients still cap bytes while streaming. + const length = response.headers.get('content-length'); + if (length === null || /^\d+$/.test(length)) return response; + const headers = new Headers(response.headers); + headers.delete('content-length'); + return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); + }) as typeof fetch; +} + +// Android back button: close an open dialog first (the UI closes dialogs on Escape), then go back +// in history, and only then leave the app (minimize, so wallet state in memory survives). +if (isNativeApp()) { + void App.addListener('backButton', ({ canGoBack }) => { + if (document.querySelector('[role="dialog"]')) { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + } else if (canGoBack) window.history.back(); + else void App.minimizeApp(); + }); +} + +type DeepLinkHandler = (url: URL) => void; +const deepLinkHandlers = new Set(); +let pendingDeepLink: URL | undefined; +/** + * Subscribe to app deep links such as the SSO redirect `dev.eom.wikideck:/oauth/callback?code=...&state=...`. + * A link that arrived before anyone subscribed (cold start) is delivered on subscribe. Returns an unsubscribe. + */ +export function onDeepLink(handler: DeepLinkHandler): () => void { + deepLinkHandlers.add(handler); + if (pendingDeepLink) { const url = pendingDeepLink; pendingDeepLink = undefined; handler(url); } + return () => { deepLinkHandlers.delete(handler); }; +} +/** Redirect URI for the native SSO flow (registered with Dex by the sso team). */ +export const NATIVE_REDIRECT_URI = 'dev.eom.wikideck:/oauth/callback'; +if (isNativeApp()) { + void App.addListener('appUrlOpen', ({ url }) => { + let parsed: URL; + try { parsed = new URL(url); } catch { return; } + if (parsed.protocol !== 'dev.eom.wikideck:') return; + if (deepLinkHandlers.size) deepLinkHandlers.forEach(h => h(parsed)); else pendingDeepLink = parsed; + }); +} diff --git a/tests/account-native.test.ts b/tests/account-native.test.ts new file mode 100644 index 0000000..342065f --- /dev/null +++ b/tests/account-native.test.ts @@ -0,0 +1,33 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +// Capacitor: login must open the system browser with the custom-scheme redirect, never the WebView. +test('account native: login opens the system browser with PKCE and the app redirect', async () => { + const g = globalThis as Record; + const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage, fetch: g.fetch, location: g.location }; + const store = new Map(); + g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); }, + removeItem: (k: string) => { store.delete(k); } }; + g.Capacitor = { isNativePlatform: () => true, Plugins: {} }; + let assigned = ''; + g.location = { origin: 'https://localhost', pathname: '/', search: '', assign: (u: string) => { assigned = u; } }; + g.fetch = (async () => new Response(JSON.stringify({ issuer: 'https://dex.eom.dev/', clientId: 'wikideck', + scopes: 'openid profile email groups', authorizationEndpoint: 'https://dex.eom.dev/auth', + redirectUris: ['dev.eom.wikideck:/oauth/callback'] }), { headers: { 'content-type': 'application/json' } })) as typeof fetch; + try { + const auth = await import('../src/auth/session.ts'); + await assert.rejects(auth.login(), /setNativeBrowser/); + assert.equal(assigned, '', 'never navigates the WebView to Dex'); + const opened: string[] = []; + auth.setNativeBrowser({ open: async ({ url }) => { opened.push(url); } }); + await auth.login(); + const url = new URL(opened[0]); + assert.equal(url.origin + url.pathname, 'https://dex.eom.dev/auth'); + assert.equal(url.searchParams.get('redirect_uri'), 'dev.eom.wikideck:/oauth/callback'); + assert.equal(url.searchParams.get('code_challenge_method'), 'S256'); + assert.equal(url.searchParams.get('client_id'), 'wikideck'); + const pending = JSON.parse(store.get('wikideck.auth.pending')!); + assert.equal(url.searchParams.get('state'), pending.state); + assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true); + } finally { Object.assign(g, saved); } +}); diff --git a/tests/modes-api.test.ts b/tests/modes-api.test.ts new file mode 100644 index 0000000..4cc4faa --- /dev/null +++ b/tests/modes-api.test.ts @@ -0,0 +1,209 @@ +// End to end over HTTP with the real engine: publish, discover, host all three example modes. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import express from 'express'; +import type { AddressInfo } from 'node:net'; +import { gameRouter } from '../server/game/index.ts'; +import { previewPool } from '../server/game/engine-binding.ts'; +import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts'; +import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts'; +import { ModeListSchema } from '../shared/game/modes.ts'; + +async function serve(env: NodeJS.ProcessEnv, enrichment?: any) { + const app = express(); + app.use(express.json({ limit: '68kb' })); + app.use('/api/game', await gameRouter({ dataDir: null, env, enrichment })); + app.use((err: Error, _q: express.Request, res: express.Response, _n: express.NextFunction) => res.status(400).json({ error: err.message })); + const server = app.listen(0, '127.0.0.1'); + await new Promise(r => server.once('listening', r)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + return { base, close: () => new Promise(r => server.close(r)) }; +} +const call = async (base: string, path: string, body?: unknown, token?: string) => { + const res = await fetch(base + path, { method: body === undefined ? 'GET' : 'POST', + headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: res.status, json: await res.json() as any }; +}; +const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' }; +const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' }; + +async function playToEnd(base: string, lobby: string, tokens: string[]) { + for (let i = 0; i < 400; i++) { + let moved = false; + for (const t of tokens) { + const v = (await call(base, `/api/game/lobbies/${lobby}`, undefined, t)).json; + if (v.phase !== 'playing') return v; + // Play the first card if possible, else end the turn. + const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'commit'); + if (a) { const r = await call(base, `/api/game/lobbies/${lobby}/actions`, { action: a }, t); assert.equal(r.status, 200, JSON.stringify(r.json)); moved = true; } + } + if (!moved) break; + } + return (await call(base, `/api/game/lobbies/${lobby}`, undefined, tokens[0])).json; +} + +test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => { + const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', + WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' }, + { get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) }); + try { + const list = (await call(node.base, '/api/game/modes')).json; + ModeListSchema.parse(list); + assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']); + assert.equal(list.host.operator, 'Node A'); + + for (const id of ['classic', 'trending']) { + const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice); + assert.equal(a.status, 201); + const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob); + assert.equal(b.status, 200, JSON.stringify(b.json)); + const peek = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`)).json; + assert.equal(peek.state, undefined); + const wrongSeat = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`, undefined, a.json.token)).json.legalActions[0]; + const cheat = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/actions`, { action: { ...wrongSeat, player: 1 } }, a.json.token); + assert.equal(cheat.status, 400, 'cannot act for the other seat'); + const end = await playToEnd(node.base, a.json.lobbyId, [a.json.token, b.json.token]); + assert.equal(end.phase, 'finished', JSON.stringify(end).slice(0, 300)); + const rec = (await call(node.base, `/api/game/matches/${end.matchId}`)).json; + assert.equal(rec.modeId, id); + assert.equal(rec.decks[0].length, 12); + } + + // Draft: 20 snake picks, 10-card decks. + const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json; + const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json; + const tokens = [a.token, b.token]; + let picks = 0; + for (;;) { + const v = (await call(node.base, `/api/game/lobbies/${a.lobbyId}`, undefined, a.token)).json; + if (v.phase !== 'drafting') { assert.equal(v.phase, 'playing'); break; } + const free = v.draft.pool.find((c: any) => c.takenBy === null); + const r = await call(node.base, `/api/game/lobbies/${a.lobbyId}/pick`, { index: free.index }, tokens[v.draft.toPick]); + assert.equal(r.status, 200, JSON.stringify(r.json)); + picks++; + } + assert.equal(picks, 20); + const end = await playToEnd(node.base, a.lobbyId, tokens); + assert.equal(end.phase, 'finished'); + const record = (await call(node.base, `/api/game/matches/${end.matchId}`)).json; + assert.equal(record.decks[1].length, 10); + // Anyone can audit a match: replaying the published record reproduces the result. + const replayed = replay(record.rules, record.decks, record.seed, record.actions.map((a: any) => a.action)); + assert.equal(replayed.phase, 'over'); + assert.equal(replayed.result?.winner ?? null, record.winner); + + const after = (await call(node.base, '/api/game/modes')).json; + assert.equal(after.matchesHosted, 3); + const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json; + assert.equal(board.entries.length, 2); + assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404); + assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404); + } finally { await node.close(); } +}); + +test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => { + const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' }); + const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A', + WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' }); + try { + // One match on B so it leads the host leaderboard. + const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json; + const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json; + await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match + const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json; + const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json; + assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0); + const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json; + const rec = (await call(peerB.base, `/api/game/matches/${resigned.matchId}`)).json; + assert.equal(replay(rec.rules, rec.decks, rec.seed, rec.actions.map((x: any) => x.action)).result?.winner, 0, 'resign replays as concede'); + const net = (await call(nodeA.base, '/api/game/network/modes')).json; + assert.equal(net.self.host.operator, 'Node A'); + assert.equal(net.peers.length, 2); + assert.equal(net.peers[0].ok, true); + assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer'); + assert.equal(net.peers[0].list.modes[0].mode.id, 'draft'); + assert.equal(net.peers[1].ok, false); + const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts; + assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]); + } finally { await nodeA.close(); await peerB.close(); } +}); + +test('modes api: draft preview pool is deterministic and deck-legal', () => { + const p1 = previewPool(DEFAULT_RULESET, 'seed', 30), p2 = previewPool(DEFAULT_RULESET, 'seed', 30); + assert.deepEqual(p1, p2); + assert.equal(p1.length, 30); + assert.equal(new Set(p1.map(c => c.cardId)).size, 30); + assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage); +}); + +test('modes api: the rule examples in HOSTING.md are valid modes', () => { + for (const rules of [ + { turns: 4, energyByTurn: [3, 4, 5, 6] }, + { onTopicBonus: [0, 2, 2, 3, 3, 4, 4], trendUp: 10, trendDown: -10 }, + { deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 }, + { turns: 6, turnSeconds: 40 }, + ]) { + const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules }); + assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules)); + } +}); + +test('modes api: mode rules that make starter decks illegal fail at startup; live trend arrows follow the ruleset', async () => { + const { ModeHost } = await import('../server/game/host.ts'); + const { MatchStore } = await import('../server/game/store.ts'); + const { engineBinding } = await import('../server/game/engine-binding.ts'); + const big = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'big', version: 1, name: 'Big', description: 'x', + decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } }); + assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding, + store: new MatchStore(null) }), /starter decks are illegal/); + const card = engineBinding.starterDeck(DEFAULT_RULESET, 's')[0]!; + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 30 }).trend, 1); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: DEFAULT_RULESET.trendDown - 1 }).trend, -1); + assert.equal(engineBinding.applyLive!({ ...DEFAULT_RULESET, trendDown: -25 }, card, { trendPercent: -30 }).trend, -1); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 5 }).trend, 0); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: null }).trend, 0); + assert.equal(engineBinding.withPower(card, 99).power, 30, 'power stays within engine bounds'); +}); + +test('modes api: turn timer applies the engine timeout action; AFK forfeits are replayable', async () => { + const { ModeHost } = await import('../server/game/host.ts'); + const { MatchStore } = await import('../server/game/store.ts'); + const { engineBinding } = await import('../server/game/engine-binding.ts'); + let now = 0; + const classic = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }); + const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding, + store: new MatchStore(null), now: () => now }); + const a = host.createLobby('classic', alice); + const b = await host.join(a.lobbyId, bob); + // Bob plays normally; Alice never acts. + for (let turn = 0; turn < 6; turn++) { + const v = host.view(a.lobbyId, b.token) as any; + if (v.phase !== 'playing') break; + await host.act(a.lobbyId, b.token, { type: 'commit', player: 1 }); + now += (DEFAULT_RULESET.turnSeconds + 6) * 1000; host.sweep(); + } + const end = host.view(a.lobbyId, a.token) as any; + assert.equal(end.phase, 'finished'); + assert.deepEqual(end.outcome, { winner: 1, reason: 'afk' }); + const rec = host.matchRecord(end.matchId); + assert.ok(rec.actions.some(x => (x.action as any).type === 'timeout')); + assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner, 1); +}); + +test('modes api: mode rules are checked beyond the engine schema and rejected, not passed on', async () => { + const { parseModeRuleset } = await import('../server/game/engine-binding.ts'); + const bad = [ + { turns: 2, energyByTurn: [1, 2] }, // portalReveal has a turn > 2 + { distinctStats: true, topicCount: 2, portalReveal: [1, 2] }, + { turns: 12, turnSeconds: 25, energyByTurn: Array(12).fill(3), portalReveal: [1, 2, 3] }, + { powerByCost: [0, 1, 2] }, + { mulligan: true }, + { keywordParams: { notAKeyword: { amount: 1 } } }, + { keywordsEnabled: [...DEFAULT_RULESET.keywordsEnabled, 'obscure'] }, + ]; + for (const rules of bad) assert.throws(() => resolveRuleset(DEFAULT_RULESET, rules as any, parseModeRuleset), JSON.stringify(rules)); + assert.throws(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'obscure'] }, parseModeRuleset), /not hostable/); + assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset)); + assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset)); +}); diff --git a/tests/modes-host.test.ts b/tests/modes-host.test.ts new file mode 100644 index 0000000..7e51bbf --- /dev/null +++ b/tests/modes-host.test.ts @@ -0,0 +1,196 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts'; +import { ModeHost, GameError } from '../server/game/host.ts'; +import { MatchStore } from '../server/game/store.ts'; +import { ModeDiscovery } from '../server/game/discovery.ts'; +import { stubEngine } from './modes-stub-engine.ts'; + +const mode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'stub', version: 1, name: 'Stub', + description: 'Stub mode.', decks: { kind: 'starter' }, ...over }); +const identity = { origin: 'http://node-a.test', operator: 'Alice' }; +const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' }; +const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' }; + +function playOut(host: ModeHost, lobbyId: string, tokens: string[]) { + for (let guard = 0; guard < 50; guard++) { + const v0 = host.view(lobbyId, tokens[0]) as any; + if (v0.phase !== 'playing') return v0; + for (const t of tokens) { + const v = host.view(lobbyId, t) as any; + if (v.legalActions?.length) void host.act(lobbyId, t, v.legalActions[0]); + } + } + throw new Error('did not finish'); +} + +test('modes host: lobby → match → record → leaderboard and host credit', async () => { + let now = 1_000_000; + const store = new MatchStore(null); + const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store, now: () => now }); + const a = host.createLobby('stub', alice); + assert.equal(host.list().modes[0]!.stats.openLobbies, 1); + assert.deepEqual(host.openLobbies('stub').map(l => l.host), ['Alice']); + const b = await host.join(a.lobbyId, bob); + assert.equal(b.seat, 1); + assert.equal((host.view(a.lobbyId) as any).state, undefined, 'spectators see no private state'); + const end = playOut(host, a.lobbyId, [a.token, b.token]); + assert.equal(end.phase, 'finished'); + const list = host.list(); + assert.equal(list.matchesHosted, 1); + assert.equal(list.host.operator, 'Alice'); + assert.equal(list.modes[0]!.stats.matchesPlayed, 1); + assert.equal(list.modes[0]!.stats.distinctPlayers, 2); + const board = host.leaderboard('stub'); + assert.equal(board.entries.length, 2); + assert.equal(board.key, 'http://node-a.test#stub@1'); + const rec = host.matchRecord(end.matchId); + assert.equal(rec.actions.length, 6); + assert.equal(rec.players[0]!.name, 'Alice'); + assert.ok(!JSON.stringify(rec).includes(alice.secret), 'secrets are never stored'); +}); + +test('modes host: actions must be legal and from the right seat', async () => { + const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(null) }); + const a = host.createLobby('stub', alice); + const b = await host.join(a.lobbyId, bob); + await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 99 }), /Illegal/); + await assert.rejects(host.act(a.lobbyId, 'not-a-token-xxxxxxxxxxxx', { type: 'play', card: 0 }), /Not a player/); + await host.act(a.lobbyId, a.token, { type: 'play', card: 0 }); + await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 0 }), /Illegal/, 'no double play'); + await host.act(a.lobbyId, b.token, { card: 1, type: 'play' }); // key order doesn't matter + await assert.rejects(host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' }), /no longer open/); + assert.throws(() => host.createLobby('stub', { name: '