Merge remote-tracking branch 'origin/night/2026-11-16' into night/ui-a/play-shell

# Conflicts:
#	src/App.tsx
This commit is contained in:
2026-11-17 00:25:31 -05:00
107 changed files with 5010 additions and 13 deletions
+101
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+54
View File
@@ -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")
}
+20
View File
@@ -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()
}
+21
View File
@@ -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
@@ -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 <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@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());
}
}
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<activity
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- SSO redirect (RFC 8252 private-use scheme, registered with Dex as dev.eom.wikideck:/oauth/callback) -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="dev.eom.wikideck" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,5 @@
package dev.eom.wikideck;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">WikiDeck</string>
<string name="title_activity_main">WikiDeck</string>
<string name="package_name">dev.eom.wikideck</string>
<string name="custom_url_scheme">dev.eom.wikideck</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -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 <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+12
View File
@@ -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
+29
View File
@@ -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
}
+9
View File
@@ -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')
+22
View File
@@ -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
Binary file not shown.
+7
View File
@@ -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
Vendored Executable
+252
View File
@@ -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" "$@"
+94
View File
@@ -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
+5
View File
@@ -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'
+16
View File
@@ -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'
}
+26
View File
@@ -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;
+4
View File
@@ -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.
+28
View File
@@ -0,0 +1,28 @@
#!/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 up` (ledgers persist in the volumes).
# 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}
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
git checkout -q --detach "$new"
echo "DEPLOY start $(git log --oneline -1 | cut -c1-90)"
if deploy/night/testnet.sh up >"$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
+8 -4
View File
@@ -47,8 +47,9 @@ const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePow
| `scoringPower(state, lane)` | Lane power plus revealed "at scoring" Portals (§7). `result().lanePower` uses this. |
| `laneCapacity(state, lane)` | Per-seat capacity of a lane. A Portal such as Stub may override it. |
| `isOnTopic(state, cardInPlay)` | §1.4/§6 on-topic test, including Disambiguation. |
| `starterDeck(seed): GameCard[]` | A 12-card loaner deck (DESIGN §2). **Placeholder** cards until starter-cards.json lands. |
| `previewPool(): GameCard[]` | Every loaner card once. For draft modes. |
| `STARTER_DECKS`, `starterDeckById(id, rules?)` | The 4 DESIGN §2.1 starter decks (`stargazers`, `field-guide`, `headliners`, `pioneers`), derived through `deriveCard` with the given rules (a `Ruleset` works). **Use these for new players.** |
| `starterDeck(seed)`, `previewPool()` | Older placeholder loaners (seeded 12-card deck / every placeholder once). Kept for tests and draft prototypes; `previewPool()` moves to `starter-cards.json` in a follow-up. |
| `deriveCard(input, table, rules?)`, `deriveDeck(inputs, table, rules?)` | DESIGN §1 + §10.1: `CardInput` → `GameCard`. **Hosts only**: run on host-frozen, plausibility-checked inputs, never on client JSON. A `Ruleset` can be passed as `rules`. |
| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. |
## 2. Actions
@@ -105,6 +106,9 @@ interface GameCard {
- **The engine takes already-derived cards and never reads raw stats.** The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1).
- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in `shared/game/derive.ts`, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before calling `createMatch`.
- `CardInput = { cardId, pageId | null, title, category, rarity, snapshot: { stats }, live: { trendPercent, dailyAverage }, check, pinned? }`. `pinned: { cost, home, faction }` replaces §1.1–1.5 **only** when `check === 'loaner'`. `check === 'unchecked'` caps cost at `uncheckedCostCap` (home and fame are kept).
- **Never build `GameCard`s from client JSON.** `validateDeck` only checks shapes and ranges; a client could send cost 1 / power 30. Constructed modes must re-derive on the host.
- Both seats can hold the same loaner `cardId`. The engine keys per seat, so UIs should key cards by `owner + cardId`.
- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them.
- A keyword that isn't in `ruleset.keywordsEnabled` never runs. Derivation is responsible for not giving that card `vanillaBonus`.
- Lane power = `power` + `bonus` + `trend` + `onTopicBonus[cost]` if on-topic + ongoing keyword and Portal effects, floored at 0.
@@ -191,7 +195,7 @@ Scoring runs after the last turn's End phase. Lane powers include revealed "at s
## 8. Keywords and Portals (extension contract)
`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`.
`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. v1 keywords (`V1_KEYWORDS`, one per faction via `FACTION_KEYWORD`): viral, rising, local, encyclopedic, nostalgic, translated; optional (`OPTIONAL_KEYWORDS`, off by default): edition, obscure, wildcard. Portals: the 6 kinds of §10.3. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`.
**Keywords**
- `onReveal(ctx, self)` and `endOfTurn(ctx, self)` may change `bonus` on cards in `ctx.state`.
@@ -220,4 +224,4 @@ Portal hooks act only once the Portal is revealed.
- on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks
- disabled keywords, AFK and concede, and draws
- the random-play property: matches terminate, replay exactly, and serialise after every action
- `tests/game-*.test.ts` (engine-b): keywords, card derivation, property tests and the DESIGN §12 golden match.
- `tests/game-keywords`, `game-derive`, `game-starter`, `game-property`, `game-golden` (engine-b): every keyword and Portal, derivation, starter decks, properties (termination, determinism, round-trip, no input mutation, legality, power ≥ 0, capacity, no hand leak) and the DESIGN §12 golden match (19–15 / 15–19 / 13–10, p0 wins).
+257
View File
@@ -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 (`<origin>#<id>@<version>`). |
| `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 <token>`: 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 &lt;operator&gt;"** (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`, `<origin>#<id>@<version>`, 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.
+92
View File
@@ -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 <user>@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 <user>@127.0.0.1:
ssh -p 10022 <user>@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 <user>@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.
+13
View File
@@ -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
+376
View File
@@ -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 = "<group>"; };
50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
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 = "<group>"; };
504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
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 = "<group>";
};
504EC3051FED79650016851F /* Products */ = {
isa = PBXGroup;
children = (
504EC3041FED79650016851F /* App.app */,
);
name = Products;
sourceTree = "<group>";
};
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 = "<group>";
};
/* 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 = "<group>";
};
504EC3101FED79650016851F /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
504EC3111FED79650016851F /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* 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 */;
}
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
+49
View File
@@ -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)
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

@@ -0,0 +1,14 @@
{
"images" : [
{
"filename" : "AppIcon-512@2x.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -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"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17132" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17105"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<imageView key="view" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="Splash" id="snD-IY-ifK">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
</imageView>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="Splash" width="1366" height="1366"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14111" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
</dependencies>
<scenes>
<!--Bridge View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
+67
View File
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CAPACITOR_DEBUG</key>
<string>$(CAPACITOR_DEBUG)</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>WikiDeck</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>dev.eom.wikideck</string>
<key>CFBundleURLSchemes</key>
<array>
<string>dev.eom.wikideck</string>
</array>
</dict>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
</dict>
</plist>
+9
View File
@@ -0,0 +1,9 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
+29
View File
@@ -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")
]
)
]
)
+5
View File
@@ -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.
@@ -0,0 +1 @@
public let isCapacitorApp = true
+1
View File
@@ -0,0 +1 @@
CAPACITOR_DEBUG = true
+1013 -1
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -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",
+42
View File
@@ -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"
+6 -2
View File
@@ -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.
+55
View File
@@ -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<string>();
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);
}
+93
View File
@@ -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<string, string> }) => Promise<Response>;
export function parsePeerOrigins(raw: string | undefined, allowPrivate: boolean): string[] {
const out = new Set<string>();
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<string, PeerModes>();
private inflight: Promise<PeerModes[]> | 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<PeerModes[]> {
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<PeerModes> {
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<string> {
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);
}
+74
View File
@@ -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<Ruleset, GameCard, MatchState, Action> = {
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),
};
+43
View File
@@ -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<Rules = unknown, Card = unknown, State = unknown, Action = unknown> {
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;
}
+357
View File
@@ -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<any, any, any, any>;
store: MatchStore;
/** Optional live Wikipedia trend lookup for `trending` modes. Failures mean "no bonus". */
liveData?: (pageId: number) => Promise<LiveCardData | null>;
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<any, any, any, any>;
private readonly store: MatchStore;
private readonly hosted = new Map<string, HostedMode>();
private readonly lobbies = new Map<string, Lobby>();
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<SeatTicket> {
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<unknown[]> {
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(); }
+45
View File
@@ -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<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean }): Promise<express.Router> {
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);
}
+12
View File
@@ -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 }
}
+28
View File
@@ -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
}
}
+29
View File
@@ -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
}
}
+70
View File
@@ -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<string, unknown>;
// 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) };
}
+87
View File
@@ -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<typeof MatchRecordSchema>;
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number };
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
const KEEP_RECENT = 500;
export class MatchStore {
private readonly file: string | null;
private readonly modes = new Map<string, ModeAgg>();
private readonly recent = new Map<string, MatchRecord>();
private readonly allPlayers = new Set<string>();
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; } }
+58
View File
@@ -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<number, { trend: number | null; at: number }>();
private readonly queue: number[] = [];
private readonly queued = new Set<number>();
private timer: ReturnType<typeof setInterval> | 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<void> {
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; }
}
}
+1
View File
@@ -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')));
+230
View File
@@ -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<typeof RuleOverridesSchema>;
/**
* 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<typeof CardMappingSchema>;
/** 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<typeof DeckPolicySchema>;
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<typeof ModeLimitsSchema>;
/** 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<typeof ModeSchema>;
export type ModeInput = z.input<typeof ModeSchema>;
/**
* 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<typeof HostIdentitySchema>;
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<typeof ModeStatsSchema>;
/** One entry of GET /api/game/modes. */
export const PublishedModeSchema = z.object({ mode: ModeSchema, stats: ModeStatsSchema }).strict();
export type PublishedMode = z.infer<typeof PublishedModeSchema>;
/** 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<typeof ModeListSchema>;
/** 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: `<origin>#<id>@<version>`. */
export function modeKey(origin: string, mode: Pick<ModeDocument, 'id' | 'version'>): 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<R>(base: R, overrides: RuleOverrides, parse: (value: unknown) => R): R {
const merged: Record<string, unknown> = structuredClone(base) as Record<string, unknown>;
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<string, unknown> = { ...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<CardMapping, { preset: 'trending' }>, 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<string, unknown>)[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<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
function byteLength(s: string): number { return new TextEncoder().encode(s).length; }
+2 -1
View File
@@ -15,6 +15,7 @@ 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 { PlaySection } from './game/PlaySection.tsx';
import { isNativeApp } from './native.ts';
import './App.css';
import './testnet.css';
@@ -187,7 +188,7 @@ export default function App() {
<div><span className="metric-icon"><WalletIcon size={19} /></span><div><span>Confirmed ownership</span><strong>{wallet && snapshot ? owned.length : '—'}<small>in your wallet</small></strong></div></div>
<div><span className="metric-icon"><Cpu size={19} /></span><div><span>Proof of work</span><strong className="algorithm">{snapshot?.algorithm ?? 'RandomX'}<small>native CPU mining</small></strong></div></div>
</section>
<section className="mining-panel native-mining" ref={minerPanel}>
<section className="mining-panel native-mining" ref={minerPanel} hidden={isNativeApp()}>
<div className="mining-description"><div className="section-eyebrow"><span className="idle-dot" /> RANDOMX · DESIGNED FOR GENERAL-PURPOSE CPUS</div><h2>Mining should be for more people.</h2><p>Wikideck and Monero use RandomX, an algorithm designed to resist specialized ASICs and keep general-purpose CPUs competitive. That can make mining more accessible—not make every machine equally powerful or promise rewards. Each accepted Wikideck block earns its miner a distinct illustrated Wikipedia card. Wikideck is its own independent network.</p><div className="mining-meta"><span><Cpu size={13} /> Mine with a CPU</span><span><Shield size={13} /> Independently validating peers</span></div><details className="mining-details"><summary>Hardware, rewards &amp; network details</summary><div className="native-memory"><strong>Light · default</strong><span>256 MiB cache plus scratchpad and process overhead.</span><strong>Fast · --fast</strong><span>About 2 GiB dataset plus cache; budget over 2.3 GiB per process. Mining uses CPU, memory, electricity and time. ASIC resistance is a design goal, not a guarantee; results depend on hardware and network difficulty. Wikideck does not share Monero’s network, hashpower or security.</span></div></details></div>
<div className="miner-controls"><div className="miner-display"><div><span>NEXT WIKIPEDIA ARTICLE</span><strong>{snapshot ? 'Chosen when the miner requests work' : `Waiting for ${NETWORK_LABEL} RPC…`}</strong></div></div><p className="muted">The miner selects a random illustrated English Wikipedia article. The same article can appear again; each card keeps its own mint-time statistics.</p><details className="mining-details"><summary>Want to run a miner? Setup &amp; safety details</summary><ol className="native-steps"><li>Build <code>wikideck-randomx</code> using the repository’s native build instructions.</li><li>Save your encrypted backup and keep its password separate.</li><li>Replace <code>&lt;backup.json&gt;</code> with your local file path (quote paths with spaces), then run:</li></ol><pre className="native-command"><code>{nativeCommand}</code></pre><p className="miner-footnote">Node: {window.location.origin}. The command connects to this node; use HTTPS for remote nodes. Password entry stays local—never put it in the command. It defaults to one worker and at most one block. Ctrl+C stops the native miner; closing this page does not.</p></details><button className="button dark full" onClick={openWallet}><Download size={16} /> Download wallet backup</button><button className="text-button" onClick={() => setDialog('guide')}>Read the {NETWORK_LABEL.toLowerCase()} field guide <ArrowRight size={14} /></button></div>
</section>
+18 -5
View File
@@ -44,8 +44,19 @@ export async function pkceChallenge(verifier: string): Promise<string> {
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<void>; close?(): Promise<void> } } };
type NativeBrowser = { open(o: { url: string }): Promise<void>; close?(): Promise<void> };
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<Session>('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 };
}
+1
View File
@@ -1,3 +1,4 @@
import './native.ts';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';

Some files were not shown because too many files have changed in this diff Show More