Compare commits
42
Commits
43b951210e
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
362cee26fd | ||
|
|
01b18be1e4 | ||
|
|
ed3544acfe | ||
|
|
6b84a5d27d | ||
|
|
ae98902446 | ||
|
|
5a4bf45bc7 | ||
|
|
36ab01aab1 | ||
|
|
a8b79ffd1b | ||
|
|
cf468ed833 | ||
|
|
7cea6ebb1e | ||
|
|
08ec03b6ec | ||
|
|
0c4dc3aacb | ||
|
|
5d9e3063c5 | ||
|
|
833eab04af | ||
|
|
0fd1805502 | ||
|
|
7150ebd13e | ||
|
|
817236f349 | ||
|
|
85e6db67b5 | ||
|
|
f246c4290f | ||
|
|
39953dc492 | ||
|
|
0d27c9a8d9 | ||
|
|
4e9cb20971 | ||
|
|
f5ee0298d8 | ||
|
|
71060bd020 | ||
|
|
1719b3c23b | ||
|
|
b4e9651529 | ||
|
|
62db511c7b | ||
|
|
94d52c7622 | ||
|
|
97c237be80 | ||
|
|
0ff94f9b10 | ||
|
|
937f51b4fb | ||
|
|
a84a36349b | ||
|
|
7dd0d34383 | ||
|
|
6aec03fb3d | ||
|
|
483a1a278b | ||
|
|
e475370a20 | ||
|
|
1fad1cc8d4 | ||
|
|
f7ccb4a173 | ||
|
|
c7840936a3 | ||
|
|
e592324639 | ||
|
|
09e3d3921f | ||
|
|
bd5b74ff3b |
No files matched your search
@@ -0,0 +1,224 @@
|
|||||||
|
name: Android Release (static debug key)
|
||||||
|
|
||||||
|
# Same flow as android-release.yml, but the APK is signed with a static debug key instead of the
|
||||||
|
# release keystore. The key is created on the first run, committed to CollabTableAndroid/signing/, and
|
||||||
|
# reused by every later run, so builds from this workflow can update each other in place. It is for
|
||||||
|
# test builds only: the release keystore is secret and this key is not.
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
bump_type:
|
||||||
|
description: 'Version bump type'
|
||||||
|
required: true
|
||||||
|
default: 'patch'
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- patch
|
||||||
|
- minor
|
||||||
|
- major
|
||||||
|
changelog:
|
||||||
|
description: 'Changelog for this release (leave blank to auto-generate from commits)'
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
|
||||||
|
# The first run creates the key and pushes it. Queue runs so that a later run sees the key instead of
|
||||||
|
# creating a second one.
|
||||||
|
concurrency:
|
||||||
|
group: android-release-static-debug
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Bump version, build & release (static debug key)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Android debug keystore conventions (password "android", alias "androiddebugkey").
|
||||||
|
STATIC_KEYSTORE: CollabTableAndroid/signing/static-debug.jks
|
||||||
|
STATIC_STORE_PASSWORD: android
|
||||||
|
STATIC_KEY_ALIAS: androiddebugkey
|
||||||
|
STATIC_KEY_PASSWORD: android
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
# Java comes first: the key is checked with keytool before anything is pushed.
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: 'temurin'
|
||||||
|
java-version: '21'
|
||||||
|
cache: 'gradle'
|
||||||
|
|
||||||
|
# A key is generated only when the repository has never held one. If the file was committed
|
||||||
|
# before but is now missing, the run stops: a new key would change the certificate and break
|
||||||
|
# in-place updates for every installed copy.
|
||||||
|
- name: Prepare static debug key
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -f "$STATIC_KEYSTORE" ]; then
|
||||||
|
echo "Reusing the static debug key in $STATIC_KEYSTORE"
|
||||||
|
elif [ -n "$(git log --all --format=%H -- "$STATIC_KEYSTORE")" ]; then
|
||||||
|
echo "::error::$STATIC_KEYSTORE exists in the repository history but not on this branch. Restore it (merge or cherry-pick) instead of generating a new key."
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
mkdir -p "$(dirname "$STATIC_KEYSTORE")"
|
||||||
|
keytool -genkeypair -noprompt \
|
||||||
|
-keystore "$STATIC_KEYSTORE" \
|
||||||
|
-storetype PKCS12 \
|
||||||
|
-storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-keypass:env STATIC_KEY_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" \
|
||||||
|
-keyalg RSA -keysize 2048 -validity 10000 \
|
||||||
|
-dname "CN=Android Debug,O=Android,C=US"
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add "$STATIC_KEYSTORE"
|
||||||
|
git commit -m "chore(android): add static debug signing key"
|
||||||
|
git push
|
||||||
|
echo "Created the static debug key and pushed it to the repository."
|
||||||
|
fi
|
||||||
|
FINGERPRINT=$(keytool -list -v -keystore "$STATIC_KEYSTORE" -storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p')
|
||||||
|
echo "::notice::Static debug certificate SHA-256: $FINGERPRINT"
|
||||||
|
|
||||||
|
- name: Bump version in build.gradle.kts
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BUMP_TYPE: ${{ inputs.bump_type }}
|
||||||
|
run: |
|
||||||
|
GRADLE_FILE="CollabTableAndroid/app/build.gradle"
|
||||||
|
|
||||||
|
CURRENT_CODE=$(grep -oP 'versionCode\s*=\s*\K[0-9]+' "$GRADLE_FILE")
|
||||||
|
CURRENT_NAME=$(grep -oP 'versionName\s*=\s*"\K[^"]+' "$GRADLE_FILE")
|
||||||
|
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_NAME"
|
||||||
|
|
||||||
|
case "$BUMP_TYPE" in
|
||||||
|
major) MAJOR=$((MAJOR+1)); MINOR=0; PATCH=0 ;;
|
||||||
|
minor) MINOR=$((MINOR+1)); PATCH=0 ;;
|
||||||
|
patch) PATCH=$((PATCH+1)) ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
NEW_CODE=$((CURRENT_CODE+1))
|
||||||
|
NEW_NAME="${MAJOR}.${MINOR}.${PATCH}"
|
||||||
|
|
||||||
|
sed -i "s/versionCode = ${CURRENT_CODE}/versionCode = ${NEW_CODE}/" "$GRADLE_FILE"
|
||||||
|
sed -i "s/versionName = \"${CURRENT_NAME}\"/versionName = \"${NEW_NAME}\"/" "$GRADLE_FILE"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "new_code=${NEW_CODE}"
|
||||||
|
echo "new_name=${NEW_NAME}"
|
||||||
|
echo "tag=v${NEW_NAME}-debug"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Commit version bump
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add CollabTableAndroid/app/build.gradle
|
||||||
|
git commit -m "chore(android): bump version to ${{ steps.version.outputs.new_name }} (code ${{ steps.version.outputs.new_code }})"
|
||||||
|
git push
|
||||||
|
|
||||||
|
- name: Set up Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@v3
|
||||||
|
|
||||||
|
- name: Install Android SDK
|
||||||
|
uses: android-actions/setup-android@v4
|
||||||
|
|
||||||
|
- name: Accept SDK licenses
|
||||||
|
shell: bash
|
||||||
|
run: yes | sdkmanager --licenses || true
|
||||||
|
|
||||||
|
# Install the compileSdk platform, build-tools 36.0.0 (used by AGP lint) and 37.0.0 (used by apksigner below).
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sdkmanager "platform-tools" "platforms;android-37.2" "build-tools;36.0.0" "build-tools;37.0.0"
|
||||||
|
|
||||||
|
- name: Run lint and ktlint
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew --no-daemon lintDebug ktlintCheck
|
||||||
|
|
||||||
|
# The release build type picks up the signing config from these variables, so the static key
|
||||||
|
# is used without any change to the Gradle build.
|
||||||
|
- name: Build release APK signed with the static debug key
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_FILE: ${{ github.workspace }}/${{ env.STATIC_KEYSTORE }}
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ env.STATIC_STORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ env.STATIC_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ env.STATIC_KEY_PASSWORD }}
|
||||||
|
run: ./gradlew --no-daemon assembleRelease
|
||||||
|
|
||||||
|
- name: Verify APK is signed with the static debug key
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APK="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
APKSIGNER="$ANDROID_HOME/build-tools/37.0.0/apksigner"
|
||||||
|
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
|
||||||
|
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^.*certificate SHA-256 digest: //p' | sed -n '1p')
|
||||||
|
EXPECTED=$(keytool -list -v -keystore "$STATIC_KEYSTORE" -storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p' | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::APK is signed with $ACTUAL, expected the static debug key $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Rename APK with version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
SRC="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
cp "$SRC" "CollabTable-${{ steps.version.outputs.tag }}.apk"
|
||||||
|
|
||||||
|
- name: Generate changelog
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CHANGELOG_INPUT: ${{ inputs.changelog }}
|
||||||
|
run: |
|
||||||
|
if [ -n "$CHANGELOG_INPUT" ]; then
|
||||||
|
printf '%s' "$CHANGELOG_INPUT" > release-notes.md
|
||||||
|
else
|
||||||
|
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
|
||||||
|
if [ -n "$LAST_TAG" ]; then
|
||||||
|
RANGE="${LAST_TAG}..HEAD"
|
||||||
|
else
|
||||||
|
RANGE="HEAD"
|
||||||
|
fi
|
||||||
|
COMMITS=$(git log "$RANGE" --pretty=format:"%s" | grep -vE "^chore\(android\): (bump version|add static debug signing key)" || true)
|
||||||
|
FEATURES=$(echo "$COMMITS" | grep -E "^feat(\\(.+\\))?:" | sed 's/^feat[^:]*: /- /' || true)
|
||||||
|
FIXES=$(echo "$COMMITS" | grep -E "^fix(\\(.+\\))?:" | sed 's/^fix[^:]*: /- /' || true)
|
||||||
|
OTHERS=$(echo "$COMMITS" | grep -vE "^(feat|fix)(\\(.+\\))?:" | grep -v '^$' | sed 's/^/- /' || true)
|
||||||
|
{
|
||||||
|
if [ -n "$FEATURES" ]; then printf '### Features\n%s\n\n' "$FEATURES"; fi
|
||||||
|
if [ -n "$FIXES" ]; then printf '### Bug Fixes\n%s\n\n' "$FIXES"; fi
|
||||||
|
if [ -n "$OTHERS" ]; then printf '### Other Changes\n%s\n\n' "$OTHERS"; fi
|
||||||
|
} > release-notes.md
|
||||||
|
if [ ! -s release-notes.md ]; then echo 'No changes recorded.' > release-notes.md; fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Marked as a pre-release so it never takes the "Latest" badge from the real release.
|
||||||
|
- name: Create GitHub pre-release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ steps.version.outputs.tag }}
|
||||||
|
name: ${{ steps.version.outputs.tag }} (static debug key)
|
||||||
|
body_path: release-notes.md
|
||||||
|
files: CollabTable-${{ steps.version.outputs.tag }}.apk
|
||||||
|
prerelease: true
|
||||||
|
fail_on_unmatched_files: true
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
name: Android Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
bump_type:
|
||||||
|
description: 'Version bump type'
|
||||||
|
required: true
|
||||||
|
default: 'patch'
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- patch
|
||||||
|
- minor
|
||||||
|
- major
|
||||||
|
changelog:
|
||||||
|
description: 'Changelog for this release (leave blank to auto-generate from commits)'
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Bump version, build & release
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
# Java comes first: the signing key is checked with keytool before anything is pushed.
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: 'temurin'
|
||||||
|
java-version: '21'
|
||||||
|
cache: 'gradle'
|
||||||
|
|
||||||
|
- name: Prepare release signing key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_BASE64: ${{ secrets.OGS_KEYSTORE_BASE64 }}
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ secrets.OGS_KEYSTORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ secrets.OGS_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ secrets.OGS_KEY_PASSWORD }}
|
||||||
|
OGS_RELEASE_CERT_SHA256: ${{ vars.OGS_RELEASE_CERT_SHA256 }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
for name in OGS_KEYSTORE_BASE64 OGS_KEYSTORE_PASSWORD OGS_KEY_ALIAS OGS_KEY_PASSWORD; do
|
||||||
|
if [ -z "${!name}" ]; then
|
||||||
|
echo "::error::Secret $name is not set. Releases must be signed with the release key."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
KEYSTORE="$RUNNER_TEMP/ogs-release.jks"
|
||||||
|
printf '%s' "$OGS_KEYSTORE_BASE64" | base64 -d > "$KEYSTORE"
|
||||||
|
|
||||||
|
# Fail before the version bump is pushed if the keystore is not the pinned release key.
|
||||||
|
ACTUAL=$(keytool -list -v -keystore "$KEYSTORE" -storepass:env OGS_KEYSTORE_PASSWORD \
|
||||||
|
-alias "$OGS_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p' | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
EXPECTED=$(printf '%s' "$OGS_RELEASE_CERT_SHA256" | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ -z "$EXPECTED" ]; then
|
||||||
|
echo "::error::Variable OGS_RELEASE_CERT_SHA256 is not set. Set it to $ACTUAL."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::Release keystore certificate is $ACTUAL, expected $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Bump version in build.gradle.kts
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BUMP_TYPE: ${{ inputs.bump_type }}
|
||||||
|
run: |
|
||||||
|
GRADLE_FILE="CollabTableAndroid/app/build.gradle"
|
||||||
|
|
||||||
|
CURRENT_CODE=$(grep -oP 'versionCode\s*=\s*\K[0-9]+' "$GRADLE_FILE")
|
||||||
|
CURRENT_NAME=$(grep -oP 'versionName\s*=\s*"\K[^"]+' "$GRADLE_FILE")
|
||||||
|
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_NAME"
|
||||||
|
|
||||||
|
case "$BUMP_TYPE" in
|
||||||
|
major) MAJOR=$((MAJOR+1)); MINOR=0; PATCH=0 ;;
|
||||||
|
minor) MINOR=$((MINOR+1)); PATCH=0 ;;
|
||||||
|
patch) PATCH=$((PATCH+1)) ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
NEW_CODE=$((CURRENT_CODE+1))
|
||||||
|
NEW_NAME="${MAJOR}.${MINOR}.${PATCH}"
|
||||||
|
|
||||||
|
sed -i "s/versionCode = ${CURRENT_CODE}/versionCode = ${NEW_CODE}/" "$GRADLE_FILE"
|
||||||
|
sed -i "s/versionName = \"${CURRENT_NAME}\"/versionName = \"${NEW_NAME}\"/" "$GRADLE_FILE"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "new_code=${NEW_CODE}"
|
||||||
|
echo "new_name=${NEW_NAME}"
|
||||||
|
echo "tag=v${NEW_NAME}"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Commit version bump
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add CollabTableAndroid/app/build.gradle
|
||||||
|
git commit -m "chore(android): bump version to ${{ steps.version.outputs.new_name }} (code ${{ steps.version.outputs.new_code }})"
|
||||||
|
git push
|
||||||
|
|
||||||
|
- name: Set up Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@v3
|
||||||
|
|
||||||
|
- name: Install Android SDK
|
||||||
|
uses: android-actions/setup-android@v4
|
||||||
|
|
||||||
|
- name: Accept SDK licenses
|
||||||
|
shell: bash
|
||||||
|
run: yes | sdkmanager --licenses || true
|
||||||
|
|
||||||
|
# Install the compileSdk platform, build-tools 36.0.0 (used by AGP lint) and 37.0.0 (used by apksigner below).
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sdkmanager "platform-tools" "platforms;android-37.2" "build-tools;36.0.0" "build-tools;37.0.0"
|
||||||
|
|
||||||
|
- name: Run lint and ktlint
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew --no-daemon lintDebug ktlintCheck
|
||||||
|
|
||||||
|
- name: Build signed release APK
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_FILE: ${{ runner.temp }}/ogs-release.jks
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ secrets.OGS_KEYSTORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ secrets.OGS_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ secrets.OGS_KEY_PASSWORD }}
|
||||||
|
run: ./gradlew --no-daemon assembleRelease
|
||||||
|
|
||||||
|
- name: Verify APK is signed with the release key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_RELEASE_CERT_SHA256: ${{ vars.OGS_RELEASE_CERT_SHA256 }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APK="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
APKSIGNER="$ANDROID_HOME/build-tools/37.0.0/apksigner"
|
||||||
|
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
|
||||||
|
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^.*certificate SHA-256 digest: //p' | sed -n '1p')
|
||||||
|
EXPECTED=$(printf '%s' "$OGS_RELEASE_CERT_SHA256" | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::APK is signed with $ACTUAL, expected $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Rename APK with version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
SRC="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
cp "$SRC" "CollabTable-${{ steps.version.outputs.tag }}.apk"
|
||||||
|
|
||||||
|
- name: Generate changelog
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CHANGELOG_INPUT: ${{ inputs.changelog }}
|
||||||
|
run: |
|
||||||
|
if [ -n "$CHANGELOG_INPUT" ]; then
|
||||||
|
printf '%s' "$CHANGELOG_INPUT" > release-notes.md
|
||||||
|
else
|
||||||
|
# Skip the static debug pre-releases, so the notes cover everything since the last public release.
|
||||||
|
LAST_TAG=$(git describe --tags --abbrev=0 --exclude '*-debug' 2>/dev/null || echo "")
|
||||||
|
if [ -n "$LAST_TAG" ]; then
|
||||||
|
RANGE="${LAST_TAG}..HEAD"
|
||||||
|
else
|
||||||
|
RANGE="HEAD"
|
||||||
|
fi
|
||||||
|
COMMITS=$(git log "$RANGE" --pretty=format:"%s" | grep -vE "^chore\(android\): (bump version|add static debug signing key)" || true)
|
||||||
|
FEATURES=$(echo "$COMMITS" | grep -E "^feat(\\(.+\\))?:" | sed 's/^feat[^:]*: /- /' || true)
|
||||||
|
FIXES=$(echo "$COMMITS" | grep -E "^fix(\\(.+\\))?:" | sed 's/^fix[^:]*: /- /' || true)
|
||||||
|
OTHERS=$(echo "$COMMITS" | grep -vE "^(feat|fix)(\\(.+\\))?:" | grep -v '^$' | sed 's/^/- /' || true)
|
||||||
|
{
|
||||||
|
if [ -n "$FEATURES" ]; then printf '### Features\n%s\n\n' "$FEATURES"; fi
|
||||||
|
if [ -n "$FIXES" ]; then printf '### Bug Fixes\n%s\n\n' "$FIXES"; fi
|
||||||
|
if [ -n "$OTHERS" ]; then printf '### Other Changes\n%s\n\n' "$OTHERS"; fi
|
||||||
|
} > release-notes.md
|
||||||
|
if [ ! -s release-notes.md ]; then echo 'No changes recorded.' > release-notes.md; fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Create GitHub release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ steps.version.outputs.tag }}
|
||||||
|
name: ${{ steps.version.outputs.tag }}
|
||||||
|
body_path: release-notes.md
|
||||||
|
files: CollabTable-${{ steps.version.outputs.tag }}.apk
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
|
||||||
|
- name: Remove release keystore
|
||||||
|
if: always()
|
||||||
|
shell: bash
|
||||||
|
run: rm -f "$RUNNER_TEMP/ogs-release.jks"
|
||||||
@@ -18,7 +18,6 @@ on:
|
|||||||
- '.github/workflows/lint.yml'
|
- '.github/workflows/lint.yml'
|
||||||
workflow_dispatch: {}
|
workflow_dispatch: {}
|
||||||
|
|
||||||
env:
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint:
|
||||||
@@ -38,13 +37,14 @@ jobs:
|
|||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
node-version: '22'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund --omit=dev
|
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund
|
||||||
|
npm run build --prefix ../shared
|
||||||
npm ci
|
npm ci
|
||||||
|
|
||||||
- name: Run ESLint
|
- name: Run ESLint
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
name: Security
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ['**']
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
schedule:
|
||||||
|
# Daily, for the Trivy job, so advisories published after the last push still get reported.
|
||||||
|
- cron: '23 5 * * *'
|
||||||
|
# Weekly, for the secrets and code jobs. Each job's if: condition picks the entry that runs it.
|
||||||
|
- cron: '23 5 * * 1'
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
secrets:
|
||||||
|
name: Secrets (gitleaks)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
# Full history, so a secret that was committed and later removed is still found.
|
||||||
|
fetch-depth: 0
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: stable
|
||||||
|
# gitleaks runs at a pinned version. go run checks the module against the Go checksum
|
||||||
|
# database. Known false positives go in .gitleaks.toml at the repo root, which gitleaks reads
|
||||||
|
# on its own.
|
||||||
|
- name: Scan git history for secrets
|
||||||
|
run: go run github.com/zricethezav/gitleaks/v8@v8.30.1 git --no-banner --redact --exit-code 1 .
|
||||||
|
|
||||||
|
code:
|
||||||
|
name: Code (Semgrep)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- name: Install Semgrep
|
||||||
|
run: pip install semgrep==1.182.1
|
||||||
|
# Fails on ERROR findings from Semgrep's default rules. WARNING findings are not gated.
|
||||||
|
- name: Scan code
|
||||||
|
run: semgrep scan --config p/default --severity ERROR --error --metrics=off .
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
name: Dependencies (Trivy)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * *'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- name: Install uv
|
||||||
|
run: pip install uv==0.13.5
|
||||||
|
- name: Install Trivy
|
||||||
|
# Always the newest Trivy release. The version is read from the release redirect when the job
|
||||||
|
# runs, and the download is checked against that release's published checksums. The
|
||||||
|
# aquasecurity/trivy-action version tags were repointed to malicious commits in March 2026,
|
||||||
|
# so that action is not used.
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
latest_url=$(curl --fail --location --silent --show-error --retry 5 --retry-delay 2 \
|
||||||
|
--output /dev/null --write-out '%{url_effective}' https://github.com/aquasecurity/trivy/releases/latest)
|
||||||
|
TRIVY_VERSION=${latest_url##*/tag/v}
|
||||||
|
if [[ ! "$TRIVY_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "Could not read the latest Trivy version from $latest_url" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Installing Trivy $TRIVY_VERSION"
|
||||||
|
archive="trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||||
|
base_url="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}"
|
||||||
|
|
||||||
|
curl --fail --location --retry 5 --retry-delay 2 \
|
||||||
|
--output "$RUNNER_TEMP/$archive" "$base_url/$archive"
|
||||||
|
curl --fail --location --retry 5 --retry-delay 2 \
|
||||||
|
--output "$RUNNER_TEMP/trivy_checksums.txt" "$base_url/trivy_${TRIVY_VERSION}_checksums.txt"
|
||||||
|
|
||||||
|
(cd "$RUNNER_TEMP" && grep -F " $archive" trivy_checksums.txt > trivy_checksum.txt \
|
||||||
|
&& sha256sum -c trivy_checksum.txt)
|
||||||
|
|
||||||
|
tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" trivy
|
||||||
|
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
|
||||||
|
"$RUNNER_TEMP/trivy" --version
|
||||||
|
# Trivy audits lockfiles and skips bare manifests. For each manifest with no lockfile in its
|
||||||
|
# own folder or any parent folder, resolve one here so its dependencies get scanned. These
|
||||||
|
# lockfiles are made only for this run and are not committed.
|
||||||
|
- name: Resolve manifests that have no lockfile
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
has_lockfile() {
|
||||||
|
local dir=$1
|
||||||
|
shift
|
||||||
|
while true; do
|
||||||
|
for lockfile in "$@"; do
|
||||||
|
if [ -f "$dir/$lockfile" ]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ "$dir" = "." ]; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
dir=$(dirname "$dir")
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
while IFS= read -r -d '' manifest; do
|
||||||
|
dir=$(dirname "$manifest")
|
||||||
|
if ! has_lockfile "$dir" package-lock.json yarn.lock pnpm-lock.yaml; then
|
||||||
|
echo "Resolving npm dependencies in $dir"
|
||||||
|
(cd "$dir" && npm install --package-lock-only --ignore-scripts --no-audit --no-fund)
|
||||||
|
fi
|
||||||
|
done < <(find . -name node_modules -prune -o -name package.json -print0)
|
||||||
|
|
||||||
|
while IFS= read -r -d '' manifest; do
|
||||||
|
dir=$(dirname "$manifest")
|
||||||
|
if ! has_lockfile "$dir" uv.lock poetry.lock Pipfile.lock; then
|
||||||
|
echo "Resolving Python dependencies in $dir"
|
||||||
|
(cd "$dir" && uv lock)
|
||||||
|
fi
|
||||||
|
done < <(find . -name node_modules -prune -o -name .venv -prune -o -name pyproject.toml -print0)
|
||||||
|
# Fails on HIGH and CRITICAL vulnerabilities that have a fixed version. Vulnerabilities with no
|
||||||
|
# fix are left out, because nothing can be changed to clear them. Development dependencies are
|
||||||
|
# included, since build and test tooling runs in CI.
|
||||||
|
# --offline-scan: Maven Central rate-limits the lookups Trivy makes for pom.xml, so Maven
|
||||||
|
# dependencies are read from their declared versions only. Transitive ones are not resolved.
|
||||||
|
- name: Scan dependencies for known vulnerabilities
|
||||||
|
run: >-
|
||||||
|
trivy fs --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --include-dev-deps
|
||||||
|
--offline-scan --exit-code 1 --timeout 15m .
|
||||||
@@ -18,7 +18,6 @@ on:
|
|||||||
- '.github/workflows/tests.yml'
|
- '.github/workflows/tests.yml'
|
||||||
workflow_dispatch: {}
|
workflow_dispatch: {}
|
||||||
|
|
||||||
env:
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
backend:
|
backend:
|
||||||
@@ -29,6 +28,21 @@ jobs:
|
|||||||
working-directory: backend
|
working-directory: backend
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
# A throwaway database for the handler and sync tests. They create their own
|
||||||
|
# schema in it and drop it again, and are skipped when TEST_DATABASE_URL is unset.
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16
|
||||||
|
env:
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: collabtable_test
|
||||||
|
ports:
|
||||||
|
- "15432:5432"
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U postgres"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -42,7 +56,14 @@ jobs:
|
|||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test ./...
|
shell: bash
|
||||||
|
env:
|
||||||
|
TEST_DATABASE_URL: "postgres://postgres:postgres@localhost:15432/collabtable_test?sslmode=disable"
|
||||||
|
run: |
|
||||||
|
if [ "${GITEA_ACTIONS:-}" = "true" ]; then
|
||||||
|
export TEST_DATABASE_URL="postgres://postgres:postgres@postgres:5432/collabtable_test?sslmode=disable"
|
||||||
|
fi
|
||||||
|
go test ./...
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
name: Dashboard checks
|
name: Dashboard checks
|
||||||
@@ -67,8 +88,12 @@ jobs:
|
|||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
npm install --prefix ../shared/packages/web-ui --no-package-lock --ignore-scripts --no-audit --no-fund --omit=dev
|
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund
|
||||||
|
npm run build --prefix ../shared
|
||||||
npm ci
|
npm ci
|
||||||
|
|
||||||
- name: Check dashboard
|
- name: Check dashboard
|
||||||
run: npm run check
|
run: npm run check
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: npm test
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# gitleaks configuration. gitleaks reads this file from the repository root.
|
||||||
|
|
||||||
|
[extend]
|
||||||
|
useDefault = true
|
||||||
|
|
||||||
|
[allowlist]
|
||||||
|
description = "Test fixtures that contain placeholder credentials, not real secrets"
|
||||||
|
paths = [
|
||||||
|
'''(^|/)(tests?|__tests__)/''',
|
||||||
|
'''_test\.go$''',
|
||||||
|
'''\.test\.[jt]sx?$''',
|
||||||
|
'''\.spec\.[jt]sx?$''',
|
||||||
|
'''(^|/)test_[^/]*\.py$''',
|
||||||
|
'''Test\.java$''',
|
||||||
|
'''(^|/)contract/auth-contract\.json$''',
|
||||||
|
]
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Semgrep skips test code and fixtures. Tests hold placeholder credentials on purpose.
|
||||||
|
# auth-contract.json holds bcrypt hashes of test passwords shared by every service's tests.
|
||||||
|
auth-contract.json
|
||||||
|
test/
|
||||||
|
tests/
|
||||||
|
__tests__/
|
||||||
|
*_test.go
|
||||||
|
*.test.js
|
||||||
|
*.test.ts
|
||||||
|
*.test.tsx
|
||||||
|
*.spec.js
|
||||||
|
*.spec.ts
|
||||||
|
test_*.py
|
||||||
|
*Test.java
|
||||||
@@ -1,23 +1,27 @@
|
|||||||
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'com.android.application'
|
id 'com.android.application'
|
||||||
id 'org.jetbrains.kotlin.android'
|
|
||||||
id 'org.jetbrains.kotlin.plugin.compose'
|
id 'org.jetbrains.kotlin.plugin.compose'
|
||||||
// KSP not available for Kotlin 2.2.21 yet; switch to kapt for Room annotation processing
|
id 'com.google.devtools.ksp'
|
||||||
id 'org.jetbrains.kotlin.kapt'
|
|
||||||
id 'org.jlleitschuh.gradle.ktlint'
|
id 'org.jlleitschuh.gradle.ktlint'
|
||||||
id 'io.gitlab.arturbosch.detekt'
|
id 'io.gitlab.arturbosch.detekt'
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = 'com.collabtable.app'
|
namespace = 'com.collabtable.app'
|
||||||
compileSdk = 34
|
compileSdk {
|
||||||
|
version = release(37) {
|
||||||
|
minorApiLevel = 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.collabtable.app"
|
applicationId = "com.collabtable.app"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 34
|
targetSdk = 37
|
||||||
versionCode 1
|
versionCode = 1
|
||||||
versionName "1.0"
|
versionName = "1.0"
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
vectorDrawables {
|
vectorDrawables {
|
||||||
@@ -25,21 +29,37 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Release signing: CI supplies the keystore and its passwords from repository secrets, so every
|
||||||
|
// published APK carries the same certificate and installs can update in place. Without
|
||||||
|
// OGS_KEYSTORE_FILE, release builds stay unsigned, which keeps local builds working.
|
||||||
|
def releaseKeystoreFile = System.getenv('OGS_KEYSTORE_FILE')
|
||||||
|
signingConfigs {
|
||||||
|
release {
|
||||||
|
if (releaseKeystoreFile != null) {
|
||||||
|
storeFile file(releaseKeystoreFile)
|
||||||
|
storePassword System.getenv('OGS_KEYSTORE_PASSWORD')
|
||||||
|
keyAlias System.getenv('OGS_KEY_ALIAS')
|
||||||
|
keyPassword System.getenv('OGS_KEY_PASSWORD')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
minifyEnabled false
|
minifyEnabled false
|
||||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||||
|
if (releaseKeystoreFile != null) {
|
||||||
|
signingConfig signingConfigs.release
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_21
|
sourceCompatibility JavaVersion.VERSION_21
|
||||||
targetCompatibility JavaVersion.VERSION_21
|
targetCompatibility JavaVersion.VERSION_21
|
||||||
}
|
}
|
||||||
kotlinOptions {
|
|
||||||
jvmTarget = '21'
|
|
||||||
}
|
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
compose = true
|
compose = true
|
||||||
|
buildConfig = true
|
||||||
}
|
}
|
||||||
packaging {
|
packaging {
|
||||||
resources {
|
resources {
|
||||||
@@ -48,6 +68,12 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
compilerOptions {
|
||||||
|
jvmTarget.set(JvmTarget.JVM_21)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
// Core Android
|
// Core Android
|
||||||
implementation 'androidx.core:core-ktx:1.12.0'
|
implementation 'androidx.core:core-ktx:1.12.0'
|
||||||
@@ -68,16 +94,15 @@ dependencies {
|
|||||||
// ViewModel
|
// ViewModel
|
||||||
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'
|
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'
|
||||||
|
|
||||||
// Room (use kapt for annotation processing). Bump to version compatible with Kotlin 2.2 metadata
|
// Room (KSP for annotation processing)
|
||||||
implementation 'androidx.room:room-runtime:2.7.0'
|
implementation 'androidx.room:room-runtime:2.7.0'
|
||||||
implementation 'androidx.room:room-ktx:2.7.0'
|
implementation 'androidx.room:room-ktx:2.7.0'
|
||||||
kapt 'androidx.room:room-compiler:2.7.0'
|
ksp 'androidx.room:room-compiler:2.7.0'
|
||||||
|
|
||||||
// Retrofit
|
// Retrofit
|
||||||
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
|
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
|
||||||
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
|
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
|
||||||
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
|
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
|
||||||
kapt 'com.squareup.retrofit2:retrofit:2.9.0'
|
|
||||||
|
|
||||||
// Coroutines
|
// Coroutines
|
||||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
<application
|
<application
|
||||||
android:name=".CollabTableApplication"
|
android:name=".CollabTableApplication"
|
||||||
android:allowBackup="true"
|
android:allowBackup="false"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.collabtable.app.data.api
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import com.collabtable.app.BuildConfig
|
||||||
import com.collabtable.app.data.preferences.PreferencesManager
|
import com.collabtable.app.data.preferences.PreferencesManager
|
||||||
import com.collabtable.app.utils.Logger
|
import com.collabtable.app.utils.Logger
|
||||||
import okhttp3.Interceptor
|
import okhttp3.Interceptor
|
||||||
@@ -17,9 +18,13 @@ object ApiClient {
|
|||||||
private var retrofit: Retrofit? = null
|
private var retrofit: Retrofit? = null
|
||||||
private var context: Context? = null
|
private var context: Context? = null
|
||||||
|
|
||||||
|
// Bodies and the Authorization header carry the sync token and user data, so
|
||||||
|
// only debug builds log them, and the header is redacted in every build.
|
||||||
private val loggingInterceptor =
|
private val loggingInterceptor =
|
||||||
HttpLoggingInterceptor().apply {
|
HttpLoggingInterceptor().apply {
|
||||||
level = HttpLoggingInterceptor.Level.BODY
|
level =
|
||||||
|
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
|
||||||
|
redactHeader("Authorization")
|
||||||
}
|
}
|
||||||
|
|
||||||
private val authInterceptor =
|
private val authInterceptor =
|
||||||
@@ -116,6 +121,18 @@ object ApiClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cleartext stays allowed so LAN servers work (see network_security_config.xml). The
|
||||||
|
// warning makes the trade-off visible: the sync token and data are not encrypted in transit.
|
||||||
|
private fun warnIfCleartext(url: String) {
|
||||||
|
if (url.startsWith("http://", ignoreCase = true)) {
|
||||||
|
Logger.w(
|
||||||
|
"HTTP",
|
||||||
|
"API base URL uses plain HTTP: the sync token and data are not encrypted in transit. " +
|
||||||
|
"Use HTTPS for any server outside your LAN.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun initialize(context: Context) {
|
fun initialize(context: Context) {
|
||||||
this.context = context.applicationContext
|
this.context = context.applicationContext
|
||||||
val prefs = PreferencesManager.getInstance(context)
|
val prefs = PreferencesManager.getInstance(context)
|
||||||
@@ -124,6 +141,7 @@ object ApiClient {
|
|||||||
Logger.i("HTTP", "API base URL initialized to $baseUrl")
|
Logger.i("HTTP", "API base URL initialized to $baseUrl")
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
|
warnIfCleartext(baseUrl)
|
||||||
retrofit = buildRetrofit()
|
retrofit = buildRetrofit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,6 +151,7 @@ object ApiClient {
|
|||||||
Logger.i("HTTP", "API base URL set to $baseUrl")
|
Logger.i("HTTP", "API base URL set to $baseUrl")
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
|
warnIfCleartext(baseUrl)
|
||||||
retrofit = buildRetrofit()
|
retrofit = buildRetrofit()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import retrofit2.http.Query
|
|||||||
|
|
||||||
data class SyncRequest(
|
data class SyncRequest(
|
||||||
val lastSyncTimestamp: Long,
|
val lastSyncTimestamp: Long,
|
||||||
|
val lastSyncToken: Long,
|
||||||
val lists: List<CollabList>,
|
val lists: List<CollabList>,
|
||||||
val fields: List<Field>,
|
val fields: List<Field>,
|
||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
@@ -24,6 +25,9 @@ data class SyncResponse(
|
|||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
val itemValues: List<ItemValue>,
|
val itemValues: List<ItemValue>,
|
||||||
val serverTimestamp: Long,
|
val serverTimestamp: Long,
|
||||||
|
val serverChangeToken: Long,
|
||||||
|
val nextSyncToken: Long,
|
||||||
|
val hasMore: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
interface CollabTableApi {
|
interface CollabTableApi {
|
||||||
|
|||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
|
||||||
|
internal data class SyncPageProgress(
|
||||||
|
val cursor: Long,
|
||||||
|
val firstPage: Boolean = true,
|
||||||
|
) {
|
||||||
|
fun after(response: SyncResponse): SyncPageProgress? {
|
||||||
|
if (response.hasMore && response.nextSyncToken <= cursor) {
|
||||||
|
throw IllegalStateException("Sync page cursor did not advance")
|
||||||
|
}
|
||||||
|
return if (response.hasMore) SyncPageProgress(response.nextSyncToken, firstPage = false) else null
|
||||||
|
}
|
||||||
|
}
|
||||||
+144
-126
@@ -52,6 +52,12 @@ class SyncRepository(
|
|||||||
return prefs.getLong("last_server_sync_ts", 0)
|
return prefs.getLong("last_server_sync_ts", 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getLastServerSyncToken(): Long = prefs.getLong("last_server_sync_token", 0)
|
||||||
|
|
||||||
|
private fun setLastServerSyncToken(token: Long) {
|
||||||
|
prefs.edit().putLong("last_server_sync_token", token).apply()
|
||||||
|
}
|
||||||
|
|
||||||
private fun setLastServerSyncTs(ts: Long) {
|
private fun setLastServerSyncTs(ts: Long) {
|
||||||
prefs
|
prefs
|
||||||
.edit()
|
.edit()
|
||||||
@@ -101,30 +107,29 @@ class SyncRepository(
|
|||||||
return@withContext Result.success(Unit)
|
return@withContext Result.success(Unit)
|
||||||
}
|
}
|
||||||
val lastServerTs = getLastServerSyncTs()
|
val lastServerTs = getLastServerSyncTs()
|
||||||
|
val lastServerToken = getLastServerSyncToken()
|
||||||
val lastLocalTs = getLastLocalSyncTs()
|
val lastLocalTs = getLastLocalSyncTs()
|
||||||
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
||||||
// updates that happen during an in-flight sync. We'll advance the local watermark
|
// updates that happen during an in-flight sync. We'll advance the local watermark
|
||||||
// to this snapshot once the sync completes successfully.
|
// to this snapshot once the sync completes successfully.
|
||||||
val localSnapshotTs = System.currentTimeMillis()
|
val localSnapshotTs = System.currentTimeMillis()
|
||||||
val isInitialSync = lastServerTs == 0L
|
// If our local DB appears empty or this install still has the legacy timestamp cursor,
|
||||||
|
// request a full down-sync through the server change-token cursor.
|
||||||
|
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
||||||
|
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
||||||
|
val effectiveLastServerToken =
|
||||||
|
when {
|
||||||
|
// App start can request a full down-sync regardless of local contents
|
||||||
|
forceFullDown && (lastServerTs > 0L || lastServerToken > 0L) -> 0L
|
||||||
|
// Fallback: if local has no lists or items but we have a watermark, do a full down-sync
|
||||||
|
(lastServerTs > 0L || lastServerToken > 0L) && (!hasAnyLists && !hasAnyItems) -> 0L
|
||||||
|
else -> lastServerToken
|
||||||
|
}
|
||||||
|
val isInitialSync = effectiveLastServerToken == 0L
|
||||||
if (isInitialSync) {
|
if (isInitialSync) {
|
||||||
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
||||||
}
|
}
|
||||||
|
if (effectiveLastServerToken == 0L && (lastServerTs > 0L || lastServerToken > 0L)) {
|
||||||
// If our local DB appears empty but we have a nonzero server watermark (e.g., after reinstall
|
|
||||||
// or clearing local data), request a one-time full down-sync by resetting the effective
|
|
||||||
// lastSyncTimestamp to 0 for this request. This avoids permanently missing historical rows.
|
|
||||||
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
|
||||||
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
|
||||||
val effectiveLastServerTs =
|
|
||||||
when {
|
|
||||||
// App start can request a full down-sync regardless of local contents
|
|
||||||
forceFullDown && lastServerTs > 0L -> 0L
|
|
||||||
// Fallback: if local looks empty but we have a watermark, do a one-time full down-sync
|
|
||||||
lastServerTs > 0L && (!hasAnyLists || !hasAnyItems) -> 0L
|
|
||||||
else -> lastServerTs
|
|
||||||
}
|
|
||||||
if (effectiveLastServerTs == 0L && lastServerTs > 0L) {
|
|
||||||
val reason = if (forceFullDown) "startup forced" else "local empty"
|
val reason = if (forceFullDown) "startup forced" else "local empty"
|
||||||
Logger.w("Sync", "$reason full down-sync requested")
|
Logger.w("Sync", "$reason full down-sync requested")
|
||||||
}
|
}
|
||||||
@@ -162,125 +167,137 @@ class SyncRepository(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send to server and get updates
|
// Upload local changes once, then follow the server's bounded pages without
|
||||||
val syncRequest =
|
// replaying the same writes on every request.
|
||||||
SyncRequest(
|
var cursor = effectiveLastServerToken
|
||||||
lastSyncTimestamp = effectiveLastServerTs,
|
var pageProgress = SyncPageProgress(cursor)
|
||||||
lists = localLists,
|
var serverTimestamp = lastServerTs
|
||||||
fields = localFields,
|
while (true) {
|
||||||
items = localItems,
|
val response =
|
||||||
itemValues = localValues,
|
try {
|
||||||
)
|
api.sync(
|
||||||
|
SyncRequest(
|
||||||
// HTTP-only sync
|
lastSyncTimestamp = lastServerTs,
|
||||||
val response =
|
lastSyncToken = pageProgress.cursor,
|
||||||
try {
|
lists = if (pageProgress.firstPage) localLists else emptyList(),
|
||||||
api.sync(syncRequest)
|
fields = if (pageProgress.firstPage) localFields else emptyList(),
|
||||||
} catch (e: UnknownHostException) {
|
items = if (pageProgress.firstPage) localItems else emptyList(),
|
||||||
// Host could not be resolved; apply exponential backoff and surface a warning once.
|
itemValues = if (pageProgress.firstPage) localValues else emptyList(),
|
||||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
),
|
||||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
)
|
||||||
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
} catch (e: UnknownHostException) {
|
||||||
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
|
|
||||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||||
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||||
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
||||||
}
|
} catch (e: Exception) {
|
||||||
throw e
|
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
|
||||||
}
|
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||||
if (!response.isSuccessful) {
|
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||||
if (response.code() == 401) {
|
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||||
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
|
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
||||||
setLastServerSyncTs(0)
|
|
||||||
setLastLocalSyncTs(0)
|
|
||||||
// Apply exponential backoff on repeated auth failures
|
|
||||||
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
|
||||||
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
|
||||||
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
|
||||||
}
|
|
||||||
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
|
||||||
}
|
|
||||||
val syncResponse = response.body()!!
|
|
||||||
// Only log receive when there are actual server changes
|
|
||||||
val inTotal =
|
|
||||||
syncResponse.lists.size +
|
|
||||||
syncResponse.fields.size +
|
|
||||||
syncResponse.items.size +
|
|
||||||
syncResponse.itemValues.size
|
|
||||||
if (inTotal > 0) {
|
|
||||||
Logger.i(
|
|
||||||
"Sync",
|
|
||||||
"[IN] Received changes " +
|
|
||||||
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
|
|
||||||
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply server changes to local database atomically in correct order
|
|
||||||
database.withTransaction {
|
|
||||||
// 1) Upsert lists first, preserving local orderIndex when present
|
|
||||||
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
|
||||||
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
|
||||||
val localUpdatedMap = database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
|
||||||
|
|
||||||
val listsPreservingOrder =
|
|
||||||
syncResponse.lists
|
|
||||||
.filter { incoming ->
|
|
||||||
val localUpdated = localUpdatedMap[incoming.id]
|
|
||||||
localUpdated == null || incoming.updatedAt >= localUpdated
|
|
||||||
}.map { incoming ->
|
|
||||||
val localOrder = localIdToOrder[incoming.id]
|
|
||||||
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
|
|
||||||
}
|
}
|
||||||
|
throw e
|
||||||
if (listsPreservingOrder.isNotEmpty()) {
|
|
||||||
database.listDao().insertLists(listsPreservingOrder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build set of existing list ids to guard child inserts
|
|
||||||
val existingListIds = database.listDao().getAllListIds().toSet()
|
|
||||||
|
|
||||||
// 2) Filter and upsert fields whose parent list exists
|
|
||||||
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
|
|
||||||
if (filteredFields.size != syncResponse.fields.size) {
|
|
||||||
val dropped = syncResponse.fields.size - filteredFields.size
|
|
||||||
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
|
|
||||||
}
|
|
||||||
if (filteredFields.isNotEmpty()) {
|
|
||||||
database.fieldDao().insertFields(filteredFields)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3) Filter and upsert items whose parent list exists
|
|
||||||
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
|
|
||||||
if (filteredItems.size != syncResponse.items.size) {
|
|
||||||
val dropped = syncResponse.items.size - filteredItems.size
|
|
||||||
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
|
|
||||||
}
|
|
||||||
if (filteredItems.isNotEmpty()) {
|
|
||||||
database.itemDao().insertItems(filteredItems)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4) Filter item values to only those whose parents (item and field) exist locally
|
|
||||||
val existingItemIds = database.itemDao().getAllItemIds().toSet()
|
|
||||||
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
|
|
||||||
val filteredValues =
|
|
||||||
syncResponse.itemValues.filter { v ->
|
|
||||||
v.itemId in existingItemIds && v.fieldId in existingFieldIds
|
|
||||||
}
|
}
|
||||||
if (filteredValues.size != syncResponse.itemValues.size) {
|
if (!response.isSuccessful) {
|
||||||
val dropped = syncResponse.itemValues.size - filteredValues.size
|
if (response.code() == 401) {
|
||||||
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
|
setLastLocalSyncTs(0)
|
||||||
|
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
||||||
|
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
||||||
|
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
||||||
|
}
|
||||||
|
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
||||||
}
|
}
|
||||||
if (filteredValues.isNotEmpty()) {
|
val syncResponse = response.body() ?: return@withContext Result.failure(Exception("Sync response was empty"))
|
||||||
database.itemValueDao().insertValues(filteredValues)
|
val inTotal =
|
||||||
|
syncResponse.lists.size +
|
||||||
|
syncResponse.fields.size +
|
||||||
|
syncResponse.items.size +
|
||||||
|
syncResponse.itemValues.size
|
||||||
|
if (inTotal > 0) {
|
||||||
|
Logger.i(
|
||||||
|
"Sync",
|
||||||
|
"[IN] Received changes " +
|
||||||
|
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
|
||||||
|
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
database.withTransaction {
|
||||||
|
// 1) Upsert lists first, preserving local orderIndex when present
|
||||||
|
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
||||||
|
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
||||||
|
val localUpdatedMap =
|
||||||
|
database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
||||||
|
|
||||||
|
val listsPreservingOrder =
|
||||||
|
syncResponse.lists
|
||||||
|
.filter { incoming ->
|
||||||
|
val localUpdated = localUpdatedMap[incoming.id]
|
||||||
|
localUpdated == null || incoming.updatedAt >= localUpdated
|
||||||
|
}.map { incoming ->
|
||||||
|
val localOrder = localIdToOrder[incoming.id]
|
||||||
|
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
|
||||||
|
}
|
||||||
|
|
||||||
|
if (listsPreservingOrder.isNotEmpty()) {
|
||||||
|
database.listDao().insertLists(listsPreservingOrder)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build set of existing list ids to guard child inserts
|
||||||
|
val existingListIds = database.listDao().getAllListIds().toSet()
|
||||||
|
|
||||||
|
// 2) Filter and upsert fields whose parent list exists
|
||||||
|
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
|
||||||
|
if (filteredFields.size != syncResponse.fields.size) {
|
||||||
|
val dropped = syncResponse.fields.size - filteredFields.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredFields.isNotEmpty()) {
|
||||||
|
database.fieldDao().insertFields(filteredFields)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) Filter and upsert items whose parent list exists
|
||||||
|
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
|
||||||
|
if (filteredItems.size != syncResponse.items.size) {
|
||||||
|
val dropped = syncResponse.items.size - filteredItems.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredItems.isNotEmpty()) {
|
||||||
|
database.itemDao().insertItems(filteredItems)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) Filter item values to only those whose parents (item and field) exist locally
|
||||||
|
val existingItemIds = database.itemDao().getAllItemIds().toSet()
|
||||||
|
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
|
||||||
|
val filteredValues =
|
||||||
|
syncResponse.itemValues.filter { v ->
|
||||||
|
v.itemId in existingItemIds && v.fieldId in existingFieldIds
|
||||||
|
}
|
||||||
|
if (filteredValues.size != syncResponse.itemValues.size) {
|
||||||
|
val dropped = syncResponse.itemValues.size - filteredValues.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredValues.isNotEmpty()) {
|
||||||
|
database.itemValueDao().insertValues(filteredValues)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val nextPage = try {
|
||||||
|
pageProgress.after(syncResponse)
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
return@withContext Result.failure(e)
|
||||||
|
}
|
||||||
|
cursor = syncResponse.nextSyncToken
|
||||||
|
serverTimestamp = syncResponse.serverTimestamp
|
||||||
|
if (nextPage == null) break
|
||||||
|
pageProgress = nextPage
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update watermarks: server ts from response, local ts from device clock now
|
// Save the server-owned change cursor only after every page has been applied.
|
||||||
setLastServerSyncTs(syncResponse.serverTimestamp)
|
setLastServerSyncToken(cursor)
|
||||||
|
setLastServerSyncTs(serverTimestamp)
|
||||||
// Advance local watermark to the snapshot taken before reading local changes.
|
// Advance local watermark to the snapshot taken before reading local changes.
|
||||||
// This avoids missing updates that occurred while the sync was in-flight.
|
// This avoids missing updates that occurred while the sync was in-flight.
|
||||||
setLastLocalSyncTs(localSnapshotTs)
|
setLastLocalSyncTs(localSnapshotTs)
|
||||||
@@ -298,6 +315,7 @@ class SyncRepository(
|
|||||||
// If WS indicated unauthorized, align behavior with HTTP path
|
// If WS indicated unauthorized, align behavior with HTTP path
|
||||||
if (e.message?.contains("Unauthorized") == true) {
|
if (e.message?.contains("Unauthorized") == true) {
|
||||||
setLastServerSyncTs(0)
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
setLastLocalSyncTs(0)
|
setLastLocalSyncTs(0)
|
||||||
}
|
}
|
||||||
// Do not reset network backoff here; it's managed where thrown.
|
// Do not reset network backoff here; it's managed where thrown.
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SyncPageProgressTest {
|
||||||
|
@Test
|
||||||
|
fun `first page advances and marks later pages as download only`() {
|
||||||
|
val first = SyncPageProgress(cursor = 4)
|
||||||
|
|
||||||
|
assertTrue(first.firstPage)
|
||||||
|
val second = first.after(response(nextToken = 9, hasMore = true))
|
||||||
|
|
||||||
|
assertEquals(9, second?.cursor)
|
||||||
|
assertFalse(second?.firstPage ?: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `final page ends the loop`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9, firstPage = false)
|
||||||
|
|
||||||
|
assertNull(progress.after(response(nextToken = 12, hasMore = false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `non advancing page is rejected`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9)
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException::class.java) {
|
||||||
|
progress.after(response(nextToken = 9, hasMore = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun response(nextToken: Long, hasMore: Boolean) =
|
||||||
|
SyncResponse(
|
||||||
|
lists = emptyList(),
|
||||||
|
fields = emptyList(),
|
||||||
|
items = emptyList(),
|
||||||
|
itemValues = emptyList(),
|
||||||
|
serverTimestamp = 0,
|
||||||
|
serverChangeToken = nextToken,
|
||||||
|
nextSyncToken = nextToken,
|
||||||
|
hasMore = hasMore,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
plugins {
|
plugins {
|
||||||
id 'com.android.application' version '8.8.0' apply false
|
id 'com.android.application' version '9.5.0' apply false
|
||||||
id 'com.android.library' version '8.8.0' apply false
|
id 'com.android.library' version '9.5.0' apply false
|
||||||
id 'org.jetbrains.kotlin.android' version '2.2.21' apply false
|
id 'org.jetbrains.kotlin.plugin.compose' version '2.3.20' apply false
|
||||||
id 'org.jetbrains.kotlin.plugin.compose' version '2.2.21' apply false
|
id 'com.google.devtools.ksp' version '2.3.13' apply false
|
||||||
id 'org.jlleitschuh.gradle.ktlint' version '14.0.1' apply false
|
id 'org.jlleitschuh.gradle.ktlint' version '14.0.1' apply false
|
||||||
id 'io.gitlab.arturbosch.detekt' version '1.23.8' apply false
|
id 'io.gitlab.arturbosch.detekt' version '1.23.8' apply false
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
+252
@@ -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" "$@"
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Performance Report — CollabTable
|
||||||
|
|
||||||
|
- **Project:** CollabTable
|
||||||
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 6aec03f on main
|
||||||
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
||||||
|
- **Updated:** 2026-10-20 — P-004 now uses bounded keyset pages for collection endpoints and sync; Android follows all sync pages. Database-backed behavior remains unverified locally because no test database is available.
|
||||||
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). Verification limits are recorded in `QUALITY_REPORT.md`.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
|
| High | 2 | 1 | 0 | 1 |
|
||||||
|
| Medium | 5 | 5 | 0 | 0 |
|
||||||
|
| Low | 3 | 0 | 0 | 3 |
|
||||||
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
|
The dashboard still sends the full dataset after a change, and sync writes rows one at a time inside one transaction. Collection endpoints and sync are now paged, while the updated-at indexes are present. Database runtime and load behavior still need verification on PostgreSQL.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High** · Fixed
|
||||||
|
- **Location:** `backend/web.go:9-29` (four unpaginated queries), `backend/data.go:68-204` (no LIMIT in any query builder), `backend/web.go:74-76` (`no-store`), `frontend/src/lib/features/lists/listsData.svelte.js:4,10`, `frontend/src/lib/api.js:27-29`
|
||||||
|
- **Description:** `createOverviewData()` polls `/web/data` with `refetchInterval: 5000`. Each response contains every non-deleted list, every field, every item and every item value, with no pagination, no `since` filter and no HTTP caching (`Cache-Control: no-store`). The server already computes per-list effective update times (`web.go:31-72`), but the client has no way to use them to skip unchanged data. TanStack Query's default is to poll only while the tab is visible, so each open dashboard pays this cost.
|
||||||
|
- **Impact:** Transfer, JSON encoding and client re-rendering all scale with total data size rather than with the amount of change. With a few thousand items and several viewers this is continuous multi-megabyte traffic and repeated full re-renders.
|
||||||
|
- **Recommendation:** Serve changes incrementally with a `since` cursor (as sync already does), or add an ETag derived from the maximum `updatedat` and answer `304` when nothing changed, dropping `no-store` for that path. Compress the response (see P-006). Consider a longer interval or server push for the dashboard.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `/web/data` now sends a weak ETag over the response data (the per-request timestamp is excluded), answers `304` when `If-None-Match` matches, and uses `Cache-Control: private, no-cache` instead of `no-store`, so an unchanged poll sends no body. A `max(updatedat)` validator was rejected because client-supplied timestamps can move backwards and hard deletes leave no trace. Residual: changed data is still sent in full, the server still runs the four queries on every poll, and browsers may now keep a private on-disk copy of the dashboard data, which `no-store` previously prevented. Files: `backend/web.go`, `backend/data.go` (stable tie-break order), `backend/web_test.go`.
|
||||||
|
|
||||||
|
### P-002 · Sync issues several statements per row inside one long transaction · **High** · Open
|
||||||
|
- **Location:** `backend/sync.go:61-209` (the transaction closure). For item values, `sync.go:172-207`: `listid` lookup (`:175`), `EXISTS` on items (`:185`), optional stub insert (`:193`), upsert (`:198`) and a notification insert (`:206`). Per-row upserts at `sync.go:64-79`, `:104-126`, `:149-164`. Request size is capped at 50 MB by `backend/server.go:253-259`.
|
||||||
|
- **Description:** Every list, field, item and value in a request is processed one at a time with separate statements. Each item value needs four to five round trips, plus a notification row per change, and the whole batch holds row locks until commit. There is no cap on the number of rows per request.
|
||||||
|
- **Impact:** An initial sync or a large offline push (potentially thousands of rows) becomes thousands of sequential round trips. The transaction stays open for the whole batch, and the 60-second `WriteTimeout` (`server.go:123`) can cut the request off. The device then retries and repeats the same work, and concurrent devices contend on the same rows.
|
||||||
|
- **Recommendation:** Batch the writes, using `pgx.Batch` or multi-row `INSERT ... SELECT FROM unnest(...)` upserts per table. Load the field-to-list map once per request instead of once per value. Insert notifications as one multi-row statement per request. Cap rows per request, return `413` above the cap, and have clients chunk their pushes.
|
||||||
|
- **Status:** Open 2026-10-19 — partly addressed: `backend/sync.go` now resolves each request's fields and items in two statements (`valueReferences`) instead of up to two lookups per value, which removes the per-value reads. Still needed: the list, field, item and value upserts and their notification inserts still run one statement at a time inside one transaction, so this needs `pgx.Batch` or `unnest` bulk upserts; the per-request row cap with `413` is a client-facing change and needs CollabTableAndroid to chunk pushes first. Not measured against PostgreSQL, since none is available in this environment.
|
||||||
|
|
||||||
|
### P-003 · No index on `updatedat`, so every delta query scans the table · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/db.go:40-189` (indexes exist only on `fields.listid`, `items.listid`, `item_values.itemid`, `item_values.fieldid`, and notifications `createdat` and `listid`, at `:83-86` and `:97-98`). Queries filtering on `updatedat`: `backend/data.go:75`, `:108`, `:145`, `:178`; sync calls at `backend/sync.go:220-235`.
|
||||||
|
- **Description:** Sync and `/web/data` filter with `updatedat >= $1`, but `lists`, `fields`, `items` and `item_values` have no index on `updatedat`. Rows are soft-deleted and never physically removed, so the tables only grow.
|
||||||
|
- **Impact:** Every sync from every device performs four full table scans, and the cost grows with history rather than with recent change volume.
|
||||||
|
- **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `initSchema` creates indexes on `updatedat` for lists, fields, items and item values, so delta queries stop scanning whole tables. The index builds run at startup and briefly block writes on large tables. Files: backend/db.go.
|
||||||
|
|
||||||
|
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/pagination.go` (bounded keyset pages); `backend/data.go` collection handlers; `backend/sync.go:326-405` (bounded sync response); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt` (client page loop).
|
||||||
|
- **Description:** Collection endpoints now return pages of at most 500 rows (default 200), with opaque keyset cursors and `hasMore`. Sync returns at most 500 changes with a server token cursor; Android requests all pages before saving the cursor.
|
||||||
|
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
|
||||||
|
- **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up.
|
||||||
|
- **Status:** Fixed 2026-10-20 — Collection queries use keyset cursors with a default page of 200 and maximum of 500; sync responses are capped at 500 and include `hasMore` and `nextSyncToken`. Android uploads local changes on the first request, then loops through server pages and stores the final cursor only after completion. Collection GET responses now wrap `items`, `nextCursor` and `hasMore` instead of returning bare arrays. Old sync clients that omit `lastSyncToken` receive 400 and must be upgraded with the backend. PostgreSQL runtime tests are written but skipped locally; see `QUALITY_REPORT.md` Verification. Files: `backend/pagination.go`, `backend/data.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
|
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed
|
||||||
|
- **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index).
|
||||||
|
- **Description:** The helpers are linear scans over the complete data set, and they run for every visible row and card. Because each 5-second poll replaces the arrays, every derived value is recomputed on every poll.
|
||||||
|
- **Impact:** Cost per render is roughly visible rows times total values. With a large data set this appears as delayed input and scroll jank.
|
||||||
|
- **Recommendation:** Build lookup maps once per data change in a `$derived` (a `Map` keyed by `listId`, by `itemId`, and by `itemId + fieldId`). Pass pre-grouped slices into the card and row components. Rely on TanStack's structural sharing so unchanged data keeps its references.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Fields, items and item values are grouped once per data change with `groupByKey`, and each grid card, table row and detail row reads only its own slice. `itemValuesFor` is removed because it had no other callers. Files: frontend/src/lib/features/lists/listHelpers.js, frontend/src/routes/+page.svelte, frontend/src/routes/lists/[id]/+page.svelte, frontend/src/lib/components/lists/ListsGrid.svelte, frontend/src/lib/components/lists/ListsTable.svelte.
|
||||||
|
|
||||||
|
### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/server.go:118-125` (plain `http.Server`, no compression middleware), `backend/server.go:292-316` (`spaFileServer` sets no `Cache-Control`), `backend/web.go:74-76` (`no-store` on `/web/data`).
|
||||||
|
- **Description:** JSON responses (`/web/data`, `/api/sync`, `/api/lists`) are sent uncompressed. Static build output, including content-hashed Vite assets, is served with no cache-control, and the embedded filesystem provides no modification times for conditional requests.
|
||||||
|
- **Impact:** Large JSON bodies transfer several times more bytes than necessary, and browsers refetch the whole app bundle on each visit.
|
||||||
|
- **Recommendation:** Add gzip or brotli middleware, or enable it at the reverse proxy. Set `Cache-Control: public, max-age=31536000, immutable` for `_app/immutable/*` and `no-cache` for `index.html`. Add ETags for `/web/data` (see P-001).
|
||||||
|
- **Status:** Fixed 2026-10-19 — Responses are gzip-compressed for clients that accept it, `_app/immutable/` assets are cached for a year as immutable, and `index.html` and other static files are sent with `no-cache`. Files: backend/server.go, backend/server_test.go.
|
||||||
|
|
||||||
|
### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/server.go:253-259` (`decodeJSON` uses `io.LimitReader(r.Body, 50*1024*1024)`), used by `backend/sync.go:46` and by the write handlers in `backend/data.go`.
|
||||||
|
- **Description:** Every write endpoint accepts up to 50 MB of JSON and decodes it fully into Go structs. `io.LimitReader` truncates silently, so an oversized body fails with a confusing decode error instead of `413`. These handlers have no concurrency cap, so each concurrent request can allocate its full decode buffer.
|
||||||
|
- **Impact:** A few concurrent large requests can exhaust memory. It is also an easy denial-of-service vector (see the rate-limiting note in the Security report).
|
||||||
|
- **Recommendation:** Use `http.MaxBytesReader` with per-route limits (for example 1 to 5 MB for single-entity writes, and a higher bound for sync), returning `413` when exceeded. Bound concurrent sync transactions with a semaphore sized below `DATABASE_MAX_CONNS`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Request bodies are limited with `http.MaxBytesReader` (2 MB for single-entity writes, 50 MB for sync), oversized bodies get 413, and at most four syncs run at once. Single-entity writes above 2 MB now fail with 413; the shared auth proxy already caps bodies at 128 KB. Files: backend/server.go, backend/sync.go, backend/data.go.
|
||||||
|
|
||||||
|
### P-008 · One notification row per changed row, on every write path · **Low**
|
||||||
|
- **Location:** `backend/sync.go:79`, `:126`, `:164`, `:206`; `backend/data.go:256`, `:302`, `:364`, `:418`, `:507`, `:561`, `:605`, `:621`; retention in `backend/db.go:212-230`; polling in `backend/web.go:92-141` (`LIMIT 500` at `:109`).
|
||||||
|
- **Description:** Each changed row inserts its own notification. A 1,000-value sync writes 1,000 extra rows, and each one is later read by the Android poller.
|
||||||
|
- **Impact:** Write amplification on the hot path and extra cleanup load. Clients polling 500 notifications at a time may need several polls to catch up after a bulk change.
|
||||||
|
- **Recommendation:** Coalesce notifications per list per request, so a sync produces one row per affected list. Alternatively, drop per-row notifications and rely on the `updatedat` delta.
|
||||||
|
|
||||||
|
### P-009 · Docker build context and cache layering can be tighter · **Low**
|
||||||
|
- **Location:** `docker/Dockerfile:34-35` (`COPY shared/backend/` happens before `go mod download`); `.dockerignore` excludes `.git`, `node_modules`, `data/` and `collabtable.db`, but not `CollabTableAndroid/`, `.github/` or `**/node_modules` under `shared/`.
|
||||||
|
- **Description:** Any edit under `shared/backend` invalidates the module-download layer, because the source is copied before `go mod download`. The build context also includes the whole Android project and CI files, which slows context transfer.
|
||||||
|
- **Impact:** Slower builds and avoidable cache misses in CI.
|
||||||
|
- **Recommendation:** Copy only `shared/backend/go.mod` and `go.sum` before `go mod download`, and copy the rest of `shared/backend` afterwards. Add `CollabTableAndroid/`, `.github/` and `**/node_modules` to `.dockerignore`.
|
||||||
|
|
||||||
|
### P-010 · No statement timeout or per-query budget on the database pool · **Low**
|
||||||
|
- **Location:** `shared/backend/postgres/postgres.go:114-121` (pool defaults: `MaxConns: 20`, no `statement_timeout`); `backend/sync.go:61` (the transaction runs under the request context).
|
||||||
|
- **Description:** Queries are bounded only by the request context. Nothing caps statement run time at the database, and a long sync transaction holds a pool connection for its full duration.
|
||||||
|
- **Impact:** A slow query or a large sync can hold one of 20 connections for longer than intended and starve other requests.
|
||||||
|
- **Recommendation:** Set `statement_timeout` (and optionally `lock_timeout`) as pool runtime parameters, and set `DATABASE_MAX_CONNS` explicitly for each environment. Combine this with the batching in P-002.
|
||||||
|
|
||||||
|
### P-011 · Checked, no issue found · **Info**
|
||||||
|
- **Location:** `shared/backend/authclient/client.go:116` (5-second HTTP client timeout on outbound identity calls); `docker/Dockerfile:41-47` (final stage is `FROM scratch`, runs as `65534`, and contains only the binary and CA bundle); `backend/db.go:83-98` (indexes on the foreign-key and list-scoped lookup columns, and on notification `createdat` for cleanup and polling).
|
||||||
|
- **Description:** Outbound identity calls have a timeout, the runtime image is minimal and contains no build tools, and the main lookup paths are indexed.
|
||||||
|
- **Impact:** None. Recorded so these areas are not re-checked.
|
||||||
|
- **Recommendation:** None.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Go and frontend verification results are in `QUALITY_REPORT.md`. No load test ran. Estimates should be confirmed with realistic data across several devices.
|
||||||
|
- AuthGuard's own performance is outside this repository and was not analyzed.
|
||||||
|
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
|
||||||
|
- The production frontend build passed after the consumer wired the local design-tokens package and preserved shared-package symlinks; the resulting bundle size was reported by Vite but not benchmarked in a browser.
|
||||||
|
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# Code Quality Report — CollabTable
|
||||||
|
|
||||||
|
- **Project:** CollabTable
|
||||||
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 6aec03f on main
|
||||||
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
|
- **Updated:** 2026-10-20 — Q-006 now uses a server-side change token; Q-004 remains partly open because its Android JVM test and PostgreSQL integration tests could not be run here.
|
||||||
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions.
|
||||||
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including the tests), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. Verification commands and results are below.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
|
| High | 0 | 0 | 0 | 0 |
|
||||||
|
| Medium | 6 | 5 | 0 | 1 |
|
||||||
|
| Low | 8 | 0 | 0 | 8 |
|
||||||
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
|
The backend is small and readable, but its transactional and delete logic is duplicated across the REST and sync paths and has drifted apart. A few error-handling assumptions are wrong, and the data layer has essentially no test coverage.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/notifications.go:51-57` (`ignoreNotificationError`); called inside transactions at `backend/sync.go:79`, `:126`, `:164`, `:206` and `backend/data.go:453`.
|
||||||
|
- **Description:** `ignoreNotificationError` says a failed notification "must never roll back the data mutation". When the notification insert runs inside the transaction, PostgreSQL marks the transaction as aborted after any failing statement, so the next statement fails and the commit cannot succeed. The error is only logged, which makes the function look like it tolerates the failure, but the whole sync then returns `500 Sync failed` after rolling back. The comment is wrong for these paths.
|
||||||
|
- **Impact:** A transient failure of a notification insert turns a successful write into a failed sync, and the client retries the same payload. Maintainers reading the comment will assume the opposite of what happens.
|
||||||
|
- **Recommendation:** Isolate the notification insert in a savepoint (a nested `tx.Begin` in pgx, or `SAVEPOINT` and `ROLLBACK TO SAVEPOINT`), or write notifications after commit. Update the comment to match the actual behavior.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Notification inserts inside a transaction now run in a savepoint (`enqueueNotificationInTx`), so a failed insert rolls back only the notification and the data change still commits. Each such notification adds two statements (savepoint and release). Files: backend/notifications.go, backend/sync.go, backend/data.go.
|
||||||
|
|
||||||
|
### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/data.go:309-321` (REST list delete sets only `lists.isdeleted`); `backend/sync.go:81-91` (sync list delete also cascades to fields, items and values); `backend/data.go:420-455` (field delete cascades only when no active fields remain); `backend/data.go:609-621` (item delete updates the item, then deletes its values in a separate statement whose error is discarded at `:620`, and skips the notification at `:618-619` if the re-read fails).
|
||||||
|
- **Description:** The same logical operations (delete a list, delete an item) leave different state depending on the entry point. A list deleted through REST keeps its fields, items and values active, while the same delete through sync removes the children. `/web/data` filters out deleted lists but still returns the active items and values that belong to them (`backend/web.go:31-72`). Item deletion is not atomic and can leave orphaned values if the second statement fails.
|
||||||
|
- **Impact:** The dashboard, the Android client and sync can disagree about what exists, and orphaned values are silently accepted.
|
||||||
|
- **Recommendation:** Implement `deleteList`, `deleteField` and `deleteItem` once, each inside a transaction, and call them from both REST and sync. Check every error.
|
||||||
|
- **Status:** Fixed 2026-10-19 — REST and sync now share `cascadeDeleteList`, `cascadeDeleteField` and `cascadeDeleteItem`, each delete runs in one transaction, and the value-delete error is no longer discarded. REST list deletes now cascade to fields, items and values as sync already did, which is a client-visible change for REST callers. Files: backend/data.go, backend/sync.go.
|
||||||
|
|
||||||
|
### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/sync.go:45-249` (one function; the transaction closure spans `:61-209`). Duplicated cascade logic: `sync.go:128-143` and `backend/data.go:440-452`. Event-type selection repeated at `sync.go:72-78`, `:119-125` and `:157-163`. Default-value handling repeated at `sync.go:96-103` and `backend/data.go:349-354` and `:393-398`.
|
||||||
|
- **Description:** Upserts, notifications, cascades and response assembly all live in one closure. The business rules for deletion, defaults and event types are implemented twice, once in the sync handler and once in the REST handlers. Q-002 is a direct result of this duplication.
|
||||||
|
- **Impact:** Hard to test or change safely, and the two code paths have already diverged.
|
||||||
|
- **Recommendation:** Extract a small repository layer (`upsertList`, `upsertField`, `upsertItem`, `upsertValue`, `deleteList`, `deleteField`, `deleteItem`) shared by the REST handlers and sync, and keep the handlers as thin request and response adapters. Move event-type selection into one helper.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are shared by REST and sync, and sync picks its event type through one helper (`changeEventType`). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
|
||||||
|
|
||||||
|
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** · Open
|
||||||
|
- **Location:** `backend/db_test.go` and `.github/workflows/tests.yml` (database-backed tests and a PostgreSQL service); `frontend/src/lib/api.test.js` and the `node:test` suite; `CollabTableAndroid/app/src/test/java/com/collabtable/app/data/repository/SyncPageProgressTest.kt` (new JVM test, not yet run here).
|
||||||
|
- **Description:** Backend and frontend coverage now exercises core paths, but local database-backed tests need PostgreSQL and the Android sync-page test has not been compiled or run. There is no Android CI job. The new coverage still needs a successful database and JVM execution.
|
||||||
|
- **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible.
|
||||||
|
- **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic.
|
||||||
|
- **Status:** Open 2026-10-20 — Partly fixed: route and middleware tests assert behavior; PostgreSQL-backed tests now cover sync, pagination, change-token backfill, membership isolation, cascades, values, notifications, `/web/data` and tokens; frontend tests cover list helpers and credential proof forwarding; and `SyncPageProgressTest.kt` covers the Android page loop. The PostgreSQL tests skip locally because `TEST_DATABASE_URL` is unset and no local PostgreSQL binaries are available. The workflow defines a PostgreSQL service but was not run here. Java and Gradle are unavailable, so the JVM test remains uncompiled and unrun; no Android CI job runs it.
|
||||||
|
|
||||||
|
### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed
|
||||||
|
- **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`).
|
||||||
|
- **Description:** The auth service is built with `RequireSecret()` (`auth.go:118`). When `SECRET` is unset, `/api/auth/status` and every auth-gated route return `500 SECRET environment variable is not set.`, so the documented Quick Start produces a dashboard that cannot load. The README table also calls `SECRET` optional. The live session cookie's `Secure` and `SameSite` attributes come from AuthGuard (see Security S-013), so `COOKIE_SECURE` does not do what the README says. `npm run dev` proxies only `/web` and `/health`, but the dashboard calls `/api/auth/*` and `/api/tech-stack` (`frontend/src/lib/api.js`), so the dev server cannot reach the API.
|
||||||
|
- **Impact:** Operators who follow the docs get a deployment that fails or looks secure when it is not, and developers hit a confusing dev setup.
|
||||||
|
- **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy.
|
||||||
|
- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js.
|
||||||
|
|
||||||
|
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`).
|
||||||
|
- **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time.
|
||||||
|
- **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts.
|
||||||
|
- **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule.
|
||||||
|
- **Status:** Fixed 2026-10-20 — Every list, field, item and value write now receives a monotonic server `change_token`; startup backfills existing rows. Sync reads a repeatable-read snapshot and returns a bounded page with `nextSyncToken`; Android follows all pages and saves the cursor after completion. Client timestamps remain metadata and govern stale-write handling. Existing clients must update because requests without `lastSyncToken` now receive 400. PostgreSQL runtime tests are written but skipped locally; see Verification. Files: `backend/db.go`, `backend/models.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
|
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
|
||||||
|
- **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`).
|
||||||
|
- **Description:** Client errors are reported as server errors, one endpoint documents a body it does not use, and unknown API paths get HTML with a success status.
|
||||||
|
- **Impact:** Clients cannot distinguish retryable from permanent failures, and an API mistake returns a web page instead of an error.
|
||||||
|
- **Recommendation:** Map unique and foreign-key violations (`pgconn.PgError` codes `23505` and `23503`) to `409` and `422`. Make `PUT /api/items/{id}` either apply the documented fields or be removed. Return JSON `404` for unmatched `/api/` paths before the SPA fallback.
|
||||||
|
|
||||||
|
### Q-008 · Dead code and unused wiring · **Low**
|
||||||
|
- **Location:** `backend/notifications.go:59-61` (`isNoRows` has no callers); `backend/server.go:38` and `:96-106` (the `carrierNode` client is built, stored and never used, and it holds the internal secret); `backend/db.go:111-140` and `:165-169` (retired auth tables are still created on every start); `backend/db.go:197-210` (session-pruning goroutine for those retired tables).
|
||||||
|
- **Description:** Dead helpers and an unused client remain in place. The retired tables are still managed by startup code even though nothing reads them.
|
||||||
|
- **Impact:** Noise for maintainers, and a secret held in memory for no purpose.
|
||||||
|
- **Recommendation:** Remove `isNoRows`. Construct the CarrierNode client only when a feature uses it. Drop the session-pruning goroutine, or document why it stays.
|
||||||
|
- **Status:** Partly fixed 2026-10-20 — removed `isNoRows` and the unused CarrierNode client construction/field. Retired auth tables and their pruning remain in place to avoid changing stored-data retention in this cleanup. Files: `backend/notifications.go`, `backend/server.go`.
|
||||||
|
|
||||||
|
### Q-009 · Several failures are discarded without a comment on the risk · **Low**
|
||||||
|
- **Location:** `backend/data.go:424` and `:587` (`_ = decodeJSON(...)` on DELETE and PUT with an optional body); `backend/data.go:620` (`_, _ =` on the item value delete); `backend/data.go:618-619` (a failed item re-read silently skips the notification); `backend/sync.go:211` (raw database error text is logged, which can include values).
|
||||||
|
- **Description:** Errors are ignored in several places. The `decodeJSON` ignores are reasonable for optional bodies, but `data.go:620` guards data integrity, and the others hide failures from operators.
|
||||||
|
- **Impact:** Silent inconsistency (see Q-002) and harder debugging.
|
||||||
|
- **Recommendation:** Check and return the error from the value delete. Document the intentional `decodeJSON` ignores, or return `400` on a malformed body. Log errors with a request identifier rather than raw values.
|
||||||
|
|
||||||
|
### Q-010 · CI does not cover shared code, lint is partial, and Node versions disagree · **Low**
|
||||||
|
- **Location:** `.github/workflows/tests.yml` and `.github/workflows/lint.yml` `paths:` filters include `backend/**` and `frontend/**` but not `shared/**`, although `backend/go.mod` replaces the shared module with `../shared/backend` (`docker.yml` does include `shared/**`); `.github/workflows/lint.yml:41` (`node-version: '20'`) against `tests.yml:64` (`'22'`), `docker/Dockerfile:4` (`node:22-alpine`) and `README.md:85` (`Node.js 22+`); no Go lint job (`gofmt`, `go vet`, `golangci-lint`); the `format:check` script in `frontend/package.json` is not run; Android has no CI (acknowledged in the README).
|
||||||
|
- **Description:** A breaking change in `shared/backend` does not trigger the Go test job on push or pull request, and lint runs on Node 20 while everything else uses 22.
|
||||||
|
- **Impact:** Breakage in the shared library can reach `main` untested by push-triggered checks. The Docker build compiles it, but does not run its tests.
|
||||||
|
- **Recommendation:** Add `shared/backend/**` and `shared/packages/web-ui/**` to the Go and frontend workflow paths. Standardize on Node 22. Add `gofmt -l` and `go vet` to the Go job, and `npm run format:check` to lint.
|
||||||
|
|
||||||
|
### Q-011 · Unpinned and inconsistent dependency declarations · **Low**
|
||||||
|
- **Location:** `frontend/package.json` `devDependencies` and `dependencies` blocks (21 entries use `"latest"`, including `svelte`, `@sveltejs/kit`, `vite` and `@tanstack/svelte-query`); `.github/workflows/tests.yml:70` (web-ui installed with `--no-package-lock`); `CollabTableAndroid/app/build.gradle` (`compose-bom:2024.06.00` for the app but `2023.10.01` for `androidTestImplementation`, and `retrofit` declared as both `implementation` and `kapt`).
|
||||||
|
- **Description:** `"latest"` specifiers make the declared range meaningless and rely entirely on the lock file being respected. CI installs web-ui without a lock file. The Android app and test dependency sets use different Compose BOMs.
|
||||||
|
- **Impact:** Upgrades happen implicitly whenever the lock is regenerated, and app and test builds can resolve different Compose versions.
|
||||||
|
- **Recommendation:** Pin ranges (for example a caret range around the locked Svelte 5.56.8), commit the lock, and use `npm ci` for web-ui in CI. Align the Compose BOM and remove the redundant `kapt` Retrofit line.
|
||||||
|
|
||||||
|
### Q-012 · Release build has minification disabled · **Low**
|
||||||
|
- **Location:** `CollabTableAndroid/app/build.gradle:30` (`minifyEnabled false` in the `release` build type).
|
||||||
|
- **Description:** The release build ships unshrunk, unobfuscated code, and `proguard-rules.pro` has no effect because minification is off.
|
||||||
|
- **Impact:** Larger APK, and easier reverse engineering of the sync protocol.
|
||||||
|
- **Recommendation:** Enable `minifyEnabled true` and `shrinkResources true` for release, then verify with a release build and the Gson and Retrofit keep rules.
|
||||||
|
|
||||||
|
### Q-013 · Mutable singleton in the Android API client is not synchronized · **Low**
|
||||||
|
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:15-18` (mutable `baseUrl`, `retrofit` and `context`); `:119-137` (`initialize` and `setBaseUrl` rebuild Retrofit); `:139-145` (the `api` getter builds Retrofit lazily).
|
||||||
|
- **Description:** The singleton's fields are written from settings and read from background sync work without synchronization or `@Volatile`, and the lazy getter can build Retrofit twice.
|
||||||
|
- **Impact:** Possibly a stale base URL or a duplicate client during a settings change. This needs verification by changing the URL while a sync is running.
|
||||||
|
- **Recommendation:** Guard the state with a lock or `@Volatile`, or make the base URL an immutable value that is rebuilt through a single factory driven by a `StateFlow`.
|
||||||
|
|
||||||
|
### Q-014 · Stale and junk artifacts are tracked in the repository · **Low**
|
||||||
|
- **Location:** `backend/data/collabtable.db` (69,632-byte SQLite file; all five tables have zero rows and a pre-migration camelCase schema); `backend/collabtable.db` (0 bytes); `CollabTableAndroid/build-errors.txt` (contains only an interrupt marker); `CollabTableAndroid/build-output.txt` (4.8 KB build log); root `.gitignore` (no `*.db` or build-log rule).
|
||||||
|
- **Description:** Database files and build logs are committed. The SQLite file is a leftover from the Node-era schema, and the Go server uses PostgreSQL only. No credentials or user data were found in them.
|
||||||
|
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
||||||
|
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Go command (all database URL variables unset):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
unset DATABASE_URL SHARED_TEST_DATABASE_URL TEST_DATABASE_URL && export PATH=/tmp/medium-pass-gosdk/go/bin:$PATH GOCACHE=/tmp/medium-pass-go-cache GOMODCACHE=/tmp/medium-pass-go-mod && go test ./... && go test -v -run 'Test(ParsePageRequest|InitSchemaCanRunAgainstAnExistingDatabase|CollectionEndpointsPageWithStableCursors|SyncUsesServerChangeTokenInsteadOfClientTimestamp|SyncBoundsAndPagesLargeInitialSync|PerListMembershipScopesDataAndSync|MembershipBackfillPreservesCurrentAPITokenUsers)$' && go vet ./... && gofmt -l . && for bin in postgres psql initdb; do command -v "$bin" || true; done
|
||||||
|
```
|
||||||
|
|
||||||
|
`go test ./...` passed. All nine `TestParsePageRequest` cases passed; the six PostgreSQL-backed cases in the focused run skipped because `TEST_DATABASE_URL` is unset. `go vet ./...` passed and `gofmt -l .` printed no files. `postgres`, `psql` and `initdb` were not found.
|
||||||
|
- Frontend commands: `unset DATABASE_URL && npm test` (9 passed); `unset DATABASE_URL && npm run check` (0 errors, 0 warnings); `unset DATABASE_URL && npm run lint` (passed); `unset DATABASE_URL && npm run build` (passed after adding the local design-tokens dependency and enabling `resolve.preserveSymlinks`; the build reports one Svelte warning in shared `layout.svelte.js:44`); `unset DATABASE_URL && npx prettier --check src/lib/api.js src/lib/api.test.js src/lib/features/layout/AppShell.svelte` and `unset DATABASE_URL && npx prettier --check --end-of-line crlf vite.config.js` (both passed).
|
||||||
|
- Build dependency wiring: `unset DATABASE_URL && npm install --save '@gabriel20xx/design-tokens@file:../shared/packages/design-tokens' --offline` added the local package to `frontend/package.json` and the lockfile. The Vite build initially exposed the local shared-package symlink resolution issue; `resolve.preserveSymlinks` fixed it.
|
||||||
|
- `unset DATABASE_URL && npm run format:check` failed on four untouched files (`src/app.css`, `src/lib/components/ui/dropdown-menu/content.svelte`, `src/lib/features/layout/SettingsDialog.svelte`, `src/routes/+layout.svelte`) and `vite.config.js`, whose original CRLF line endings were preserved to keep the change limited.
|
||||||
|
- Android JVM tests were not run: Java and Gradle executables and a Unix `gradlew` wrapper are unavailable. The source test exists at the path listed in Q-004. A final redundant Svelte-check rerun was stopped after the process remained in uninterruptible I/O for several minutes; an earlier `npm run check` completed successfully before the Vite-only symlink setting.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- No live AuthGuard instance or browser session was available, and no load benchmark was run. Performance estimates still need realistic data and multiple devices.
|
||||||
|
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
||||||
|
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
||||||
|
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|
||||||
@@ -35,7 +35,7 @@ CollabTable's browser dashboard authenticates through AuthGuard, a centralized i
|
|||||||
AuthGuard integration has three states:
|
AuthGuard integration has three states:
|
||||||
- `AUTHGUARD_URL` set — used immediately.
|
- `AUTHGUARD_URL` set — used immediately.
|
||||||
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
||||||
- `AUTH_DISABLED=true` — authentication is fully off (no login screen, nothing gated, every request treated as authenticated) — only use this for local development or a deployment you are certain does not need access control.
|
- `AUTH_DISABLED=true` — browser-session gates are off. List access still requires membership; the placeholder identity used in this mode has no memberships, so dashboard data is empty and sync tokens minted for it are rejected. Use this only to develop the auth shell, not for a working data deployment.
|
||||||
|
|
||||||
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
||||||
|
|
||||||
@@ -47,14 +47,19 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
|----------|----------|---------|--------------|
|
|----------|----------|---------|--------------|
|
||||||
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
||||||
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. |
|
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. |
|
||||||
| `AUTH_DISABLED` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. |
|
| `AUTH_DISABLED` | No | `false` | Set `true` to disable browser-session gates. List access remains membership-scoped; the placeholder identity has no memberships and its sync tokens are rejected. Use only for auth-shell development, not for a working data deployment. |
|
||||||
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
||||||
| `SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. |
|
| `SECRET` | Yes, unless `AUTH_DISABLED=true` | unset | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal` and `PUT /api/auth/access/internal`. Without it, `GET /api/auth/status` reports `SECRET environment variable is not set.` and every auth-gated route returns 500, and the internal endpoints refuse every caller. |
|
||||||
|
| `ALLOWED_ORIGINS` | No | unset | Comma-separated browser origins that may call the API cross-origin with credentials. Leave unset: the dashboard is same-origin and needs no CORS. |
|
||||||
| `PORT` | No | `8080` | HTTP listen port |
|
| `PORT` | No | `8080` | HTTP listen port |
|
||||||
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
|
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
|
||||||
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
|
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS. It marks only the cookies CollabTable clears on logout as `Secure`; the session cookie's `Secure`, `SameSite` and `Domain` attributes are set by AuthGuard. |
|
||||||
|
| `TRUSTED_PROXIES` | No | unset | Comma-separated IPs or CIDR ranges of reverse proxies. `X-Forwarded-For` (client IP for rate limits) and `X-Forwarded-Proto` are read only from these peers. |
|
||||||
|
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
|
||||||
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
||||||
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
||||||
|
| `OMNILOGGER_URL` | No | unset | Optional initial base URL of the OmniLogger log sink. Server log lines are also sent there when it and `OMNILOGGER_INGEST_TOKEN` are both set; console output is unchanged. ProjectConfigurator's push can supply or replace it at runtime. The `remap-users` command is not shipped. |
|
||||||
|
| `OMNILOGGER_INGEST_TOKEN` | No | unset | Optional initial ingest token for this service (`collabtable`). ProjectConfigurator normally supplies the token at runtime through its core-services push, which also starts shipping. Shipping stays off until both a URL and a token are known. |
|
||||||
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
||||||
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
||||||
|
|
||||||
@@ -73,6 +78,7 @@ docker run -d \
|
|||||||
-p 8080:8080 \
|
-p 8080:8080 \
|
||||||
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
|
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
|
||||||
-e AUTHGUARD_URL="https://auth.example.com" \
|
-e AUTHGUARD_URL="https://auth.example.com" \
|
||||||
|
-e SECRET="<long-random-shared-secret>" \
|
||||||
collabtable:local
|
collabtable:local
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -120,8 +126,12 @@ Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emul
|
|||||||
```bash
|
```bash
|
||||||
cd backend
|
cd backend
|
||||||
go test ./...
|
go test ./...
|
||||||
|
# The handler and sync tests need a disposable PostgreSQL and are skipped without one.
|
||||||
|
# Never point this at your real DATABASE_URL: each test creates and drops its own schema.
|
||||||
|
TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable' go test ./...
|
||||||
|
|
||||||
cd ../frontend
|
cd ../frontend
|
||||||
|
npm test
|
||||||
npm run check
|
npm run check
|
||||||
npm run lint
|
npm run lint
|
||||||
```
|
```
|
||||||
@@ -136,7 +146,7 @@ Every push runs three GitHub Actions workflows against the backend and frontend
|
|||||||
|
|
||||||
- **`docker.yml`** — builds a multi-arch image (`linux/amd64` + `linux/arm64` on `main`, `linux/amd64` otherwise) from `docker/Dockerfile` and pushes `${DOCKERHUB_USERNAME}/collabtableserver` to Docker Hub on pushes to `main`, tagged by branch name, `sha-<short-sha>`, and `latest`.
|
- **`docker.yml`** — builds a multi-arch image (`linux/amd64` + `linux/arm64` on `main`, `linux/amd64` otherwise) from `docker/Dockerfile` and pushes `${DOCKERHUB_USERNAME}/collabtableserver` to Docker Hub on pushes to `main`, tagged by branch name, `sha-<short-sha>`, and `latest`.
|
||||||
- **`lint.yml`** — runs `npm run lint` (ESLint) against `frontend`.
|
- **`lint.yml`** — runs `npm run lint` (ESLint) against `frontend`.
|
||||||
- **`tests.yml`** — runs `go test ./...` against `backend` and `npm run check` against `frontend`.
|
- **`tests.yml`** — runs `go test ./...` against `backend` (with a PostgreSQL service container, so the database-backed tests run) and `npm test` and `npm run check` against `frontend`.
|
||||||
|
|
||||||
**Required secrets / variables in your GitHub repository settings:**
|
**Required secrets / variables in your GitHub repository settings:**
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
# Security Report — CollabTable
|
||||||
|
|
||||||
|
- **Project:** CollabTable
|
||||||
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 6aec03f on main
|
||||||
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
|
- **Updated:** 2026-10-20 — S-003 now enforces the approved per-list membership model; S-005 applies the shared reauthentication rule and remains open only for other-session revocation. S-002 remains Not reproduced by owner decision.
|
||||||
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server with PostgreSQL; identity delegated to a separate AuthGuard service via `shared/backend/auth`; SvelteKit 2 / Svelte 5 static dashboard embedded in the Go binary; Android client (Kotlin, Retrofit/OkHttp, Room, SharedPreferences); Docker multi-stage image on `scratch`; GitHub Actions.
|
||||||
|
- **Scope:** Read all first-party backend code (`backend/*.go`), the Docker and CI configuration, the frontend API client, routes and query layer, the Vite config, the Android API client, preferences, manifest, network security config and app Gradle file, and the shared auth, authclient, authproxy, coreconfig and postgres code that CollabTable calls. Git history was searched for credential-shaped strings and `.env` files. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, generated build output, lock files (read for versions only), and the rest of `shared/`. Tracked SQLite files were inspected read-only from a copy, schema and row counts only. Available tests and builds are recorded in `QUALITY_REPORT.md`; no network audit or live deployment check was made.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
|
| High | 0 | 0 | 0 | 0 |
|
||||||
|
| Medium | 10 | 8 | 1 | 1 |
|
||||||
|
| Low | 7 | 0 | 0 | 7 |
|
||||||
|
| Info | 2 | 0 | 0 | 2 |
|
||||||
|
|
||||||
|
No critical or high-severity issues were confirmed. Authentication is delegated to AuthGuard and fails closed when it is not configured, and sync tokens are generated with 256 bits of randomness and stored hashed. Data access is now scoped by list membership; legacy lists remain available to all API-token users present during migration, as approved. Other concerns include reflective CORS with credentials, missing rate limits and security headers, and Android token exposure through cleartext traffic or plain device preferences.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### S-001 · Reflective CORS with credentials on every route · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/server.go:274-290` (`withCORS`), in particular `:276-281`.
|
||||||
|
- **Description:** The middleware echoes any request `Origin` into `Access-Control-Allow-Origin` and sets `Access-Control-Allow-Credentials: true` on all responses, including session-protected routes (`/web/data`, `/api/auth/users`, `/api/auth/token/regenerate`). If the browser sends the user's cookies, any origin can read those responses. The preflight `Allow-Methods` list also omits `PATCH`, which `server.go:181` accepts.
|
||||||
|
- **Impact:** Exploitability depends on the AuthGuard cookie attributes, which are not in this repository. With `SameSite=Lax`, a cross-site page will not receive the cookie, but a same-site origin will (another subdomain of the same site, or a sibling app on a shared cookie domain, which the authclient docs describe as a cross-project SSO option). Such an origin could read `/web/data` or call `POST /api/auth/token/regenerate` and read the new sync token. Rated Medium here; it would be High if the cookie is scoped to a parent domain. Needs verification against the deployed AuthGuard cookie.
|
||||||
|
- **Recommendation:** Replace the reflection with an explicit allow-list from configuration (for example `ALLOWED_ORIGINS`) and set credentials headers only for those origins. The dashboard is same-origin and needs no CORS headers at all, so the default should be none. Keep `Vary: Origin` and add `PATCH` to the allowed methods if it is needed.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `withCORS` now reflects only origins listed in `ALLOWED_ORIGINS` (empty by default), sends credentials headers only for them, and allows `PATCH` in preflight. Browser clients on other origins lose cross-origin access, which the same-origin dashboard does not need. Files: backend/server.go, backend/server_test.go, backend/README.md, README.md.
|
||||||
|
|
||||||
|
### S-002 · Login-disabled mode lets anyone obtain a write-capable sync token · **Medium** · Not reproduced
|
||||||
|
- **Location:** `backend/server.go:186-188` (`POST /api/auth/token/regenerate` behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:504-519` (`CurrentUser` returns the superadmin placeholder whenever login is not required); `backend/auth.go:194-210` (`handleTokenRegenerate` mints a token for the placeholder identity).
|
||||||
|
- **Description:** When login is not required (`AUTH_DISABLED=true`, or the login-required override pushed by ProjectConfigurator set to false), `RequireIfLoginRequired` lets any caller reach token regeneration without credentials. The endpoint mints a write-capable sync token for identity 0, and the bearer-token check on the sync API then passes for that caller.
|
||||||
|
- **Impact:** The sync API's token requirement protects nothing in that mode, and any network client can obtain full read, write and delete access. The README describes `AUTH_DISABLED` as "nothing gated", so this matches the documented intent. The override path can be set centrally in a shared deployment, however, and nobody may notice that the token API has become open.
|
||||||
|
- **Recommendation:** Keep token minting behind a real credential even when login is off (for example, always require a session for token regeneration), or document the consequence prominently and log a warning when the override is set to false.
|
||||||
|
- **Status:** Not reproduced 2026-10-20 — The last step of the chain fails. With login off, callers resolve to placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so a token minted without a session gets 401 on `/api/sync` and `/api/lists`. `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` pins this. Write and delete access through that token is not reachable. Login-off still bypasses the browser-session gate, but `/web/data` returns no list rows because identity 0 has no memberships. Devices cannot get a working sync token; accepting identity 0 would open sync and is not part of this decision.
|
||||||
|
|
||||||
|
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth.go:129-149` (`requireAPIToken` only checks that a token exists); `backend/server.go:195-219` (all data routes); `backend/data.go` (all handlers); `backend/sync.go:61-209`; `backend/db.go:40-189` (no owner or tenant columns); `backend/sync.go:198-203` and `backend/data.go:549-558` (item values upserted by `id` alone).
|
||||||
|
- **Description:** Any valid sync token (one per account) and any logged-in account can read, overwrite, soft-delete and move every list, field, item and value. The item-value conflict clause updates only `value` and `updatedat`, so a write that names a different `itemId` or `fieldId` than the stored row is silently applied to the stored row. The schema has no owner column, and `api_tokens.user_id` is used only for token regeneration. Item values are hard-deleted when their item or list is deleted (`sync.go:88`, `:129`, `:140`, `:166`), so those deletions cannot be undone by a later sync, even though lists and items are soft-deleted.
|
||||||
|
- **Impact:** For a collaborative tool this may be intended, in which case every account is effectively an administrator of the data. If it is not intended, it is an authorization gap. Either way, one compromised device token can wipe or rewrite the database, and some of that loss is permanent.
|
||||||
|
- **Recommendation:** Confirm the intended model and document it. If the data is shared, make item-value upserts reject writes whose `itemid` or `fieldid` do not match the stored row. If per-list access is needed, add a membership table and check it in every handler.
|
||||||
|
- **Status:** Fixed 2026-10-20 — `list_memberships` now scopes REST, sync, dashboard and notification reads; cross-list item/field IDs are rejected. New lists belong only to their creator. Per the owner decision, migration grants every current API-token user access to each legacy list because prior ownership cannot be reconstructed. Login-disabled identity 0 has no list access. Item values still hard-delete with their parent, as before. Files: `backend/db.go`, `backend/ownership.go`, `backend/data.go`, `backend/sync.go`, `backend/web.go`.
|
||||||
|
|
||||||
|
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/server.go:178-182` (list, create, update and delete users, behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:897-1013` (handlers forward the caller's session to AuthGuard without a local role check); `shared/backend/auth/proxy.go:618` (`RequireUserManager` exists but CollabTable does not use it).
|
||||||
|
- **Description:** The handlers document that AuthGuard enforces authorization, which holds only if AuthGuard rejects non-admin sessions. CollabTable does not check the role before proxying. If AuthGuard does not reject it, `GET /api/auth/users` returns every account's username, email and role to any logged-in account.
|
||||||
|
- **Impact:** No defense in depth. A bug or policy change in AuthGuard would expose administrative functions here. Needs verification against the deployed AuthGuard version.
|
||||||
|
- **Recommendation:** Gate these routes with `RequireUserManager` (or `RequireAdminIfLoginRequired`), which the shared package already provides, so the policy is visible in this repository.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Managed-user routes now pass the shared `RequireUserManager` gate, so the role check happens in this repository as well as in AuthGuard; accounts without user-management rights get 403 locally. Files: backend/server.go, backend/routes_test.go.
|
||||||
|
|
||||||
|
### S-005 · Password change does not require the current password, and existing sessions stay valid · **Medium** · Open
|
||||||
|
- **Location:** `shared/backend/auth/proxy.go:664-705` (`UpdateMe` accepts only `email`, `username` and `password`); `backend/auth.go:39-43` (documented behavior: a credentials change "simply returns the updated account and leaves the current session valid").
|
||||||
|
- **Description:** Anyone holding a session cookie can change the account password without knowing the current one. Sessions on other devices also remain valid, and there is no re-authentication step.
|
||||||
|
- **Impact:** A stolen or unattended session can lock the owner out. The usual defenses (re-authentication, and revoking other sessions on password change) are absent.
|
||||||
|
- **Recommendation:** Require `currentPassword` (and the TOTP code when enabled) on `POST /api/auth/credentials` whenever the password changes, and have AuthGuard revoke other sessions on a password change.
|
||||||
|
- **Status:** Open 2026-10-20 — Partly fixed: the mirrored shared `UpdateMe` requires the current password and TOTP proof when enabled, and the dashboard forwards both values. Still open: revoking other sessions after a password change; no owner decision was made for that behavior. Files: `frontend/src/lib/api.js`, `frontend/src/lib/features/layout/AppShell.svelte`, `shared/backend/auth/proxy.go`.
|
||||||
|
|
||||||
|
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed
|
||||||
|
- **Location:** `shared/backend/auth/proxy.go:1093-1142` (`Login` forwards every attempt to AuthGuard with no local throttling); `backend/auth.go:129-149` (sync-token check, no throttling); `backend/server.go:188` (token regeneration); `backend/server.go:253-259` (up to 50 MB per request, see P-007).
|
||||||
|
- **Description:** A search of CollabTable and the shared auth packages finds no rate limiter, lockout or request throttle. Brute-force protection for passwords and TOTP codes depends entirely on AuthGuard. Sync tokens carry 256 bits of entropy, so guessing them is not a practical concern; the issue is request volume and availability.
|
||||||
|
- **Impact:** Credential stuffing against the login proxy, load from unthrottled token checks, and memory exhaustion from large bodies.
|
||||||
|
- **Recommendation:** Add per-IP and per-account limits on `/api/auth/login`, `/api/auth/totp/*` and `/api/auth/setup`, either in-process or at the proxy. Confirm AuthGuard's own limits. Enforce body size per route (see P-007).
|
||||||
|
- **Status:** Fixed 2026-10-19 — In-process budgets (owner decision 5) on setup, login, the TOTP routes and token regeneration: 30 requests per minute per client IP, and 10 failed logins per account identifier per 15 minutes, answered with 429 and `Retry-After`. The client IP is read from `X-Forwarded-For` only when the socket peer is in the new `TRUSTED_PROXIES` list, and is the socket address otherwise. Not throttled per request: the sync API and writes, because the bearer token is 256 bits and devices sync often; body size and concurrent syncs bound their cost (P-007). Still to confirm: AuthGuard's own login limits on the deployed instance. Verified by Go unit and route tests only, not against a running instance. Files: backend/clientip.go, backend/ratelimit.go, backend/server.go, backend/clientip_test.go, backend/ratelimit_test.go, backend/.env.example, backend/README.md, README.md.
|
||||||
|
|
||||||
|
### S-007 · No security headers on the dashboard or API · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/server.go:118-125` (no header middleware); `backend/server.go:292-316` (`spaFileServer` writes `index.html` with only `Content-Type`); `backend/web.go:74-76` (cache headers only).
|
||||||
|
- **Description:** Responses carry no `Content-Security-Policy`, no `X-Frame-Options` or `frame-ancestors`, no `X-Content-Type-Options` and no `Referrer-Policy`. The app can be framed, which allows clickjacking of user-management and token-regeneration actions. Without a CSP, an injected script would have no restrictions. No unsafe HTML rendering was found in first-party code, which limits the immediate risk.
|
||||||
|
- **Impact:** Clickjacking of logged-in actions and a weaker defense against future XSS. HSTS belongs at the TLS terminator and is not set here.
|
||||||
|
- **Recommendation:** Add middleware that sets `X-Frame-Options: DENY` (or `frame-ancestors 'none'`), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and a CSP such as `default-src 'self'` with hashes or nonces for SvelteKit's inline bootstrap script. Set HSTS at the proxy.
|
||||||
|
- **Status:** Fixed 2026-10-19 — The dashboard page (`index.html` and the deep-link fallback) now sends a full Content-Security-Policy (`backend/csp.go`, set in `spaFileServer`): `default-src 'self'`, `script-src 'self'` plus the SHA-256 of the page's inline bootstrap script (read from the embedded `index.html` at request time, so it follows each build), `style-src 'self' 'unsafe-inline'` (the page shell uses a style attribute), `connect-src 'self'`, `object-src 'none'`, `base-uri`, `form-action` and `frame-ancestors 'none'`. Other responses keep `frame-ancestors 'none'`. HSTS stays with the TLS proxy, as recommended, and `backend/README.md` says so. Checked on a real build: the Go hash equals an independent computation, and the bundle has no eval, workers, external URLs or CSS `url()`. Not loaded in a browser (none available here), so open the dashboard once after deploying.
|
||||||
|
|
||||||
|
### S-008 · Android app logs full HTTP traffic, including the bearer token, in every build · **Medium** · Fixed
|
||||||
|
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:20-23` (`HttpLoggingInterceptor` at `Level.BODY`), and `:55-64` (the interceptor is added to the client unconditionally; `authInterceptor` at `:58` sets the `Authorization` header first).
|
||||||
|
- **Description:** The logging interceptor is not gated on the debug build type, and it does not redact headers. Its output includes the `Authorization: Bearer <token>` header and the full request and response bodies, which carry all list and item data, in release builds.
|
||||||
|
- **Impact:** The long-lived sync token and user data end up in logcat and in any log capture or bug report. Exploiting this requires access to device logs (ADB, a debugging tool, or a bug report), not a remote attack.
|
||||||
|
- **Recommendation:** Use `Level.NONE` for release builds (for example `if (BuildConfig.DEBUG)`), call `redactHeader("Authorization")`, and do not log bodies in production.
|
||||||
|
- **Status:** Fixed 2026-10-19 — HTTP logging now uses `Level.NONE` unless `BuildConfig.DEBUG`, and the `Authorization` header is redacted in every build; `buildConfig` is enabled because AGP 8.8 does not generate `BuildConfig` by default. The Kotlin compile could not run in this environment (the JVM hit the process limit), so it is unverified. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, CollabTableAndroid/app/build.gradle.
|
||||||
|
|
||||||
|
### S-009 · Cleartext HTTP is allowed for all domains and is the default server URL · **Medium** · Fixed
|
||||||
|
- **Location:** `CollabTableAndroid/app/src/main/res/xml/network_security_config.xml:3-4` (`cleartextTrafficPermitted="true"` in `base-config`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:298` (default `http://10.0.2.2:8080/api/`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:25-44` (the bearer token is attached to every request).
|
||||||
|
- **Description:** The release app accepts `http://` server URLs for any host, and the bearer token is sent with every request. Traffic is unencrypted and can be read or altered on the network path.
|
||||||
|
- **Impact:** Token and data exposure on untrusted networks whenever an operator configures an HTTP URL. Cleartext is needed only for the emulator default.
|
||||||
|
- **Recommendation:** Keep cleartext only for debug builds (a debug resource overlay) or for `10.0.2.2` and `localhost`. Require HTTPS for remote hosts and reject `http://` in the settings UI otherwise.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Handled by owner decision 11 (LAN HTTP allowed, with a warning). Cleartext stays permitted, so the network security config and the default emulator URL are unchanged. `ApiClient` logs a warning whenever the server URL is `http://`. The backend logs a warning at startup while TLS is off. `PRODUCTION=true` refuses plain HTTP requests unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends `X-Forwarded-Proto: https` (`/health` stays open). The Android app has no production profile, so release builds keep cleartext. The settings screen does not reject `http://` for remote hosts, which the decision replaces. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, backend/server.go, backend/.env.example, backend/README.md, README.md. The Kotlin change is not compiled: the Android build cannot run on this Alpine (musl) host, because the SDK's aapt2 needs glibc.
|
||||||
|
|
||||||
|
### S-010 · Long-lived sync token stored in plain SharedPreferences, with app backup enabled · **Medium** · Fixed
|
||||||
|
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:73-80` and `:283` (token written to `collab_table_prefs` with `MODE_PRIVATE`, unencrypted); `CollabTableAndroid/app/src/main/AndroidManifest.xml:11` (`android:allowBackup="true"`).
|
||||||
|
- **Description:** The API token is written to ordinary SharedPreferences. With `allowBackup="true"` the file is included in device backups, and on a rooted device or with ADB backup access it can be read directly.
|
||||||
|
- **Impact:** The token grants full sync access (see S-003) and can be recovered from a backup or a compromised device.
|
||||||
|
- **Recommendation:** Store the token with `EncryptedSharedPreferences` or the Android Keystore, exclude it from backups with `dataExtractionRules` and `fullBackupContent`, or set `allowBackup="false"`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `android:allowBackup` is now `false`, so the sync token is kept out of device backups and transfers. Users must re-enter the token on a new device, and the token remains plain text on the device, which a rooted device can still read. Files: CollabTableAndroid/app/src/main/AndroidManifest.xml.
|
||||||
|
|
||||||
|
### S-011 · Sync token has no expiry, scope or per-device identity · **Low**
|
||||||
|
- **Location:** `backend/db.go:181-188` (`api_tokens` has no expiry column); `backend/auth.go:159-170` (32 random bytes, stored as an unsalted SHA-256 hash); `backend/auth.go:194-210` (regeneration replaces the account's single token).
|
||||||
|
- **Description:** The token is well built: 256 bits from `crypto/rand`, stored only as a hash, and checked through an indexed lookup. It never expires, carries no scope, and cannot be revoked per device. Regenerating invalidates every device at once.
|
||||||
|
- **Impact:** A lost or retired device keeps write access until the operator regenerates the token, and regenerating also breaks every other device.
|
||||||
|
- **Recommendation:** Issue per-device tokens with `last_used` and `expires_at` columns and a revoke action, or at least document a rotation procedure.
|
||||||
|
|
||||||
|
### S-012 · Shared-secret comparisons are not constant-time · **Low**
|
||||||
|
- **Location:** `shared/backend/coreconfig/coreconfig.go:182` (`r.Header.Get("X-Internal-Auth") != secret`); `shared/backend/auth/proxy.go:819` (same pattern in `SetLoginRequiredInternal`).
|
||||||
|
- **Description:** A `!=` comparison on strings can exit early. Other helpers in the workspace use `subtle.ConstantTimeCompare` (`shared/backend/auth/reset.go:73`, `shared/backend/auth/totp.go:82`), so these two are inconsistent.
|
||||||
|
- **Impact:** A theoretical timing side channel on the internal `SECRET`. Network jitter makes practical exploitation unlikely.
|
||||||
|
- **Recommendation:** Compare with `subtle.ConstantTimeCompare` on byte slices, after confirming that the expected secret is non-empty.
|
||||||
|
|
||||||
|
### S-013 · `COOKIE_SECURE` does not govern the session cookie; its attributes come from AuthGuard · **Low**
|
||||||
|
- **Location:** `shared/backend/authclient/client.go:411-417` (`ForwardCookies` replays AuthGuard's `Set-Cookie` unchanged); `shared/backend/auth/proxy.go:1140` (login forwards those cookies); `shared/backend/authproxy/authproxy.go:72-83` (only the logout-clearing cookies use the `secure` flag); `README.md:55`.
|
||||||
|
- **Description:** The README says `COOKIE_SECURE=true` marks cookies `Secure`. In practice that flag affects only the cookies CollabTable clears on logout. The live session cookie's `Secure`, `SameSite` and `Domain` attributes come from AuthGuard. Needs verification against the AuthGuard configuration.
|
||||||
|
- **Impact:** An operator may believe the session cookie is `Secure` when it is not, and the cookie's scope (see S-001) is not visible from this repository.
|
||||||
|
- **Recommendation:** Document that AuthGuard controls these attributes, and verify them in a deployed environment (`Secure`, `HttpOnly`, `SameSite`, `Domain`).
|
||||||
|
|
||||||
|
### S-014 · No length or format limits on input, and item-value upserts do not check row ownership · **Low**
|
||||||
|
- **Location:** `backend/models.go:50-94` (all IDs and free-text fields are unconstrained strings); `backend/data.go:223-263` (list creation checks only for an empty ID and name); `backend/sync.go:96-98` (`fieldType` accepts any string); `backend/sync.go:198-203` and `backend/data.go:549-558` (the upsert conflict clause ignores `itemid` and `fieldid`); `backend/data.go:206-214` (the `X-Device-Id` header is stored verbatim in notifications).
|
||||||
|
- **Description:** Client-chosen primary keys and free-text fields have no length or character limits, and `fieldType` is not checked against the types the UI understands. The item-value conflict clause (see S-003) silently ignores a mismatched `itemId` or `fieldId`. The device identifier is stored without limits.
|
||||||
|
- **Impact:** Oversized rows and storage growth, inconsistent typing, and a data-integrity problem that is as much a correctness issue as a security one.
|
||||||
|
- **Recommendation:** Bound string lengths (IDs to a sensible maximum such as 64 characters, names to a few hundred, values to a configured limit). Validate `fieldType` against the known set. Reject item-value writes whose `itemId` or `fieldId` do not match the stored row, or add that check to the conflict clause.
|
||||||
|
|
||||||
|
### S-015 · Public first-run setup can be claimed by whoever reaches the server first · **Low**
|
||||||
|
- **Location:** `backend/server.go:173` (`POST /api/auth/setup` is public); `shared/backend/auth/proxy.go:1014-1091` (`Signup` registers the first AuthGuard account while setup is unclaimed).
|
||||||
|
- **Description:** Until an operator completes setup, anyone who can reach the URL can create the first account, which in AuthGuard is the superadmin. The claim flag prevents a second setup, but not a first-visitor takeover.
|
||||||
|
- **Impact:** Matters only for a deployment reachable from untrusted networks before setup is completed. It is a common pattern for setup flows, but it should be stated.
|
||||||
|
- **Recommendation:** Complete setup before exposing the service, or protect `/api/auth/setup` with a one-time setup token printed at startup or supplied through the environment.
|
||||||
|
|
||||||
|
### S-016 · CI and supply-chain hygiene · **Low**
|
||||||
|
- **Location:** `.github/workflows/docker.yml:52` (`echo "${{ secrets.DOCKERHUB_TOKEN }}" | docker login ...`, with the secret interpolated into the shell script); `.github/workflows/docker.yml:34-65`, `.github/workflows/lint.yml:35-39` and `.github/workflows/tests.yml:35-62` (third-party actions pinned to major tags, not commit SHAs); `.github/workflows/tests.yml:70` (web-ui installed with `--no-package-lock`).
|
||||||
|
- **Description:** The Docker Hub token is interpolated into a shell command rather than passed through an environment variable. Actions are referenced by mutable tags.
|
||||||
|
- **Impact:** Lower risk on GitHub-hosted runners, but a compromised action tag would run with access to the secret on pushes to `main`.
|
||||||
|
- **Recommendation:** Pass the secret through an `env:` entry and pipe it to `docker login --password-stdin` from that variable. Pin actions to full commit SHAs, which Dependabot can maintain. Use a lock file for web-ui.
|
||||||
|
|
||||||
|
### S-017 · Dependency versions need an audit, which was not possible offline · **Low**
|
||||||
|
- **Location:** `backend/go.mod` (`github.com/jackc/pgx/v5 v5.10.0`, `golang.org/x/crypto v0.54.0`, `github.com/joho/godotenv v1.5.1`); `frontend/package-lock.json` (`svelte 5.56.8`, `@sveltejs/kit 2.70.2`, `vite 8.2.0`, `@tanstack/svelte-query 6.1.38`, `tailwindcss 4.3.3`); `frontend/package.json` (21 `"latest"` specifiers, see Q-011 in the Quality report); `CollabTableAndroid/app/build.gradle` (`okhttp3:logging-interceptor 4.12.0`, `retrofit2 2.9.0`, `kotlinx-coroutines-android 1.7.3`).
|
||||||
|
- **Description:** Versions were read from manifests and locks only. No vulnerability database was queried, because that requires network access. Several Android libraries are older releases, for example Retrofit 2.9.0 and kotlinx-coroutines 1.7.3.
|
||||||
|
- **Impact:** Known-vulnerable dependencies may be present. This review can neither confirm nor rule them out.
|
||||||
|
- **Recommendation:** Run `govulncheck ./...` in `backend`, `npm audit` (including build tooling) in `frontend`, and a Gradle dependency vulnerability scan (for example OWASP Dependency-Check) for the Android app. Upgrade whatever is flagged.
|
||||||
|
|
||||||
|
### S-018 · Committed-secret scan found no live credentials · **Info**
|
||||||
|
- **Location:** Tracked files (`git ls-files`); full history of `backend/.env.example` (commits `07e25a3` and `9a6ec94` for the `SECRET` and `DATABASE_URL` lines); `git log -G` over all refs for credential-shaped strings; `docker/Dockerfile`; `README.md`.
|
||||||
|
- **Description:** No `.env`, key or certificate files are tracked. The only env file is `backend/.env.example`, which holds placeholders. The historical `SECRET` value at `07e25a3` was the placeholder text, and the historical `DATABASE_URL` at `9a6ec94` was empty. The history search matched only test fixtures in `shared/` and documentation placeholders, and those hits were reviewed and redacted. The tracked SQLite file `backend/data/collabtable.db` has empty tables and no credentials (see Q-014 in the Quality report).
|
||||||
|
- **Impact:** None found.
|
||||||
|
- **Recommendation:** Keep `.env` ignored (it is, in `backend/.gitignore`), and consider a pre-commit secret scanner.
|
||||||
|
|
||||||
|
### S-019 · Controls verified as sound · **Info**
|
||||||
|
- **Location:** `backend/data.go:107-113`, `:145-149`, `:178-182` (dynamic SQL only adds numbered placeholders); `backend/db.go` and `backend/data.go` (all values bound as parameters); `backend/server.go:292-316` (static files served only from the embedded build, so no path traversal); `frontend/src` (no `{@html}`, `innerHTML` or `eval`; Svelte escapes text); `backend/auth.go:159-170` and `:194-210` (token generation and hashing); `shared/backend/coreconfig/coreconfig.go:182` and `shared/backend/auth/proxy.go:817-820` (internal endpoints refuse requests when `SECRET` is empty); `shared/backend/auth/proxy.go:359-361` and `:838-841` (auth fails closed when `SECRET` or the AuthGuard URL is missing); `shared/backend/authclient/client.go:116` (5-second timeout on outbound calls); `docker/Dockerfile:41-47` (non-root user, `scratch` base, no build tools in the final image); no `InsecureSkipVerify` or similar TLS bypass in CollabTable's own code or in the packages it imports.
|
||||||
|
- **Impact:** Positive findings.
|
||||||
|
- **Recommendation:** None.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Source review and available checks are recorded in `QUALITY_REPORT.md` under Verification. No live AuthGuard instance or browser session was available, so delegated auth behavior was not exercised end to end.
|
||||||
|
- AuthGuard, the identity service, is outside this repository. S-001 (exploitability), S-004, S-005, S-006 and S-013 depend on how it behaves and should be verified against a running instance.
|
||||||
|
- Android findings come from source, manifest and Gradle review. The sync-page JVM test source was added, but could not be compiled or run here because Java and Gradle are unavailable.
|
||||||
|
- `shared/` was reviewed selectively. `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify = true` (which disables WebSocket origin checks in the library) when the allowed origin is `*`. CollabTable does not import this package, so it is not counted here, but its owners should review it.
|
||||||
|
- `shared/.githooks/post-commit` runs `shared/scripts/sync-consumers.ps1 -Commit` on commit once the hook path is configured (see `install-sync-hook.ps1`). `-Push` is opt-in (`sync-consumers.ps1:11-12` and `:370`). This is a developer-workflow concern rather than a runtime one.
|
||||||
@@ -7,6 +7,16 @@ APP_VERSION=dev
|
|||||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||||
COOKIE_SECURE=false
|
COOKIE_SECURE=false
|
||||||
|
|
||||||
|
# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and
|
||||||
|
# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the
|
||||||
|
# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16
|
||||||
|
TRUSTED_PROXIES=
|
||||||
|
|
||||||
|
# Set to "true" in production. Plain HTTP requests are refused unless they arrive
|
||||||
|
# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https.
|
||||||
|
# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning.
|
||||||
|
PRODUCTION=false
|
||||||
|
|
||||||
#################################################################
|
#################################################################
|
||||||
# Authentication (AuthGuard)
|
# Authentication (AuthGuard)
|
||||||
#################################################################
|
#################################################################
|
||||||
@@ -68,3 +78,8 @@ NOTIF_RETENTION_MS=604800000
|
|||||||
SECRET=change-me-to-a-long-random-value
|
SECRET=change-me-to-a-long-random-value
|
||||||
# Set true only for local development or a standalone deployment.
|
# Set true only for local development or a standalone deployment.
|
||||||
AUTH_DISABLED=false
|
AUTH_DISABLED=false
|
||||||
|
|
||||||
|
# Optional initial values for shipping server log lines to OmniLogger. Shipping runs only when both are set.
|
||||||
|
# ProjectConfigurator normally supplies the ingest token at runtime, so these can stay empty.
|
||||||
|
OMNILOGGER_URL=
|
||||||
|
OMNILOGGER_INGEST_TOKEN=
|
||||||
+89
-7
@@ -24,6 +24,7 @@ docker run -d --name collabtable-server --restart unless-stopped \
|
|||||||
-p 8080:8080 \
|
-p 8080:8080 \
|
||||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||||
-e AUTHGUARD_URL=https://auth.example.com \
|
-e AUTHGUARD_URL=https://auth.example.com \
|
||||||
|
-e SECRET=<long-random-shared-secret> \
|
||||||
-e COOKIE_SECURE=false \
|
-e COOKIE_SECURE=false \
|
||||||
collabtable-server
|
collabtable-server
|
||||||
```
|
```
|
||||||
@@ -41,6 +42,10 @@ go test ./...
|
|||||||
go run .
|
go run .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`go test ./...` skips the tests that need a database. To run them, set `TEST_DATABASE_URL` to a
|
||||||
|
disposable PostgreSQL (a `postgres://` URL, never your real `DATABASE_URL`). Each test creates
|
||||||
|
its own schema in it and drops the schema afterwards.
|
||||||
|
|
||||||
To build the dashboard for the embedded production binary:
|
To build the dashboard for the embedded production binary:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -55,6 +60,26 @@ go -C backend build -o collabtable-server .
|
|||||||
|
|
||||||
The Dockerfile performs those dashboard and Go build steps automatically.
|
The Dockerfile performs those dashboard and Go build steps automatically.
|
||||||
|
|
||||||
|
## One-time legacy user remap
|
||||||
|
|
||||||
|
Databases from before the AuthGuard migration key list memberships and API tokens by the old
|
||||||
|
local user IDs. After the migration each person's identity is their AuthGuard ID, which is
|
||||||
|
usually different, so they sign in and see none of the lists they owned. Run this once, with the
|
||||||
|
server stopped and before any AuthGuard account signs in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# users.json: the array GET /api/auth/users returns, copied while signed in as an AuthGuard admin
|
||||||
|
collabtable-server remap-users --authguard-users users.json # dry run: prints the plan
|
||||||
|
collabtable-server remap-users --authguard-users users.json --apply # writes the remap
|
||||||
|
```
|
||||||
|
|
||||||
|
Legacy users are matched to AuthGuard accounts by email, or by username when the legacy account
|
||||||
|
has no email. For anything unmatched or ambiguous, pass `--map` with a JSON object from legacy ID to
|
||||||
|
AuthGuard ID, such as `{"3": 12}`. The tool refuses to write while a legacy user who owns rows is
|
||||||
|
unmapped, and it refuses a second run. If a legacy ID is also the ID of a different AuthGuard
|
||||||
|
account, the plan blocks until you pass `--accept-id-overlap`; use that only after confirming the
|
||||||
|
account has never signed in. `DATABASE_URL` must be set.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
All Android synchronization routes are prefixed with `/api/` and require:
|
All Android synchronization routes are prefixed with `/api/` and require:
|
||||||
@@ -82,9 +107,11 @@ accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/aut
|
|||||||
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
||||||
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
||||||
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
||||||
(authentication fully off -- no login screen, nothing gated). Only set `AUTH_DISABLED=true` for
|
(the browser-session gate is off). List access still requires membership. In this mode requests
|
||||||
local development or a deployment you are certain does not need access control. API tokens are
|
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
|
||||||
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
|
sync API tokens for identity 0 are rejected. Use it only for local development of the auth shell,
|
||||||
|
not for a working data deployment. API tokens are unrelated to AuthGuard (see below), hashed at
|
||||||
|
rest, and shown only when generated.
|
||||||
|
|
||||||
### Data
|
### Data
|
||||||
|
|
||||||
@@ -101,6 +128,14 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
- `POST /api/sync`
|
- `POST /api/sync`
|
||||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||||
|
|
||||||
|
The list, field, item and item-value collection GETs accept `limit` (default 200, maximum 500)
|
||||||
|
and an opaque `cursor`. They return `{ "items": [...], "nextCursor": "...", "hasMore": true }`;
|
||||||
|
continue with `nextCursor` while `hasMore` is true. The final page has an empty `nextCursor`.
|
||||||
|
`POST /api/sync` requires `lastSyncToken` (use `0` for the first sync) and returns at most 500
|
||||||
|
changes with `nextSyncToken` and `hasMore`. Clients must request each page until `hasMore` is
|
||||||
|
false. Older sync clients without `lastSyncToken` receive HTTP 400 and must be updated with the
|
||||||
|
server.
|
||||||
|
|
||||||
### Dashboard and health
|
### Dashboard and health
|
||||||
|
|
||||||
- `GET /health` is public.
|
- `GET /health` is public.
|
||||||
@@ -112,15 +147,27 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
|
|
||||||
- `PORT` — HTTP port, default `8080`
|
- `PORT` — HTTP port, default `8080`
|
||||||
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
||||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
- `COOKIE_SECURE` — set to `true` when served over HTTPS. It marks only the cookies CollabTable
|
||||||
|
clears on logout as `Secure`; the session cookie's attributes are set by AuthGuard.
|
||||||
|
- `TRUSTED_PROXIES` — comma-separated IP addresses or CIDR ranges of reverse proxies, default
|
||||||
|
unset (no proxy trusted). `X-Forwarded-For` is read for the client IP, used by the rate limits,
|
||||||
|
only when the socket peer is in this list; `X-Forwarded-Proto` is honoured the same way.
|
||||||
|
- `PRODUCTION` — set `true` for a production deployment, default `false`. Plain HTTP requests
|
||||||
|
get 403 unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends
|
||||||
|
`X-Forwarded-Proto: https` (`/health` stays open). Requires `TRUSTED_PROXIES`. With it unset,
|
||||||
|
the server logs a warning that TLS is off.
|
||||||
|
- `SECRET` — shared secret for the internal endpoints. Required unless `AUTH_DISABLED=true`:
|
||||||
|
without it the auth status endpoint reports the missing secret and auth-gated routes return 500.
|
||||||
|
- `ALLOWED_ORIGINS` — comma-separated browser origins allowed to call the API cross-origin with
|
||||||
|
credentials, default unset (no CORS headers; the dashboard is same-origin).
|
||||||
- `DATABASE_URL` — PostgreSQL connection string, required
|
- `DATABASE_URL` — PostgreSQL connection string, required
|
||||||
- `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service
|
- `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service
|
||||||
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
||||||
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
||||||
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
||||||
- `AUTH_DISABLED` — set `true` to disable authentication entirely (no login screen, nothing
|
- `AUTH_DISABLED` — set `true` to disable browser-session gates, default `false`. List access is
|
||||||
gated, every request treated as authenticated), default `false`. For local development or a
|
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
|
||||||
standalone deployment with no AuthGuard integration at all.
|
rejected. Use only for local auth-shell development, not a working data deployment.
|
||||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||||
@@ -129,6 +176,41 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
The Go server initializes the existing CollabTable tables in place, so switching from the
|
The Go server initializes the existing CollabTable tables in place, so switching from the
|
||||||
previous server does not require a data export or schema conversion.
|
previous server does not require a data export or schema conversion.
|
||||||
|
|
||||||
|
## Rate limits
|
||||||
|
|
||||||
|
The auth routes are throttled in process, per client IP (see `TRUSTED_PROXIES` for how the IP is
|
||||||
|
resolved): setup, login, TOTP and token regeneration allow 30 requests per minute, after which
|
||||||
|
the server answers 429 with `Retry-After`. Failed logins (401) are also counted per account
|
||||||
|
identifier, and an account is locked for its 15-minute window after 10 failures. Anyone who knows
|
||||||
|
an account name can therefore lock that account out for the window. Limits are per instance and
|
||||||
|
reset on restart. AuthGuard applies its own limits; confirm them separately.
|
||||||
|
The sync API is not throttled per request, because the bearer token is 256 bits and devices
|
||||||
|
sync often.
|
||||||
|
|
||||||
|
## Security headers
|
||||||
|
|
||||||
|
Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
|
||||||
|
`Referrer-Policy: strict-origin-when-cross-origin` and `Content-Security-Policy: frame-ancestors
|
||||||
|
'none'`. The dashboard page (`index.html`, including the fallback for deep links) gets a full
|
||||||
|
Content-Security-Policy instead: scripts only from this origin plus the page's own inline
|
||||||
|
bootstrap script, whose hash is read from the embedded `index.html` at request time, so it
|
||||||
|
follows every dashboard build. Styles allow `'unsafe-inline'` because the page shell uses a style
|
||||||
|
attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
|
||||||
|
|
||||||
|
## Access model
|
||||||
|
|
||||||
|
List, field, item and value reads and writes are scoped to `list_memberships`. On migration,
|
||||||
|
every current API-token user is granted access to every existing list because the old schema did
|
||||||
|
not store owners. Lists created afterward are owned only by their creator. There is currently no
|
||||||
|
API for owners to add or remove members, so a newly created list is private to its creator's
|
||||||
|
account and devices. Deleting an item, field or list still removes its values permanently, while
|
||||||
|
the parent rows remain soft-deleted.
|
||||||
|
|
||||||
|
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
||||||
|
ProjectConfigurator), browser-session gates are bypassed. Data remains membership-scoped; the
|
||||||
|
placeholder identity 0 has no memberships, so `/web/data` contains no lists. A caller without a
|
||||||
|
session can only mint a token for that placeholder identity, and the sync API refuses it.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
+21
-5
@@ -139,15 +139,31 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
|
|||||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// getAPITokenUserID answers 0 for an unknown token. 0 is also the
|
||||||
|
// placeholder identity used when login is off, so tokens minted without
|
||||||
|
// a session are refused here as well (see handleTokenRegenerate).
|
||||||
if userID == 0 {
|
if userID == 0 {
|
||||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
ctx := context.WithValue(r.Context(), apiUserIDContextKey{}, userID)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type apiUserIDContextKey struct{}
|
||||||
|
|
||||||
|
func requestUserID(r *http.Request) int64 {
|
||||||
|
if userID, ok := r.Context().Value(apiUserIDContextKey{}).(int64); ok {
|
||||||
|
return userID
|
||||||
|
}
|
||||||
|
if user := sharedauth.UserFromContext(r.Context()); user != nil {
|
||||||
|
return user.ID
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
func extractBearer(r *http.Request) string {
|
func extractBearer(r *http.Request) string {
|
||||||
header := r.Header.Get("Authorization")
|
header := r.Header.Get("Authorization")
|
||||||
if !strings.HasPrefix(header, "Bearer ") {
|
if !strings.HasPrefix(header, "Bearer ") {
|
||||||
@@ -173,10 +189,10 @@ func hashToken(token string) string {
|
|||||||
// view/regenerate the bearer token its own devices use against the sync API.
|
// view/regenerate the bearer token its own devices use against the sync API.
|
||||||
// The caller's identity is resolved via sharedauth.UserFromContext, populated
|
// The caller's identity is resolved via sharedauth.UserFromContext, populated
|
||||||
// by the s.auth.Require wrapper server.go mounts these routes behind -- in
|
// by the s.auth.Require wrapper server.go mounts these routes behind -- in
|
||||||
// auth-disabled mode that middleware always resolves to sharedauth's fixed
|
// auth-disabled mode, or while login is switched off, that middleware always
|
||||||
// placeholder identity (ID 0), so a token minted in that mode is real and
|
// resolves to sharedauth's fixed placeholder identity (ID 0). A token minted
|
||||||
// functional, just scoped to that one shared identity rather than a
|
// for it is stored, but requireAPIToken never accepts identity 0, so a caller
|
||||||
// per-account AuthGuard identity, matching the pre-migration behavior.
|
// without a session cannot turn it into access to the sync API.
|
||||||
func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
user := sharedauth.UserFromContext(r.Context())
|
user := sharedauth.UserFromContext(r.Context())
|
||||||
if user == nil {
|
if user == nil {
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// parseTrustedProxies reads TRUSTED_PROXIES, a comma-separated list of IP
|
||||||
|
// addresses and CIDR ranges for reverse proxies whose forwarding headers may be
|
||||||
|
// believed. An empty value trusts no proxy.
|
||||||
|
func parseTrustedProxies(value string) ([]*net.IPNet, error) {
|
||||||
|
var networks []*net.IPNet
|
||||||
|
for _, entry := range strings.Split(value, ",") {
|
||||||
|
entry = strings.TrimSpace(entry)
|
||||||
|
if entry == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(entry); ip != nil {
|
||||||
|
if v4 := ip.To4(); v4 != nil {
|
||||||
|
ip = v4
|
||||||
|
}
|
||||||
|
networks = append(networks, &net.IPNet{IP: ip, Mask: net.CIDRMask(8*len(ip), 8*len(ip))})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, network, err := net.ParseCIDR(entry)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("TRUSTED_PROXIES entry %q is neither an IP address nor a CIDR range", entry)
|
||||||
|
}
|
||||||
|
networks = append(networks, network)
|
||||||
|
}
|
||||||
|
return networks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientIP returns the address a request is attributed to, for rate limits and
|
||||||
|
// logs. The socket peer is used unless it is a trusted proxy. Only then is
|
||||||
|
// X-Forwarded-For read, walking from the nearest hop outwards and stopping at
|
||||||
|
// the first address that is not itself a trusted proxy. A malformed chain falls
|
||||||
|
// back to the peer, so an unknown caller cannot choose the address it appears as.
|
||||||
|
func clientIP(r *http.Request, trusted []*net.IPNet) string {
|
||||||
|
peer := remoteHost(r.RemoteAddr)
|
||||||
|
peerIP := net.ParseIP(peer)
|
||||||
|
if peerIP == nil || !inNetworks(peerIP, trusted) {
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||||
|
var leftmost net.IP
|
||||||
|
for i := len(hops) - 1; i >= 0; i-- {
|
||||||
|
hop := net.ParseIP(strings.TrimSpace(hops[i]))
|
||||||
|
if hop == nil {
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
if !inNetworks(hop, trusted) {
|
||||||
|
return hop.String()
|
||||||
|
}
|
||||||
|
leftmost = hop
|
||||||
|
}
|
||||||
|
if leftmost != nil {
|
||||||
|
return leftmost.String()
|
||||||
|
}
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
|
||||||
|
// requestIsHTTPS reports whether the client's connection was encrypted: either
|
||||||
|
// TLS terminated in this process, or a trusted proxy reported https through
|
||||||
|
// X-Forwarded-Proto. The header is ignored from any other peer.
|
||||||
|
func requestIsHTTPS(r *http.Request, trusted []*net.IPNet) bool {
|
||||||
|
if r.TLS != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
peerIP := net.ParseIP(remoteHost(r.RemoteAddr))
|
||||||
|
if peerIP == nil || !inNetworks(peerIP, trusted) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
protos := strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")
|
||||||
|
return strings.EqualFold(strings.TrimSpace(protos[len(protos)-1]), "https")
|
||||||
|
}
|
||||||
|
|
||||||
|
func remoteHost(remoteAddr string) string {
|
||||||
|
host, _, err := net.SplitHostPort(remoteAddr)
|
||||||
|
if err != nil {
|
||||||
|
return remoteAddr
|
||||||
|
}
|
||||||
|
return host
|
||||||
|
}
|
||||||
|
|
||||||
|
func inNetworks(ip net.IP, networks []*net.IPNet) bool {
|
||||||
|
for _, network := range networks {
|
||||||
|
if network.Contains(ip) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mustTrusted(t *testing.T, value string) []*net.IPNet {
|
||||||
|
t.Helper()
|
||||||
|
networks, err := parseTrustedProxies(value)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseTrustedProxies(%q) error = %v", value, err)
|
||||||
|
}
|
||||||
|
return networks
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTrustedProxiesAcceptsAddressesAndRanges(t *testing.T) {
|
||||||
|
networks := mustTrusted(t, " 10.0.0.5, 192.168.2.0/24 ,, fd00::1 ")
|
||||||
|
if len(networks) != 3 {
|
||||||
|
t.Fatalf("parsed %d networks, want 3", len(networks))
|
||||||
|
}
|
||||||
|
for _, ip := range []string{"10.0.0.5", "192.168.2.77", "fd00::1"} {
|
||||||
|
if !inNetworks(net.ParseIP(ip), networks) {
|
||||||
|
t.Fatalf("%s should be trusted", ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, ip := range []string{"10.0.0.6", "192.168.3.1", "fd00::2"} {
|
||||||
|
if inNetworks(net.ParseIP(ip), networks) {
|
||||||
|
t.Fatalf("%s should not be trusted", ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTrustedProxiesEmptyTrustsNothing(t *testing.T) {
|
||||||
|
networks := mustTrusted(t, "")
|
||||||
|
if len(networks) != 0 {
|
||||||
|
t.Fatalf("empty TRUSTED_PROXIES parsed %d networks, want none", len(networks))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTrustedProxiesRejectsGarbage(t *testing.T) {
|
||||||
|
for _, value := range []string{"proxy.local", "10.0.0.0/33", "10.0.0.1/", "999.1.1.1"} {
|
||||||
|
if _, err := parseTrustedProxies(value); err == nil {
|
||||||
|
t.Fatalf("parseTrustedProxies(%q) returned no error", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientIPUsesSocketPeerUnlessPeerIsTrusted(t *testing.T) {
|
||||||
|
trusted := mustTrusted(t, "10.0.0.1")
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
remoteAddr string
|
||||||
|
forwarded string
|
||||||
|
trusted []*net.IPNet
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "untrusted peer ignores forwarded header", remoteAddr: "192.0.2.9:4000", forwarded: "203.0.113.7", trusted: trusted, want: "192.0.2.9"},
|
||||||
|
{name: "no trusted proxies at all", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: nil, want: "10.0.0.1"},
|
||||||
|
{name: "trusted peer uses forwarded client", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: trusted, want: "203.0.113.7"},
|
||||||
|
{name: "trusted peer without header uses peer", remoteAddr: "10.0.0.1:4000", forwarded: "", trusted: trusted, want: "10.0.0.1"},
|
||||||
|
{name: "chain skips trusted hops", remoteAddr: "10.0.0.1:4000", forwarded: "198.51.100.4, 203.0.113.7, 10.0.0.1", trusted: trusted, want: "203.0.113.7"},
|
||||||
|
{name: "spoofed leftmost entry is not used", remoteAddr: "10.0.0.1:4000", forwarded: "1.2.3.4, 203.0.113.7", trusted: trusted, want: "203.0.113.7"},
|
||||||
|
{name: "malformed entry falls back to peer", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7, not-an-ip", trusted: trusted, want: "10.0.0.1"},
|
||||||
|
{name: "all hops trusted returns leftmost", remoteAddr: "10.0.0.1:4000", forwarded: "10.0.0.1, 10.0.0.1", trusted: trusted, want: "10.0.0.1"},
|
||||||
|
{name: "IPv6 forwarded client is normalised", remoteAddr: "10.0.0.1:4000", forwarded: "2001:DB8::7", trusted: trusted, want: "2001:db8::7"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil)
|
||||||
|
request.RemoteAddr = tc.remoteAddr
|
||||||
|
if tc.forwarded != "" {
|
||||||
|
request.Header.Set("X-Forwarded-For", tc.forwarded)
|
||||||
|
}
|
||||||
|
if got := clientIP(request, tc.trusted); got != tc.want {
|
||||||
|
t.Fatalf("clientIP() = %q, want %q", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequestIsHTTPSHonoursTLSOrTrustedProxyOnly(t *testing.T) {
|
||||||
|
trusted := mustTrusted(t, "10.0.0.1")
|
||||||
|
|
||||||
|
direct := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||||
|
direct.TLS = &tls.ConnectionState{}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
remoteAddr string
|
||||||
|
proto string
|
||||||
|
tlsConn bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "plain request", remoteAddr: "192.0.2.9:4000", want: false},
|
||||||
|
{name: "terminated here", remoteAddr: "192.0.2.9:4000", tlsConn: true, want: true},
|
||||||
|
{name: "trusted proxy reports https", remoteAddr: "10.0.0.1:4000", proto: "https", want: true},
|
||||||
|
{name: "trusted proxy reports http", remoteAddr: "10.0.0.1:4000", proto: "http", want: false},
|
||||||
|
{name: "untrusted peer claims https", remoteAddr: "192.0.2.9:4000", proto: "https", want: false},
|
||||||
|
{name: "last proto hop decides", remoteAddr: "10.0.0.1:4000", proto: "https, http", want: false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||||
|
request.RemoteAddr = tc.remoteAddr
|
||||||
|
if tc.proto != "" {
|
||||||
|
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||||
|
}
|
||||||
|
if tc.tlsConn {
|
||||||
|
request.TLS = direct.TLS
|
||||||
|
}
|
||||||
|
if got := requestIsHTTPS(request, trusted); got != tc.want {
|
||||||
|
t.Fatalf("requestIsHTTPS() = %v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
scriptElement = regexp.MustCompile(`(?is)<script\b([^>]*)>(.*?)</script\s*>`)
|
||||||
|
scriptSrcAttribute = regexp.MustCompile(`(?i)\bsrc\s*=`)
|
||||||
|
// A browser reads a CR or CRLF in the HTML source as LF, and hashes that.
|
||||||
|
htmlNewlines = strings.NewReplacer("\r\n", "\n", "\r", "\n")
|
||||||
|
)
|
||||||
|
|
||||||
|
// inlineScriptHashes returns a CSP hash source for every inline <script> in the
|
||||||
|
// page. SvelteKit's static build puts one bootstrap script in index.html, and its
|
||||||
|
// text changes with every build, so the hash is read from the page being served
|
||||||
|
// instead of being configured.
|
||||||
|
func inlineScriptHashes(page []byte) []string {
|
||||||
|
var hashes []string
|
||||||
|
for _, match := range scriptElement.FindAllSubmatch(page, -1) {
|
||||||
|
if scriptSrcAttribute.Match(match[1]) || len(match[2]) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256([]byte(htmlNewlines.Replace(string(match[2]))))
|
||||||
|
hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'")
|
||||||
|
}
|
||||||
|
return hashes
|
||||||
|
}
|
||||||
|
|
||||||
|
// dashboardCSP is the Content-Security-Policy for the dashboard page. Scripts may
|
||||||
|
// only come from this origin or be the page's own inline bootstrap script, so an
|
||||||
|
// injected script does not run. Styles keep 'unsafe-inline' because the page
|
||||||
|
// shell uses a style attribute; the bundle has no eval, workers or external URLs.
|
||||||
|
func dashboardCSP(page []byte) string {
|
||||||
|
scriptSrc := append([]string{"script-src 'self'"}, inlineScriptHashes(page)...)
|
||||||
|
return strings.Join([]string{
|
||||||
|
"default-src 'self'",
|
||||||
|
strings.Join(scriptSrc, " "),
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self' data:",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
}, "; ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func scriptHash(text string) string {
|
||||||
|
sum := sha256.Sum256([]byte(text))
|
||||||
|
return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInlineScriptHashesCoversOnlyInlineScripts(t *testing.T) {
|
||||||
|
const bootstrap = "\n\t{\n\t\tconst element = document.currentScript.parentElement;\n\t}\n"
|
||||||
|
page := `<html><head><script src="/_app/start.js"></script>
|
||||||
|
<script type="module" crossorigin src="/_app/other.js"></script><script></script></head>
|
||||||
|
<body><script>` + bootstrap + `</script></body></html>`
|
||||||
|
|
||||||
|
got := inlineScriptHashes([]byte(page))
|
||||||
|
if len(got) != 1 || got[0] != scriptHash(bootstrap) {
|
||||||
|
t.Fatalf("inlineScriptHashes() = %v, want only %s", got, scriptHash(bootstrap))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInlineScriptHashesNormalizesNewlinesLikeABrowser(t *testing.T) {
|
||||||
|
got := inlineScriptHashes([]byte("<script>a();\r\nb();\rc();</script>"))
|
||||||
|
if len(got) != 1 || got[0] != scriptHash("a();\nb();\nc();") {
|
||||||
|
t.Fatalf("inlineScriptHashes() = %v, want the hash of the LF-normalized text", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDashboardCSPAllowsOnlyOwnAndHashedScripts(t *testing.T) {
|
||||||
|
const bootstrap = "start();"
|
||||||
|
policy := dashboardCSP([]byte("<body><script>" + bootstrap + "</script></body>"))
|
||||||
|
|
||||||
|
directives := map[string]string{}
|
||||||
|
for _, part := range strings.Split(policy, "; ") {
|
||||||
|
name, value, _ := strings.Cut(part, " ")
|
||||||
|
directives[name] = value
|
||||||
|
}
|
||||||
|
if want := "'self' " + scriptHash(bootstrap); directives["script-src"] != want {
|
||||||
|
t.Fatalf("script-src = %q, want %q", directives["script-src"], want)
|
||||||
|
}
|
||||||
|
for name, want := range map[string]string{
|
||||||
|
"default-src": "'self'",
|
||||||
|
"object-src": "'none'",
|
||||||
|
"base-uri": "'self'",
|
||||||
|
"frame-ancestors": "'none'",
|
||||||
|
} {
|
||||||
|
if directives[name] != want {
|
||||||
|
t.Fatalf("%s = %q, want %q", name, directives[name], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(directives["script-src"], "unsafe") {
|
||||||
|
t.Fatalf("script-src = %q, must not allow unsafe-inline or unsafe-eval", directives["script-src"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDashboardCSPWithoutInlineScriptAllowsOnlyOwnOrigin(t *testing.T) {
|
||||||
|
policy := dashboardCSP([]byte("<html></html>"))
|
||||||
|
if !strings.Contains(policy, "script-src 'self';") {
|
||||||
|
t.Fatalf("policy = %q, want script-src limited to 'self'", policy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSPAFileServerSendsDashboardCSPOnThePageOnly(t *testing.T) {
|
||||||
|
const bootstrap = "start();"
|
||||||
|
root := fstest.MapFS{
|
||||||
|
"index.html": {Data: []byte("<html><body><script>" + bootstrap + "</script></body></html>")},
|
||||||
|
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
|
||||||
|
}
|
||||||
|
// Behind withSecurityHeaders, as in main: the page's policy replaces the
|
||||||
|
// frame-ancestors-only default instead of being added to it.
|
||||||
|
handler := withSecurityHeaders(spaFileServer(root))
|
||||||
|
|
||||||
|
for _, path := range []string{"/", "/index.html", "/lists/123"} {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil))
|
||||||
|
values := recorder.Header().Values("Content-Security-Policy")
|
||||||
|
if len(values) != 1 || !strings.Contains(values[0], scriptHash(bootstrap)) || !strings.Contains(values[0], "frame-ancestors 'none'") {
|
||||||
|
t.Fatalf("GET %s Content-Security-Policy = %q, want one full policy with the bootstrap hash", path, values)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
asset := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(asset, httptest.NewRequest(http.MethodGet, "/_app/immutable/app.abc.js", nil))
|
||||||
|
if got := asset.Header().Get("Content-Security-Policy"); got != "frame-ancestors 'none'" {
|
||||||
|
t.Fatalf("asset Content-Security-Policy = %q, want the frame-ancestors default", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+504
-144
@@ -65,21 +65,23 @@ func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
|||||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
func (d *DB) queryLists(ctx context.Context, userID int64, includeDeleted bool, since *int64) ([]List, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 1)
|
args := make([]any, 0, 2)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
if since != nil {
|
if since != nil {
|
||||||
conditions = append(conditions, "updatedat >= $1")
|
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
}
|
}
|
||||||
query := `SELECT ` + listColumns + ` FROM lists`
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
}
|
}
|
||||||
query += " ORDER BY updatedat DESC"
|
query += " ORDER BY updatedat DESC, id"
|
||||||
|
|
||||||
rows, err := d.pool.Query(ctx, query, args...)
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -98,9 +100,11 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
|||||||
return lists, rows.Err()
|
return lists, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
func (d *DB) queryFields(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -116,7 +120,7 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
}
|
}
|
||||||
query += ` ORDER BY "order" ASC`
|
query += ` ORDER BY "order" ASC, id`
|
||||||
|
|
||||||
rows, err := d.pool.Query(ctx, query, args...)
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -134,9 +138,11 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return fields, rows.Err()
|
return fields, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
func (d *DB) queryItems(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -152,7 +158,7 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
}
|
}
|
||||||
query += " ORDER BY updatedat DESC"
|
query += " ORDER BY updatedat DESC, id"
|
||||||
|
|
||||||
rows, err := d.pool.Query(ctx, query, args...)
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -170,9 +176,11 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return items, rows.Err()
|
return items, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
func (d *DB) queryValues(ctx context.Context, userID int64, since *int64, itemID string) ([]ItemValue, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
if since != nil {
|
if since != nil {
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
@@ -185,7 +193,7 @@ func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]It
|
|||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
}
|
}
|
||||||
query += " ORDER BY updatedat ASC"
|
query += " ORDER BY updatedat ASC, id"
|
||||||
|
|
||||||
rows, err := d.pool.Query(ctx, query, args...)
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -220,6 +228,132 @@ func boolInt(value bool) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fieldDefaults fills in the field type and alignment that clients may leave out.
|
||||||
|
func fieldDefaults(fieldType, alignment string) (string, string) {
|
||||||
|
if fieldType == "" {
|
||||||
|
fieldType = "TEXT"
|
||||||
|
}
|
||||||
|
if alignment == "" {
|
||||||
|
alignment = "start"
|
||||||
|
}
|
||||||
|
return fieldType, alignment
|
||||||
|
}
|
||||||
|
|
||||||
|
// The upsert helpers below write one row each and report whether the write was
|
||||||
|
// applied. A write older than the stored row loses (last writer wins by client
|
||||||
|
// timestamp) and changes nothing, so callers skip the cascade and notification
|
||||||
|
// for it.
|
||||||
|
func upsertList(ctx context.Context, executor queryExecutor, list List, createdAt, updatedAt int64) (bool, error) {
|
||||||
|
result, err := executor.Exec(ctx, `
|
||||||
|
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||||
|
WHERE EXCLUDED.updatedat >= lists.updatedat
|
||||||
|
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected() > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func upsertField(ctx context.Context, executor queryExecutor, field Field, createdAt, updatedAt int64) (bool, error) {
|
||||||
|
fieldType, alignment := fieldDefaults(field.FieldType, field.Alignment)
|
||||||
|
result, err := executor.Exec(ctx, `
|
||||||
|
INSERT INTO fields
|
||||||
|
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET name = EXCLUDED.name,
|
||||||
|
fieldtype = EXCLUDED.fieldtype,
|
||||||
|
fieldoptions = EXCLUDED.fieldoptions,
|
||||||
|
alignment = EXCLUDED.alignment,
|
||||||
|
"order" = EXCLUDED."order",
|
||||||
|
updatedat = EXCLUDED.updatedat,
|
||||||
|
isdeleted = EXCLUDED.isdeleted
|
||||||
|
WHERE EXCLUDED.updatedat >= fields.updatedat
|
||||||
|
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected() > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func upsertItem(ctx context.Context, executor queryExecutor, item Item, createdAt, updatedAt int64) (bool, error) {
|
||||||
|
result, err := executor.Exec(ctx, `
|
||||||
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||||
|
WHERE EXCLUDED.updatedat >= items.updatedat
|
||||||
|
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected() > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// upsertValue also ignores a value that names a different item or field than the
|
||||||
|
// stored row, so a write cannot move a value onto another cell.
|
||||||
|
func upsertValue(ctx context.Context, executor queryExecutor, value ItemValue, updatedAt int64) (bool, error) {
|
||||||
|
result, err := executor.Exec(ctx, `
|
||||||
|
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||||
|
WHERE EXCLUDED.updatedat >= item_values.updatedat
|
||||||
|
AND item_values.itemid = EXCLUDED.itemid
|
||||||
|
AND item_values.fieldid = EXCLUDED.fieldid
|
||||||
|
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected() > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cascadeDeleteList removes the children of a deleted list: its fields and items
|
||||||
|
// are soft-deleted and their values are hard-deleted. The REST and sync delete
|
||||||
|
// paths both call it, so they leave the same state behind.
|
||||||
|
func cascadeDeleteList(ctx context.Context, tx pgx.Tx, listID string, updatedAt int64) error {
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// cascadeDeleteField removes the values of a deleted field. When no active field
|
||||||
|
// remains in the list, the list's items are deleted too, and the returned flag
|
||||||
|
// reports that.
|
||||||
|
func cascadeDeleteField(ctx context.Context, tx pgx.Tx, fieldID, listID string, updatedAt int64) (bool, error) {
|
||||||
|
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE fieldid = $1`, fieldID); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
var remaining int
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, listID).Scan(&remaining); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if remaining > 0 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cascadeDeleteItem removes the values of a deleted item.
|
||||||
|
func cascadeDeleteItem(ctx context.Context, tx pgx.Tx, itemID string) error {
|
||||||
|
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid = $1`, itemID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
type listMutation struct {
|
type listMutation struct {
|
||||||
List
|
List
|
||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
@@ -227,7 +361,11 @@ type listMutation struct {
|
|||||||
|
|
||||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == http.MethodGet {
|
if r.Method == http.MethodGet {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
page, ok := requestPage(w, r, "lists")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lists, err := s.db.queryListPage(r.Context(), requestUserID(r), false, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||||
return
|
return
|
||||||
@@ -237,23 +375,42 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var request listMutation
|
var request listMutation
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.ID == "" || request.Name == "" {
|
if request.ID == "" || request.Name == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
return err
|
||||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
}
|
||||||
|
if _, err := authorizeList(r.Context(), tx, requestUserID(r), request.ID, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := addListOwner(r.Context(), tx, requestUserID(r), request.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
|
||||||
list, err := s.db.getList(r.Context(), request.ID)
|
list, err := s.db.getList(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
@@ -266,6 +423,9 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
id := r.PathValue("id")
|
id := r.PathValue("id")
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
|
if !s.requireListMembership(w, r, id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
list, err := s.db.getList(r.Context(), id)
|
list, err := s.db.getList(r.Context(), id)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
@@ -285,22 +445,39 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
}
|
}
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
var list List
|
||||||
if err != nil {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||||
|
var scanErr error
|
||||||
|
list, scanErr = scanList(tx.QueryRow(r.Context(), `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
|
return scanErr
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
|
||||||
list, err := s.db.getList(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||||
return
|
return
|
||||||
@@ -308,16 +485,38 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, list)
|
writeJSON(w, http.StatusOK, list)
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
if err := cascadeDeleteList(r.Context(), tx, id, updatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -328,7 +527,15 @@ type fieldMutation struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
listID := r.PathValue("listId")
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "fields")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fields, err := s.db.queryFieldsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||||
return
|
return
|
||||||
@@ -338,30 +545,45 @@ func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||||
var request fieldMutation
|
var request fieldMutation
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.Alignment == "" {
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
request.Alignment = "start"
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
}
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
if request.FieldType == "" {
|
return err
|
||||||
request.FieldType = "TEXT"
|
}
|
||||||
}
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
if err != nil {
|
||||||
INSERT INTO fields
|
return err
|
||||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
}
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
if !member {
|
||||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO fields
|
||||||
|
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
field, err := s.getField(r.Context(), request.ID)
|
field, err := s.getField(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
@@ -386,74 +608,91 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
Order int `json:"order"`
|
Order int `json:"order"`
|
||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
}
|
}
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.Alignment == "" {
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
request.Alignment = "start"
|
|
||||||
}
|
|
||||||
if request.FieldType == "" {
|
|
||||||
request.FieldType = "TEXT"
|
|
||||||
}
|
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `
|
var field Field
|
||||||
UPDATE fields
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
WHERE id = $7
|
return err
|
||||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
}
|
||||||
if err != nil {
|
var listID string
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `
|
||||||
|
UPDATE fields
|
||||||
|
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||||
|
WHERE id = $7
|
||||||
|
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
field, scanErr = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
field, err := s.getField(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, field)
|
writeJSON(w, http.StatusOK, field)
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
var request struct {
|
var request struct {
|
||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
}
|
}
|
||||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
_ = decodeJSON(w, r, &request) // DELETE bodies are optional.
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
var field Field
|
var field Field
|
||||||
cascade := false
|
cascade := false
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
|
cascade, err = cascadeDeleteField(r.Context(), tx, id, field.ListID, updatedAt)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var remaining int
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if remaining == 0 {
|
|
||||||
cascade = true
|
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -478,7 +717,14 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
|||||||
listID = parts[1]
|
listID = parts[1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "items")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := s.db.queryItemsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||||
return
|
return
|
||||||
@@ -488,23 +734,43 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||||
var request itemMutation
|
var request itemMutation
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.ID == "" || request.ListID == "" {
|
if request.ID == "" || request.ListID == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
return err
|
||||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
item, err := s.getItem(r.Context(), request.ID)
|
item, err := s.getItem(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
@@ -525,7 +791,23 @@ func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
itemID = parts[0]
|
itemID = parts[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
var listID string
|
||||||
|
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, itemID).Scan(&listID); err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
|
} else {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "values")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
values, err := s.db.queryValuesPage(r.Context(), requestUserID(r), itemID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
return
|
return
|
||||||
@@ -538,37 +820,65 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
|||||||
ItemValue
|
ItemValue
|
||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
}
|
}
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSON(w, r, &request); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
writeDecodeError(w, err, "Invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
|
||||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
ON CONFLICT (id) DO UPDATE
|
|
||||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
|
||||||
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
|
|
||||||
if err != nil {
|
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var listID string
|
|
||||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
|
||||||
}
|
|
||||||
var value ItemValue
|
var value ItemValue
|
||||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
&value.ID,
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
&value.ItemID,
|
return err
|
||||||
&value.FieldID,
|
}
|
||||||
&value.Value,
|
var fieldListID, itemListID string
|
||||||
&value.UpdatedAt,
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&fieldListID); err != nil {
|
||||||
)
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, request.ItemID).Scan(&itemListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fieldListID != itemListID {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), fieldListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
var storedItemID, storedFieldID string
|
||||||
|
storedErr := tx.QueryRow(r.Context(), `SELECT itemid, fieldid FROM item_values WHERE id = $1`, request.ID).Scan(&storedItemID, &storedFieldID)
|
||||||
|
if storedErr == nil && (storedItemID != request.ItemID || storedFieldID != request.FieldID) {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
if storedErr != nil && !errors.Is(storedErr, pgx.ErrNoRows) {
|
||||||
|
return storedErr
|
||||||
|
}
|
||||||
|
applied, err := upsertValue(r.Context(), tx, request.ItemValue, int64(request.UpdatedAt))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// An older write than the stored value changes nothing, so it notifies no one.
|
||||||
|
if applied {
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
value, scanErr = scanItemValue(tx.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID))
|
||||||
|
return scanErr
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) || errors.Is(err, errCellIdentityMismatch) || errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item value not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -584,41 +894,91 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
DeviceID string `json:"deviceId,omitempty"`
|
DeviceID string `json:"deviceId,omitempty"`
|
||||||
}
|
}
|
||||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||||
_ = decodeJSON(r, &request)
|
_ = decodeJSON(w, r, &request)
|
||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
if r.Method == http.MethodPut {
|
if r.Method == http.MethodPut {
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
var item Item
|
||||||
if err != nil {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
item, scanErr = scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
item, err := s.getItem(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, item)
|
writeJSON(w, http.StatusOK, item)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
if err != nil {
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
return err
|
||||||
return
|
}
|
||||||
}
|
var listID string
|
||||||
if result.RowsAffected() == 0 {
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
item, err := scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := cascadeDeleteItem(r.Context(), tx, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
item, itemErr := s.getItem(r.Context(), id)
|
if err != nil {
|
||||||
if itemErr == nil {
|
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
return
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFieldDefaultsFillMissingValues(t *testing.T) {
|
||||||
|
fieldType, alignment := fieldDefaults("", "")
|
||||||
|
if fieldType != "TEXT" || alignment != "start" {
|
||||||
|
t.Fatalf("fieldDefaults(empty) = (%q, %q), want (TEXT, start)", fieldType, alignment)
|
||||||
|
}
|
||||||
|
fieldType, alignment = fieldDefaults("NUMBER", "end")
|
||||||
|
if fieldType != "NUMBER" || alignment != "end" {
|
||||||
|
t.Fatalf("fieldDefaults(set) = (%q, %q), want (NUMBER, end)", fieldType, alignment)
|
||||||
|
}
|
||||||
|
}
|
||||||
+115
-3
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -35,6 +36,11 @@ func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
|||||||
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func lockChangeClock(ctx context.Context, tx pgx.Tx) error {
|
||||||
|
var token int64
|
||||||
|
return tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1 FOR UPDATE`).Scan(&token)
|
||||||
|
}
|
||||||
|
|
||||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||||
// be used by the Go server without a separate migration step.
|
// be used by the Go server without a separate migration step.
|
||||||
func (d *DB) initSchema(ctx context.Context) error {
|
func (d *DB) initSchema(ctx context.Context) error {
|
||||||
@@ -44,7 +50,8 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS fields (
|
CREATE TABLE IF NOT EXISTS fields (
|
||||||
@@ -58,6 +65,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -67,6 +75,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -76,6 +85,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
fieldid TEXT NOT NULL,
|
fieldid TEXT NOT NULL,
|
||||||
value TEXT,
|
value TEXT,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||||
);
|
);
|
||||||
@@ -84,6 +94,58 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
||||||
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
||||||
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_updatedat ON lists(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_page ON lists(updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_page ON fields(listid, "order" ASC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_page ON items(listid, updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_page ON item_values(itemid, updatedat ASC, id ASC);
|
||||||
|
ALTER TABLE lists ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE fields ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE items ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE item_values ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS collabtable_sync_clock (
|
||||||
|
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||||
|
token BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
INSERT INTO collabtable_sync_clock (id, token) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_change_token ON lists(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_change_token ON fields(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_change_token ON items(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_change_token ON item_values(change_token);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION collabtable_assign_change_token()
|
||||||
|
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE next_token BIGINT;
|
||||||
|
BEGIN
|
||||||
|
UPDATE collabtable_sync_clock SET token = token + 1 WHERE id = 1 RETURNING token INTO next_token;
|
||||||
|
IF next_token IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'sync clock row is missing';
|
||||||
|
END IF;
|
||||||
|
NEW.change_token := next_token;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'lists_change_token' AND tgrelid = 'lists'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER lists_change_token BEFORE INSERT OR UPDATE ON lists FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'fields_change_token' AND tgrelid = 'fields'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER fields_change_token BEFORE INSERT OR UPDATE ON fields FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'items_change_token' AND tgrelid = 'items'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER items_change_token BEFORE INSERT OR UPDATE ON items FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'item_values_change_token' AND tgrelid = 'item_values'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER item_values_change_token BEFORE INSERT OR UPDATE ON item_values FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS notifications (
|
CREATE TABLE IF NOT EXISTS notifications (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
@@ -186,14 +248,64 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||||
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS list_memberships (
|
||||||
|
listid TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
is_owner BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (listid, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_list_memberships_user ON list_memberships(user_id, listid);
|
||||||
`)
|
`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("initialize schema: %w", err)
|
return fmt.Errorf("initialize schema: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := d.backfillChangeTokens(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill change tokens: %w", err)
|
||||||
|
}
|
||||||
|
if err := d.backfillListMemberships(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill list memberships: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillListMemberships(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO list_memberships (listid, user_id, is_owner)
|
||||||
|
SELECT lists.id, token_users.user_id, FALSE
|
||||||
|
FROM lists
|
||||||
|
CROSS JOIN (SELECT DISTINCT user_id FROM api_tokens WHERE user_id <> 0) AS token_users
|
||||||
|
-- New lists already have their creator's membership, so they are not
|
||||||
|
-- expanded to every token user on later starts.
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM list_memberships existing WHERE existing.listid = lists.id)
|
||||||
|
ON CONFLICT (listid, user_id) DO NOTHING
|
||||||
|
`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillChangeTokens(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, table := range []string{"lists", "fields", "items", "item_values"} {
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE `+table+` SET change_token = change_token WHERE change_token = 0`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||||
ticker := time.NewTicker(time.Hour)
|
ticker := time.NewTicker(time.Hour)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@@ -203,7 +315,7 @@ func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||||
fmt.Printf("[db] session prune failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] session prune failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -223,7 +335,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
|
|||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
cutoff := time.Now().UnixMilli() - retention
|
cutoff := time.Now().UnixMilli() - retention
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
||||||
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] notification cleanup failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,866 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// These tests run the handlers against a real PostgreSQL. Set TEST_DATABASE_URL
|
||||||
|
// to a postgres:// URL of a database the tests may write to; without it they are
|
||||||
|
// skipped. Each test works in its own schema, which it drops afterwards, so the
|
||||||
|
// database can be shared. TEST_DATABASE_URL must not be the service's own
|
||||||
|
// DATABASE_URL.
|
||||||
|
|
||||||
|
const (
|
||||||
|
testBearer = "test-device-token"
|
||||||
|
// Realistic millisecond timestamps in the past, so normalizeTimestamp leaves
|
||||||
|
// them alone. Later writes use t0 plus an offset.
|
||||||
|
t0 = int64(1_700_000_000_000)
|
||||||
|
)
|
||||||
|
|
||||||
|
// testDB returns a DB on a fresh schema of TEST_DATABASE_URL, with the tables
|
||||||
|
// created by initSchema.
|
||||||
|
func testDB(t *testing.T) *DB {
|
||||||
|
t.Helper()
|
||||||
|
base := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL"))
|
||||||
|
if base == "" {
|
||||||
|
t.Skip("TEST_DATABASE_URL is not set; database-backed tests need a PostgreSQL they may write to")
|
||||||
|
}
|
||||||
|
if base == strings.TrimSpace(os.Getenv("DATABASE_URL")) {
|
||||||
|
t.Fatal("TEST_DATABASE_URL must not be the same database as DATABASE_URL")
|
||||||
|
}
|
||||||
|
parsed, err := url.Parse(base)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TEST_DATABASE_URL is not a URL: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
suffix := make([]byte, 6)
|
||||||
|
if _, err := rand.Read(suffix); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
schema := "collabtable_test_" + hex.EncodeToString(suffix)
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
admin, err := pgx.Connect(ctx, base)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect to TEST_DATABASE_URL: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||||
|
_ = admin.Close(ctx)
|
||||||
|
t.Fatalf("create schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
query := parsed.Query()
|
||||||
|
query.Set("search_path", schema)
|
||||||
|
parsed.RawQuery = query.Encode()
|
||||||
|
db, err := connectDB(ctx, parsed.String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connectDB: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
db.close()
|
||||||
|
_, _ = admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
|
||||||
|
_ = admin.Close(ctx)
|
||||||
|
})
|
||||||
|
if err := db.initSchema(ctx); err != nil {
|
||||||
|
t.Fatalf("initSchema: %v", err)
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
// testUserID owns testBearer. It is not 0: identity 0 is the placeholder used
|
||||||
|
// when login is off, and the sync API never accepts it.
|
||||||
|
const testUserID = 1
|
||||||
|
|
||||||
|
// testAPI serves the real routes over a test database. Auth is disabled, and the
|
||||||
|
// sync API accepts testBearer.
|
||||||
|
type testAPI struct {
|
||||||
|
t *testing.T
|
||||||
|
db *DB
|
||||||
|
mux *http.ServeMux
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestAPI(t *testing.T) *testAPI {
|
||||||
|
t.Helper()
|
||||||
|
db := testDB(t)
|
||||||
|
server := &Server{
|
||||||
|
db: db,
|
||||||
|
auth: newAuthService(db, "", false, true),
|
||||||
|
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
server.registerRoutes(mux, webFS)
|
||||||
|
if err := db.regenerateAPIToken(context.Background(), testUserID, hashToken(testBearer)); err != nil {
|
||||||
|
t.Fatalf("seed API token: %v", err)
|
||||||
|
}
|
||||||
|
return &testAPI{t: t, db: db, mux: mux}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
||||||
|
return a.doAs(method, path, device, testBearer, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) doAs(method, path, device, token string, body any) *httptest.ResponseRecorder {
|
||||||
|
a.t.Helper()
|
||||||
|
var reader *bytes.Reader
|
||||||
|
if body == nil {
|
||||||
|
reader = bytes.NewReader(nil)
|
||||||
|
} else {
|
||||||
|
encoded, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
a.t.Fatalf("encode request: %v", err)
|
||||||
|
}
|
||||||
|
reader = bytes.NewReader(encoded)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest(method, path, reader)
|
||||||
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if device != "" {
|
||||||
|
request.Header.Set("X-Device-Id", device)
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
a.mux.ServeHTTP(recorder, request)
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||||
|
a.t.Helper()
|
||||||
|
recorder := a.do(method, path, device, body)
|
||||||
|
if recorder.Code != wantStatus {
|
||||||
|
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||||
|
}
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) mustDoAs(method, path, device, token string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||||
|
a.t.Helper()
|
||||||
|
recorder := a.doAs(method, path, device, token, body)
|
||||||
|
if recorder.Code != wantStatus {
|
||||||
|
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||||
|
}
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||||
|
t.Helper()
|
||||||
|
var value T
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {
|
||||||
|
t.Fatalf("decode %q: %v", recorder.Body.String(), err)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
||||||
|
a.t.Helper()
|
||||||
|
if request.LastSyncToken == nil {
|
||||||
|
initialToken := int64(0)
|
||||||
|
request.LastSyncToken = &initialToken
|
||||||
|
}
|
||||||
|
request.DeviceID = device
|
||||||
|
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) currentSyncToken() int64 {
|
||||||
|
a.t.Helper()
|
||||||
|
var token int64
|
||||||
|
if err := a.db.pool.QueryRow(context.Background(), `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&token); err != nil {
|
||||||
|
a.t.Fatalf("read sync token: %v", err)
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
func ptrInt64(value int64) *int64 { return &value }
|
||||||
|
|
||||||
|
func (a *testAPI) count(query string, args ...any) int {
|
||||||
|
a.t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := a.db.pool.QueryRow(context.Background(), query, args...).Scan(&n); err != nil {
|
||||||
|
a.t.Fatalf("%s: %v", query, err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) notifications(eventType, entityType, entityID string) int {
|
||||||
|
a.t.Helper()
|
||||||
|
return a.count(`SELECT count(*) FROM notifications WHERE eventtype = $1 AND entitytype = $2 AND entityid = $3`, eventType, entityType, entityID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// cascadeState summarizes a list and its children, so two delete paths can be
|
||||||
|
// compared: the list's isdeleted flag, deleted/total fields and items, and the
|
||||||
|
// number of values left on the list's items.
|
||||||
|
func (a *testAPI) cascadeState(listID string) string {
|
||||||
|
a.t.Helper()
|
||||||
|
return fmt.Sprintf("list=%d fields=%d/%d items=%d/%d values=%d",
|
||||||
|
a.count(`SELECT isdeleted FROM lists WHERE id = $1`, listID),
|
||||||
|
a.count(`SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 1`, listID),
|
||||||
|
a.count(`SELECT count(*) FROM fields WHERE listid = $1`, listID),
|
||||||
|
a.count(`SELECT count(*) FROM items WHERE listid = $1 AND isdeleted = 1`, listID),
|
||||||
|
a.count(`SELECT count(*) FROM items WHERE listid = $1`, listID),
|
||||||
|
a.count(`SELECT count(*) FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testList(id, name string, updatedAt int64, deleted bool) List {
|
||||||
|
return List{ID: id, Name: name, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testField(id, listID, name string, updatedAt int64, deleted bool) Field {
|
||||||
|
return Field{ID: id, ListID: listID, Name: name, FieldType: "TEXT", Alignment: "start", CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testItem(id, listID string, updatedAt int64, deleted bool) Item {
|
||||||
|
return Item{ID: id, ListID: listID, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testValue(id, itemID, fieldID, value string, updatedAt int64) ItemValue {
|
||||||
|
return ItemValue{ID: id, ItemID: itemID, FieldID: fieldID, Value: value, UpdatedAt: Timestamp(updatedAt)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// seedList pushes a list with two fields, one item and a value in each field, all
|
||||||
|
// stamped t0+10, as one device's first sync. Its IDs are prefix-list, prefix-f1,
|
||||||
|
// prefix-f2, prefix-item, prefix-v1 and prefix-v2.
|
||||||
|
func (a *testAPI) seedList(device, prefix string) {
|
||||||
|
a.t.Helper()
|
||||||
|
at := t0 + 10
|
||||||
|
a.sync(device, SyncRequest{
|
||||||
|
Lists: []List{testList(prefix+"-list", "Groceries", at, false)},
|
||||||
|
Fields: []Field{testField(prefix+"-f1", prefix+"-list", "Name", at, false), testField(prefix+"-f2", prefix+"-list", "Qty", at, false)},
|
||||||
|
Items: []Item{testItem(prefix+"-item", prefix+"-list", at, false)},
|
||||||
|
ItemValues: []ItemValue{
|
||||||
|
testValue(prefix+"-v1", prefix+"-item", prefix+"-f1", "milk", at),
|
||||||
|
testValue(prefix+"-v2", prefix+"-item", prefix+"-f2", "2", at),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('backfill', 'Backfill', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists DISABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `UPDATE lists SET change_token = 0 WHERE id = 'backfill'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists ENABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
|
t.Fatalf("second initSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
var firstToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&firstToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if firstToken == 0 {
|
||||||
|
t.Fatal("initSchema left an existing list without a change token")
|
||||||
|
}
|
||||||
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
|
t.Fatalf("third initSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
var secondToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&secondToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if secondToken != firstToken {
|
||||||
|
t.Fatalf("re-running initSchema changed backfilled token from %d to %d", firstToken, secondToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
|
||||||
|
// A device that has never synced gets everything.
|
||||||
|
full := api.sync("tablet", SyncRequest{})
|
||||||
|
if len(full.Lists) != 1 || len(full.Fields) != 2 || len(full.Items) != 1 || len(full.ItemValues) != 2 {
|
||||||
|
t.Fatalf("first sync returned lists=%d fields=%d items=%d values=%d, want 1/2/1/2", len(full.Lists), len(full.Fields), len(full.Items), len(full.ItemValues))
|
||||||
|
}
|
||||||
|
if full.ServerTimestamp <= 0 {
|
||||||
|
t.Fatalf("serverTimestamp = %d, want a positive time", full.ServerTimestamp)
|
||||||
|
}
|
||||||
|
if len(full.OrphanItemValues) != 0 {
|
||||||
|
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The server returns a cursor from the same snapshot as its data page.
|
||||||
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: &full.NextSyncToken}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||||
|
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
||||||
|
}
|
||||||
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(0)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
||||||
|
t.Fatalf("initial page returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The REST reads see the same data.
|
||||||
|
lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
|
if len(lists.Items) != 1 || lists.Items[0].Name != "Groceries" || lists.HasMore {
|
||||||
|
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
||||||
|
}
|
||||||
|
values := decodeBody[PageResponse[ItemValue]](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||||
|
if len(values.Items) != 2 || values.HasMore {
|
||||||
|
t.Fatalf("GET item values = %+v, want 2", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The first push is announced to the other device, and not back to its sender.
|
||||||
|
toTablet := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "tablet", nil, http.StatusOK))
|
||||||
|
if len(toTablet.Notifications) == 0 {
|
||||||
|
t.Fatal("tablet got no notifications for the phone's push")
|
||||||
|
}
|
||||||
|
for _, event := range toTablet.Notifications {
|
||||||
|
if event.DeviceIDOrigin != "phone" {
|
||||||
|
t.Fatalf("notification origin = %q, want phone", event.DeviceIDOrigin)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toPhone := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "phone", nil, http.StatusOK))
|
||||||
|
if len(toPhone.Notifications) != 0 {
|
||||||
|
t.Fatalf("phone got its own notifications back: %+v", toPhone.Notifications)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectionEndpointsPageWithStableCursors(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
api.sync("phone", SyncRequest{
|
||||||
|
Lists: []List{testList("a-list", "A", t0+10, false)},
|
||||||
|
Items: []Item{testItem("a-item", "g-list", t0+10, false)},
|
||||||
|
})
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
endpoint string
|
||||||
|
decode func(*testing.T, *httptest.ResponseRecorder) (string, string, bool)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "lists",
|
||||||
|
endpoint: "/api/lists",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[List]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first list page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fields",
|
||||||
|
endpoint: "/api/fields/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Field]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first field page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "items",
|
||||||
|
endpoint: "/api/items/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Item]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first item page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "values",
|
||||||
|
endpoint: "/api/items/g-item/values",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[ItemValue]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first value page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
firstPath := test.endpoint + "?limit=1"
|
||||||
|
firstRecorder := api.mustDo(http.MethodGet, firstPath, "", nil, http.StatusOK)
|
||||||
|
firstID, cursor, hasMore := test.decode(t, firstRecorder)
|
||||||
|
if !hasMore || cursor == "" {
|
||||||
|
t.Fatalf("first page hasMore=%v cursor=%q, want another page", hasMore, cursor)
|
||||||
|
}
|
||||||
|
secondPath := firstPath + "&cursor=" + url.QueryEscape(cursor)
|
||||||
|
secondRecorder := api.mustDo(http.MethodGet, secondPath, "", nil, http.StatusOK)
|
||||||
|
secondID, nextCursor, hasMore := test.decode(t, secondRecorder)
|
||||||
|
if secondID == firstID {
|
||||||
|
t.Fatalf("cursor repeated item %q", firstID)
|
||||||
|
}
|
||||||
|
if hasMore || nextCursor != "" {
|
||||||
|
t.Fatalf("second page hasMore=%v cursor=%q, want final page", hasMore, nextCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?limit=501", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor=not-a-cursor", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor="+url.QueryEscape(encodePageCursor(pageCursor{Kind: "items", Key: 1, ID: "x"})), "", nil, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncUsesServerChangeTokenInsteadOfClientTimestamp(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
cursor := api.currentSyncToken()
|
||||||
|
clientTimestamp := Timestamp(time.Now().UnixMilli())
|
||||||
|
|
||||||
|
response := api.sync("tablet", SyncRequest{
|
||||||
|
LastSyncTimestamp: clientTimestamp,
|
||||||
|
LastSyncToken: ptrInt64(cursor),
|
||||||
|
Lists: []List{testList("g-list", "Edited offline", t0+20, false)},
|
||||||
|
})
|
||||||
|
if len(response.Lists) != 1 || response.Lists[0].Name != "Edited offline" {
|
||||||
|
t.Fatalf("change with an old client timestamp = %+v, want the updated list", response.Lists)
|
||||||
|
}
|
||||||
|
if response.NextSyncToken <= cursor {
|
||||||
|
t.Fatalf("next sync token = %d, want greater than previous cursor %d", response.NextSyncToken, cursor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncBoundsAndPagesLargeInitialSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.mustDo(http.MethodPost, "/api/sync", "phone", map[string]any{}, http.StatusBadRequest)
|
||||||
|
lists := make([]List, 501)
|
||||||
|
for i := range lists {
|
||||||
|
id := fmt.Sprintf("list-%03d", i)
|
||||||
|
lists[i] = testList(id, id, t0+int64(i), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := api.sync("phone", SyncRequest{Lists: lists})
|
||||||
|
if len(first.Lists) != syncPageSize || !first.HasMore {
|
||||||
|
t.Fatalf("first page has lists=%d hasMore=%v, want %d and true", len(first.Lists), first.HasMore, syncPageSize)
|
||||||
|
}
|
||||||
|
if first.NextSyncToken <= 0 || first.NextSyncToken >= first.ServerChangeToken {
|
||||||
|
t.Fatalf("first page tokens are next=%d server=%d, want next before server high-water mark", first.NextSyncToken, first.ServerChangeToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
second := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(first.NextSyncToken)})
|
||||||
|
if len(second.Lists) != 1 || second.HasMore || second.NextSyncToken != second.ServerChangeToken {
|
||||||
|
t.Fatalf("second page has lists=%d hasMore=%v next=%d server=%d, want 1, false, and caught up", len(second.Lists), second.HasMore, second.NextSyncToken, second.ServerChangeToken)
|
||||||
|
}
|
||||||
|
if second.Lists[0].ID == first.Lists[len(first.Lists)-1].ID {
|
||||||
|
t.Fatalf("second page repeated list %q", second.Lists[0].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPerListMembershipScopesDataAndSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
const secondToken = "second-user-device-token"
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken(secondToken)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
firstUserLists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
|
if len(firstUserLists.Items) != 1 || firstUserLists.Items[0].ID != "g-list" {
|
||||||
|
t.Fatalf("first user lists = %+v, want g-list", firstUserLists.Items)
|
||||||
|
}
|
||||||
|
secondUserLists := decodeBody[PageResponse[List]](t, api.mustDoAs(http.MethodGet, "/api/lists", "", secondToken, nil, http.StatusOK))
|
||||||
|
if len(secondUserLists.Items) != 0 {
|
||||||
|
t.Fatalf("second user lists = %+v, want no access to the first user's list", secondUserLists.Items)
|
||||||
|
}
|
||||||
|
api.mustDoAs(http.MethodGet, "/api/items/g-item/values", "", secondToken, nil, http.StatusNotFound)
|
||||||
|
|
||||||
|
foreignCursor := int64(0)
|
||||||
|
foreignSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken,
|
||||||
|
SyncRequest{LastSyncToken: &foreignCursor}, http.StatusOK))
|
||||||
|
if len(foreignSync.Lists)+len(foreignSync.Fields)+len(foreignSync.Items)+len(foreignSync.ItemValues) != 0 {
|
||||||
|
t.Fatalf("second user's initial sync returned another list's data: %+v", foreignSync)
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("g-list", "Overwritten", t0+20, false)},
|
||||||
|
}, http.StatusNotFound)
|
||||||
|
var name string
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT name FROM lists WHERE id = 'g-list'`).Scan(&name); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if name != "Groceries" {
|
||||||
|
t.Fatalf("unauthorized sync changed list name to %q", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
newListSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("second-list", "Private", t0+30, false)},
|
||||||
|
}, http.StatusOK))
|
||||||
|
if len(newListSync.Lists) != 1 || newListSync.Lists[0].ID != "second-list" {
|
||||||
|
t.Fatalf("creator's sync response = %+v, want only second-list", newListSync.Lists)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, secondUserID, "second-list") || hasMembership(t, api.db, testUserID, "second-list") {
|
||||||
|
t.Fatal("new sync list was not private to its creator")
|
||||||
|
}
|
||||||
|
var creator bool
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT is_owner FROM list_memberships WHERE listid = 'second-list' AND user_id = $1`, secondUserID).Scan(&creator); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !creator {
|
||||||
|
t.Fatal("new sync list did not mark its creator as owner")
|
||||||
|
}
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists/second-list", "", nil, http.StatusNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMembershipBackfillPreservesCurrentAPITokenUsers(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('legacy-list', 'Legacy', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken("second-user-device-token")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, testUserID, "legacy-list") || !hasMembership(t, api.db, secondUserID, "legacy-list") {
|
||||||
|
t.Fatal("membership migration did not grant every current API-token user access to the legacy list")
|
||||||
|
}
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('new-list', 'New', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.withTx(context.Background(), func(tx pgx.Tx) error {
|
||||||
|
return addListOwner(context.Background(), tx, secondUserID, "new-list")
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if hasMembership(t, api.db, testUserID, "new-list") {
|
||||||
|
t.Fatal("re-running membership backfill exposed a creator-owned list to another token user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasMembership(t *testing.T, db *DB, userID int64, listID string) bool {
|
||||||
|
t.Helper()
|
||||||
|
member, err := hasListMembership(context.Background(), db.pool, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
push := func(name string, updatedAt int64) {
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("l1", name, updatedAt, false)}})
|
||||||
|
}
|
||||||
|
name := func() string {
|
||||||
|
return decodeBody[List](t, api.mustDo(http.MethodGet, "/api/lists/l1", "", nil, http.StatusOK)).Name
|
||||||
|
}
|
||||||
|
|
||||||
|
push("v2", t0+2000)
|
||||||
|
events := api.notifications("updated", "list", "l1")
|
||||||
|
|
||||||
|
push("v1", t0+1000)
|
||||||
|
if got := name(); got != "v2" {
|
||||||
|
t.Fatalf("name after an older write = %q, want v2", got)
|
||||||
|
}
|
||||||
|
if got := api.notifications("updated", "list", "l1"); got != events {
|
||||||
|
t.Fatalf("an ignored write added %d notification(s)", got-events)
|
||||||
|
}
|
||||||
|
|
||||||
|
push("v3", t0+3000)
|
||||||
|
if got := name(); got != "v3" {
|
||||||
|
t.Fatalf("name after a newer write = %q, want v3", got)
|
||||||
|
}
|
||||||
|
push("v3b", t0+3000)
|
||||||
|
if got := name(); got != "v3b" {
|
||||||
|
t.Fatalf("name after a write with the same timestamp = %q, want v3b", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
seedCursor := api.currentSyncToken()
|
||||||
|
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
||||||
|
|
||||||
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||||
|
if got := api.cascadeState("g-list"); got != kept {
|
||||||
|
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
||||||
|
}
|
||||||
|
if got := api.notifications("deleted", "list", "g-list"); got != 0 {
|
||||||
|
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||||
|
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
||||||
|
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
||||||
|
}
|
||||||
|
if got := api.notifications("deleted", "list", "g-list"); got != 1 {
|
||||||
|
t.Fatalf("deleted notifications = %d, want 1", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tombstone travels to other devices, but the REST list read hides it.
|
||||||
|
delta := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(seedCursor)})
|
||||||
|
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
||||||
|
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
||||||
|
}
|
||||||
|
if lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists.Items) != 0 {
|
||||||
|
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeletingTheLastFieldDeletesTheItems(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Fields: []Field{testField("g-f1", "g-list", "Name", t0+20, true)}})
|
||||||
|
if got, want := api.cascadeState("g-list"), "list=0 fields=1/2 items=0/1 values=1"; got != want {
|
||||||
|
t.Fatalf("state after deleting one of two fields = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Through REST this time. The response says the items went with it.
|
||||||
|
answer := decodeBody[map[string]any](t, api.mustDo(http.MethodDelete, "/api/fields/g-f2", "phone", nil, http.StatusOK))
|
||||||
|
if answer["cascadeItemsDeleted"] != true {
|
||||||
|
t.Fatalf("DELETE last field answer = %v, want cascadeItemsDeleted true", answer)
|
||||||
|
}
|
||||||
|
if got, want := api.cascadeState("g-list"), "list=0 fields=2/2 items=1/1 values=0"; got != want {
|
||||||
|
t.Fatalf("state after deleting the last field = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRESTAndSyncDeletesLeaveTheSameState(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "rest")
|
||||||
|
api.seedList("phone", "sync")
|
||||||
|
|
||||||
|
api.mustDo(http.MethodDelete, "/api/lists/rest-list", "phone", nil, http.StatusOK)
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("sync-list", "Groceries", time.Now().UnixMilli(), true)}})
|
||||||
|
|
||||||
|
const want = "list=1 fields=2/2 items=1/1 values=0"
|
||||||
|
if got := api.cascadeState("rest-list"); got != want {
|
||||||
|
t.Fatalf("REST delete left %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
if got := api.cascadeState("sync-list"); got != want {
|
||||||
|
t.Fatalf("sync delete left %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Item deletes agree as well.
|
||||||
|
api.seedList("phone", "ri")
|
||||||
|
api.seedList("phone", "si")
|
||||||
|
api.mustDo(http.MethodDelete, "/api/items/ri-item", "phone", nil, http.StatusOK)
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("si-item", "si-list", time.Now().UnixMilli(), true)}})
|
||||||
|
const wantItem = "list=0 fields=0/2 items=1/1 values=0"
|
||||||
|
if got := api.cascadeState("ri-list"); got != wantItem {
|
||||||
|
t.Fatalf("REST item delete left %s, want %s", got, wantItem)
|
||||||
|
}
|
||||||
|
if got := api.cascadeState("si-list"); got != wantItem {
|
||||||
|
t.Fatalf("sync item delete left %s, want %s", got, wantItem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncCannotMoveAValueOntoAnotherCell(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("g-item2", "g-list", t0+10, false)}})
|
||||||
|
|
||||||
|
// Same value id, newer timestamp, but naming another item and another field.
|
||||||
|
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item2", "g-f2", "hijacked", t0+50)}})
|
||||||
|
|
||||||
|
var itemID, fieldID, value string
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT itemid, fieldid, value FROM item_values WHERE id = 'g-v1'`).Scan(&itemID, &fieldID, &value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if itemID != "g-item" || fieldID != "g-f1" || value != "milk" {
|
||||||
|
t.Fatalf("stored value = (%s, %s, %q), want it unchanged at (g-item, g-f1, milk)", itemID, fieldID, value)
|
||||||
|
}
|
||||||
|
if got := api.notifications("listContentUpdated", "value", "g-v1"); got != 1 {
|
||||||
|
t.Fatalf("notifications for the value = %d, want only the original push", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncReportsValuesItCannotPlaceAndStubsMissingItems(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
|
||||||
|
answer := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{
|
||||||
|
testValue("lost", "g-item", "no-such-field", "x", t0+20),
|
||||||
|
testValue("late", "item-not-pushed-yet", "g-f1", "y", t0+20),
|
||||||
|
}})
|
||||||
|
if len(answer.OrphanItemValues) != 1 || answer.OrphanItemValues[0].ID != "lost" || answer.OrphanItemValues[0].Reason != "missingField" {
|
||||||
|
t.Fatalf("orphanItemValues = %+v, want only lost with reason missingField", answer.OrphanItemValues)
|
||||||
|
}
|
||||||
|
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'lost'`); got != 0 {
|
||||||
|
t.Fatal("a value for a missing field was stored")
|
||||||
|
}
|
||||||
|
// A value for an item the server has not seen yet creates the item in the
|
||||||
|
// field's list, so the value is kept.
|
||||||
|
if got := api.count(`SELECT count(*) FROM items WHERE id = 'item-not-pushed-yet' AND listid = 'g-list' AND isdeleted = 0`); got != 1 {
|
||||||
|
t.Fatalf("stub item rows = %d, want 1", got)
|
||||||
|
}
|
||||||
|
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'late'`); got != 1 {
|
||||||
|
t.Fatalf("value rows for the stubbed item = %d, want 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFailedNotificationDoesNotAbortTheMutation(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `DROP TABLE notifications`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every notification insert now fails. The sync still commits its data.
|
||||||
|
api.sync("phone", SyncRequest{Lists: []List{testList("l1", "Kept", t0+10, false)}})
|
||||||
|
if got := api.count(`SELECT count(*) FROM lists WHERE id = 'l1'`); got != 1 {
|
||||||
|
t.Fatal("the list was rolled back because its notification failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// So does a REST delete, which runs in a transaction.
|
||||||
|
api.mustDo(http.MethodDelete, "/api/lists/l1", "phone", nil, http.StatusOK)
|
||||||
|
if got := api.count(`SELECT isdeleted FROM lists WHERE id = 'l1'`); got != 1 {
|
||||||
|
t.Fatal("the REST delete was rolled back because its notification failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
write := func(value string, updatedAt int64) ItemValue {
|
||||||
|
return decodeBody[ItemValue](t, api.mustDo(http.MethodPost, "/api/items/values", "phone",
|
||||||
|
testValue("g-v1", "g-item", "g-f1", value, updatedAt), http.StatusOK))
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := write("oat milk", t0+30); got.Value != "oat milk" {
|
||||||
|
t.Fatalf("newer write answered %q, want oat milk", got.Value)
|
||||||
|
}
|
||||||
|
if got := write("stale", t0+20); got.Value != "oat milk" || int64(got.UpdatedAt) != t0+30 {
|
||||||
|
t.Fatalf("older write answered %+v, want the stored oat milk at t0+30", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
server := &Server{db: api.db}
|
||||||
|
get := func(etag string) *httptest.ResponseRecorder {
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||||
|
if etag != "" {
|
||||||
|
request.Header.Set("If-None-Match", etag)
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
server.writeWebData(recorder, request, testUserID)
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
first := get("")
|
||||||
|
if first.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET /web/data status = %d, want 200; body %s", first.Code, first.Body.String())
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Lists []struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
|
||||||
|
} `json:"lists"`
|
||||||
|
Stats map[string]int `json:"stats"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(first.Body.Bytes(), &payload); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(payload.Lists) != 1 || payload.Lists[0].EffectiveUpdatedAt != t0+10 || payload.Stats["values"] != 2 {
|
||||||
|
t.Fatalf("payload = %+v, want one list effective at t0+10 and two values", payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
etag := first.Header().Get("ETag")
|
||||||
|
if etag == "" {
|
||||||
|
t.Fatal("GET /web/data sent no ETag")
|
||||||
|
}
|
||||||
|
if again := get(etag); again.Code != http.StatusNotModified {
|
||||||
|
t.Fatalf("unchanged data status = %d, want 304", again.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item", "g-f1", "oat milk", t0+40)}})
|
||||||
|
if changed := get(etag); changed.Code != http.StatusOK {
|
||||||
|
t.Fatalf("changed data status = %d, want 200", changed.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegeneratingAnAccountsTokenReplacesTheOldOne(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
const fresh = "replacement-device-token"
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), testUserID, hashToken(fresh)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if old := api.do(http.MethodGet, "/api/lists", "", nil); old.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("old token status = %d, want 401", old.Code)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||||
|
request.Header.Set("Authorization", "Bearer "+fresh)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
api.mux.ServeHTTP(recorder, request)
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("new token status = %d, want 200", recorder.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// With login off (AUTH_DISABLED, or the login-required override) a caller with no
|
||||||
|
// session can reach token regeneration, but only as the placeholder identity 0.
|
||||||
|
// A token minted that way must not open the sync API.
|
||||||
|
func TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
|
||||||
|
answer := decodeBody[map[string]string](t, api.mustDo(http.MethodPost, "/api/auth/token/regenerate", "", nil, http.StatusOK))
|
||||||
|
minted := answer["token"]
|
||||||
|
if minted == "" {
|
||||||
|
t.Fatalf("regenerate answer = %v, want a token", answer)
|
||||||
|
}
|
||||||
|
if got := api.count(`SELECT count(*) FROM api_tokens WHERE user_id = 0`); got != 1 {
|
||||||
|
t.Fatalf("tokens stored for identity 0 = %d, want 1", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, probe := range []struct{ method, path string }{
|
||||||
|
{http.MethodGet, "/api/lists"},
|
||||||
|
{http.MethodPost, "/api/sync"},
|
||||||
|
} {
|
||||||
|
request := httptest.NewRequest(probe.method, probe.path, strings.NewReader("{}"))
|
||||||
|
request.Header.Set("Authorization", "Bearer "+minted)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
api.mux.ServeHTTP(recorder, request)
|
||||||
|
if recorder.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("%s %s with a session-less token status = %d, want 401", probe.method, probe.path, recorder.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// And it did not disturb the real account's token.
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetupClaimCanBeTakenOnceAndReopened(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
claimed, err := db.IsSetupClaimed(ctx)
|
||||||
|
if err != nil || claimed {
|
||||||
|
t.Fatalf("IsSetupClaimed() on a new database = %v, %v, want false", claimed, err)
|
||||||
|
}
|
||||||
|
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
|
||||||
|
t.Fatalf("first TryClaimSetup() = %v, %v, want true", won, err)
|
||||||
|
}
|
||||||
|
if won, err := db.TryClaimSetup(ctx); err != nil || won {
|
||||||
|
t.Fatalf("second TryClaimSetup() = %v, %v, want false", won, err)
|
||||||
|
}
|
||||||
|
if err := db.UnclaimSetup(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
|
||||||
|
t.Fatalf("TryClaimSetup() after UnclaimSetup() = %v, %v, want true", won, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -11,7 +11,7 @@ replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../shared/backend
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
||||||
golang.org/x/crypto v0.54.0 // indirect
|
golang.org/x/crypto v0.55.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -19,6 +19,6 @@ require (
|
|||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
golang.org/x/sync v0.22.0 // indirect
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
golang.org/x/text v0.40.0 // indirect
|
golang.org/x/text v0.41.0 // indirect
|
||||||
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
|
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
|
||||||
)
|
)
|
||||||
+4
-4
@@ -20,12 +20,12 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
|||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|||||||
+16
-6
@@ -86,6 +86,7 @@ type ItemValue struct {
|
|||||||
|
|
||||||
type SyncRequest struct {
|
type SyncRequest struct {
|
||||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||||
|
LastSyncToken *int64 `json:"lastSyncToken"`
|
||||||
Lists []List `json:"lists"`
|
Lists []List `json:"lists"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
Items []Item `json:"items"`
|
Items []Item `json:"items"`
|
||||||
@@ -94,12 +95,21 @@ type SyncRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SyncResponse struct {
|
type SyncResponse struct {
|
||||||
Lists []List `json:"lists"`
|
Lists []List `json:"lists"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
Items []Item `json:"items"`
|
Items []Item `json:"items"`
|
||||||
ItemValues []ItemValue `json:"itemValues"`
|
ItemValues []ItemValue `json:"itemValues"`
|
||||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||||
|
ServerChangeToken int64 `json:"serverChangeToken"`
|
||||||
|
NextSyncToken int64 `json:"nextSyncToken"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PageResponse[T any] struct {
|
||||||
|
Items []T `json:"items"`
|
||||||
|
NextCursor string `json:"nextCursor"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrphanValue struct {
|
type OrphanValue struct {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
type queryExecutor interface {
|
type queryExecutor interface {
|
||||||
@@ -41,6 +43,31 @@ func enqueueNotification(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// enqueueNotificationInTx writes a notification inside a savepoint. PostgreSQL
|
||||||
|
// aborts the whole transaction after any failing statement, so without the
|
||||||
|
// savepoint a failed notification insert would make the data mutation's commit
|
||||||
|
// fail too.
|
||||||
|
func enqueueNotificationInTx(
|
||||||
|
ctx context.Context,
|
||||||
|
tx pgx.Tx,
|
||||||
|
deviceID string,
|
||||||
|
eventType string,
|
||||||
|
entityType string,
|
||||||
|
entityID string,
|
||||||
|
listID string,
|
||||||
|
createdAt int64,
|
||||||
|
) error {
|
||||||
|
savepoint, err := tx.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := enqueueNotification(ctx, savepoint, deviceID, eventType, entityType, entityID, listID, createdAt); err != nil {
|
||||||
|
_ = savepoint.Rollback(ctx)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return savepoint.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
func nullableString(value string) any {
|
func nullableString(value string) any {
|
||||||
if value == "" {
|
if value == "" {
|
||||||
return nil
|
return nil
|
||||||
@@ -48,14 +75,12 @@ func nullableString(value string) any {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ignoreNotificationError logs a failed notification. Use it only for
|
||||||
|
// notifications written by enqueueNotificationInTx or outside a transaction.
|
||||||
func ignoreNotificationError(err error) {
|
func ignoreNotificationError(err error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Notifications are an acceleration path for clients that poll. A failed
|
// Notifications are an acceleration path for clients that poll. A failed
|
||||||
// notification must never roll back the data mutation that produced it.
|
// notification must never roll back the data mutation that produced it.
|
||||||
fmt.Printf("[notifications] enqueue failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[notifications] enqueue failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isNoRows(err error) bool {
|
|
||||||
return err == pgx.ErrNoRows
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// omniShipper mirrors the server's console lines to OmniLogger. It is always set: with no OMNILOGGER_URL or
|
||||||
|
// OMNILOGGER_INGEST_TOKEN it is disabled and ships nothing, until main hands it ProjectConfigurator's
|
||||||
|
// pushed token (see omniShipper.Follow in server.go).
|
||||||
|
var omniShipper = newOmniLoggerShipper()
|
||||||
|
|
||||||
|
// newOmniLoggerShipper returns a shipper for OmniLogger. OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are
|
||||||
|
// optional initial values; ProjectConfigurator normally supplies the token at runtime.
|
||||||
|
func newOmniLoggerShipper() *logshipper.Shipper {
|
||||||
|
return logshipper.New(logshipper.Config{
|
||||||
|
BaseURL: strings.TrimSpace(os.Getenv("OMNILOGGER_URL")),
|
||||||
|
IngestToken: strings.TrimSpace(os.Getenv("OMNILOGGER_INGEST_TOKEN")),
|
||||||
|
Service: "collabtable",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// stdoutLog and stderrLog are the Loggers behind the helpers below. Each writes its line to its console stream
|
||||||
|
// exactly as the fmt function it replaced did, and ships the line to OmniLogger at the severity the caller names.
|
||||||
|
var (
|
||||||
|
stdoutLog = newConsoleLogger(os.Stdout, omniShipper)
|
||||||
|
stderrLog = newConsoleLogger(os.Stderr, omniShipper)
|
||||||
|
)
|
||||||
|
|
||||||
|
// newConsoleLogger returns a Logger for console. NewLogger copies the standard logger's flags, and these helper
|
||||||
|
// lines have never carried a timestamp, so the flags are cleared only while the Logger is made. The standard
|
||||||
|
// logger keeps its own flags.
|
||||||
|
func newConsoleLogger(console io.Writer, shipper *logshipper.Shipper) *logshipper.Logger {
|
||||||
|
previous := log.Flags()
|
||||||
|
log.SetFlags(0)
|
||||||
|
defer log.SetFlags(previous)
|
||||||
|
return logshipper.NewLogger(console, shipper)
|
||||||
|
}
|
||||||
|
|
||||||
|
// logPrintf, logPrintln, logErrorf and logErrorln write to stdout or stderr exactly as the fmt functions
|
||||||
|
// they wrap, and also ship the line to OmniLogger when shipping is enabled, at the severity the caller
|
||||||
|
// names. The console stream is the one the helper always used, whatever the severity.
|
||||||
|
func logPrintf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logPrintln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// logLine writes msg to l's console and ships it at sev. msg keeps the newline its fmt call added, so the console
|
||||||
|
// line is the same bytes as before. Levels outside the five OmniLogger knows are reported as errors.
|
||||||
|
func logLine(l *logshipper.Logger, sev logshipper.Level, msg string) {
|
||||||
|
switch sev {
|
||||||
|
case logshipper.LevelDebug:
|
||||||
|
l.Debugf("%s", msg)
|
||||||
|
case logshipper.LevelInfo:
|
||||||
|
l.Infof("%s", msg)
|
||||||
|
case logshipper.LevelWarn:
|
||||||
|
l.Warnf("%s", msg)
|
||||||
|
case logshipper.LevelCritical:
|
||||||
|
l.Criticalf("%s", msg)
|
||||||
|
default:
|
||||||
|
l.Errorf("%s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// exitAfterFlush sends the buffered log lines to OmniLogger and then exits. Use it instead of os.Exit after a
|
||||||
|
// line that must reach OmniLogger, such as a critical startup failure, which os.Exit would otherwise lose.
|
||||||
|
func exitAfterFlush(code int) {
|
||||||
|
omniShipper.Flush()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeOmniLogger is a stand-in OmniLogger that accepts only the bearer token it was started with and
|
||||||
|
// records every entry it receives.
|
||||||
|
type fakeOmniLogger struct {
|
||||||
|
*httptest.Server
|
||||||
|
mu sync.Mutex
|
||||||
|
requests int
|
||||||
|
entries []map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFakeOmniLogger(t *testing.T, token string) *fakeOmniLogger {
|
||||||
|
t.Helper()
|
||||||
|
f := &fakeOmniLogger{}
|
||||||
|
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.requests++
|
||||||
|
f.mu.Unlock()
|
||||||
|
if r.Header.Get("Authorization") != "Bearer "+token {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var batch []map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&batch); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
f.entries = append(f.entries, batch...)
|
||||||
|
f.mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
}))
|
||||||
|
t.Cleanup(f.Close)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
// received reports how many requests arrived and the entries that were accepted.
|
||||||
|
func (f *fakeOmniLogger) received() (int, []map[string]any) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return f.requests, append([]map[string]any(nil), f.entries...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasMessage reports whether an entry for the collabtable service contains text.
|
||||||
|
func hasMessage(entries []map[string]any, text string) bool {
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && strings.Contains(message, text) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// useOmniShipper makes shipper the package's omniShipper for the rest of the test. The helper Loggers are rebuilt
|
||||||
|
// on it with their consoles discarded, since they are made once at start-up and would otherwise keep the old shipper.
|
||||||
|
func useOmniShipper(t *testing.T, shipper *logshipper.Shipper) {
|
||||||
|
t.Helper()
|
||||||
|
previous, previousOut, previousErr := omniShipper, stdoutLog, stderrLog
|
||||||
|
omniShipper = shipper
|
||||||
|
stdoutLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
stderrLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = shipper.Close()
|
||||||
|
omniShipper = previous
|
||||||
|
stdoutLog, stderrLog = previousOut, previousErr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerShipperIsNeverNilAndDisabledWithoutConfig(t *testing.T) {
|
||||||
|
if omniShipper == nil {
|
||||||
|
t.Fatal("omniShipper must never be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
if shipper == nil {
|
||||||
|
t.Fatal("shipper must never be nil; with no configuration it is simply disabled")
|
||||||
|
}
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no configuration, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
|
||||||
|
// A URL without a token is still disabled, so nothing reaches a reachable OmniLogger.
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
shipper = newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no token, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("disabled shipper sent %d requests to OmniLogger", requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogPrintfReachesOmniLogger(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "[test] hello from collabtable %d\n", 7)
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
|
||||||
|
if _, entries := sink.received(); !hasMessage(entries, "hello from collabtable 7") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line; entries: %v", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerFollowsCoreConfigPush(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "pushed-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
store := coreconfig.NewStore(coreconfig.Info{})
|
||||||
|
shipper.Follow(store)
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "before the push\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("shipper sent %d requests before ProjectConfigurator pushed a token", requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
store.Set(coreconfig.Info{OmniLoggerURL: sink.URL, OmniLoggerIngestToken: "pushed-token"})
|
||||||
|
logPrintf(logshipper.LevelInfo, "after the push\n")
|
||||||
|
_ = shipper.Close()
|
||||||
|
|
||||||
|
_, entries := sink.received()
|
||||||
|
if !hasMessage(entries, "after the push") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line after the push; entries: %v", entries)
|
||||||
|
}
|
||||||
|
if hasMessage(entries, "before the push") {
|
||||||
|
t.Fatal("a line logged before the push was shipped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine runs a converted call site: a failed
|
||||||
|
// notification is printed on stdout as before, and reaches OmniLogger once, at warn.
|
||||||
|
func TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
reader, writer, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
previousStdout := stdoutLog
|
||||||
|
stdoutLog = newConsoleLogger(writer, omniShipper)
|
||||||
|
ignoreNotificationError(errors.New("disk full"))
|
||||||
|
stdoutLog = previousStdout
|
||||||
|
_ = writer.Close()
|
||||||
|
console, _ := io.ReadAll(reader)
|
||||||
|
_ = reader.Close()
|
||||||
|
if got, want := string(console), "[notifications] enqueue failed: disk full\n"; got != want {
|
||||||
|
t.Fatalf("console output = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
_, entries := sink.received()
|
||||||
|
var levels []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && message == "[notifications] enqueue failed: disk full" {
|
||||||
|
level, _ := entry["level"].(string)
|
||||||
|
levels = append(levels, level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(levels) != 1 || levels[0] != "warn" {
|
||||||
|
t.Fatalf("OmniLogger levels for the notification line = %v, want exactly one warn (entries %v)", levels, entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errListAccessDenied = errors.New("list access denied")
|
||||||
|
errCellIdentityMismatch = errors.New("item and field belong to different lists")
|
||||||
|
)
|
||||||
|
|
||||||
|
type rowQueryer interface {
|
||||||
|
QueryRow(context.Context, string, ...any) pgx.Row
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasListMembership(ctx context.Context, queryer rowQueryer, userID int64, listID string) (bool, error) {
|
||||||
|
var member bool
|
||||||
|
err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM list_memberships WHERE listid = $1 AND user_id = $2)`, listID, userID).Scan(&member)
|
||||||
|
return member, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func authorizeList(ctx context.Context, queryer rowQueryer, userID int64, listID string, allowCreate bool) (bool, error) {
|
||||||
|
if userID <= 0 || listID == "" {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, queryer, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if member {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM lists WHERE id = $1)`, listID).Scan(&exists); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if exists || !allowCreate {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addListOwner(ctx context.Context, tx pgx.Tx, userID int64, listID string) error {
|
||||||
|
_, err := tx.Exec(ctx, `INSERT INTO list_memberships (listid, user_id, is_owner) VALUES ($1, $2, TRUE) ON CONFLICT (listid, user_id) DO NOTHING`, listID, userID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireListMembership(w http.ResponseWriter, r *http.Request, listID string) bool {
|
||||||
|
member, err := hasListMembership(r.Context(), s.db.pool, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to authorize list")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultPageSize = 200
|
||||||
|
maxPageSize = 500
|
||||||
|
)
|
||||||
|
|
||||||
|
type pageCursor struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Key int64 `json:"key"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type pageRequest struct {
|
||||||
|
Limit int
|
||||||
|
Cursor *pageCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePageRequest(r *http.Request, kind string) (pageRequest, error) {
|
||||||
|
page := pageRequest{Limit: defaultPageSize}
|
||||||
|
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
|
||||||
|
limit, err := strconv.Atoi(rawLimit)
|
||||||
|
if err != nil || limit < 1 || limit > maxPageSize {
|
||||||
|
return pageRequest{}, fmt.Errorf("limit must be between 1 and %d", maxPageSize)
|
||||||
|
}
|
||||||
|
page.Limit = limit
|
||||||
|
}
|
||||||
|
if rawCursor := r.URL.Query().Get("cursor"); rawCursor != "" {
|
||||||
|
decoded, err := base64.RawURLEncoding.DecodeString(rawCursor)
|
||||||
|
if err != nil {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
var cursor pageCursor
|
||||||
|
if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Kind != kind || cursor.ID == "" {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
page.Cursor = &cursor
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestPage(w http.ResponseWriter, r *http.Request, kind string) (pageRequest, bool) {
|
||||||
|
page, err := parsePageRequest(r, kind)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return pageRequest{}, false
|
||||||
|
}
|
||||||
|
return page, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodePageCursor(cursor pageCursor) string {
|
||||||
|
encoded, _ := json.Marshal(cursor)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPage[T any](rows pgx.Rows, request pageRequest, kind string, scan func(rowScanner) (T, error), key func(T) int64, id func(T) string) (PageResponse[T], error) {
|
||||||
|
defer rows.Close()
|
||||||
|
items := make([]T, 0, request.Limit+1)
|
||||||
|
for rows.Next() {
|
||||||
|
item, err := scan(rows)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
hasMore := len(items) > request.Limit
|
||||||
|
if hasMore {
|
||||||
|
items = items[:request.Limit]
|
||||||
|
}
|
||||||
|
response := PageResponse[T]{Items: items, HasMore: hasMore}
|
||||||
|
if hasMore {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
response.NextCursor = encodePageCursor(pageCursor{Kind: kind, Key: key(last), ID: id(last)})
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPageCursor(conditions *[]string, args *[]any, column string, direction string, cursor *pageCursor) {
|
||||||
|
if cursor == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*args = append(*args, cursor.Key)
|
||||||
|
keyParam := len(*args)
|
||||||
|
*args = append(*args, cursor.ID)
|
||||||
|
idParam := len(*args)
|
||||||
|
comparison := ">"
|
||||||
|
if direction == "desc" {
|
||||||
|
comparison = "<"
|
||||||
|
}
|
||||||
|
*conditions = append(*conditions, fmt.Sprintf("(%s %s $%d OR (%s = $%d AND id > $%d))", column, comparison, keyParam, column, keyParam, idParam))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryListPage(ctx context.Context, userID int64, includeDeleted bool, request pageRequest) (PageResponse[List], error) {
|
||||||
|
conditions := make([]string, 0, 3)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
|
if len(conditions) > 0 {
|
||||||
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
|
}
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[List]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "lists", scanList, func(item List) int64 { return int64(item.UpdatedAt) }, func(item List) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryFieldsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Field], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, `"order"`, "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + fieldColumns + ` FROM fields WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(` ORDER BY "order" ASC, id ASC LIMIT $%d`, len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Field]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "fields", scanField, func(item Field) int64 { return int64(item.Order) }, func(item Field) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryItemsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Item], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + itemColumns + ` FROM items WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Item]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "items", scanItem, func(item Item) int64 { return int64(item.UpdatedAt) }, func(item Item) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryValuesPage(ctx context.Context, userID int64, itemID string, request pageRequest) (PageResponse[ItemValue], error) {
|
||||||
|
conditions := make([]string, 0, 2)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, itemID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + valueColumns + ` FROM item_values WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat ASC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[ItemValue]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "values", scanItemValue, func(item ItemValue) int64 { return int64(item.UpdatedAt) }, func(item ItemValue) string { return item.ID })
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParsePageRequest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
query string
|
||||||
|
wantLimit int
|
||||||
|
wantCursor *pageCursor
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "defaults", wantLimit: defaultPageSize},
|
||||||
|
{name: "custom limit", query: "limit=17", wantLimit: 17},
|
||||||
|
{name: "maximum limit", query: "limit=500", wantLimit: 500},
|
||||||
|
{name: "zero limit", query: "limit=0", wantErr: true},
|
||||||
|
{name: "oversized limit", query: "limit=501", wantErr: true},
|
||||||
|
{name: "invalid limit", query: "limit=large", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "lists", Key: 123, ID: "list-1"}),
|
||||||
|
wantLimit: defaultPageSize,
|
||||||
|
wantCursor: &pageCursor{Kind: "lists", Key: 123, ID: "list-1"},
|
||||||
|
},
|
||||||
|
{name: "malformed cursor", query: "cursor=not-a-cursor", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor for another collection",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "items", Key: 123, ID: "item-1"}),
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest("GET", "/api/lists?"+test.query, nil)
|
||||||
|
got, err := parsePageRequest(request, "lists")
|
||||||
|
if (err != nil) != test.wantErr {
|
||||||
|
t.Fatalf("parsePageRequest() error = %v, wantErr %v", err, test.wantErr)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Limit != test.wantLimit {
|
||||||
|
t.Fatalf("limit = %d, want %d", got.Limit, test.wantLimit)
|
||||||
|
}
|
||||||
|
if test.wantCursor == nil {
|
||||||
|
if got.Cursor != nil {
|
||||||
|
t.Fatalf("cursor = %+v, want none", got.Cursor)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Cursor == nil || *got.Cursor != *test.wantCursor {
|
||||||
|
t.Fatalf("cursor = %+v, want %+v", got.Cursor, test.wantCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Budgets for the credential-bearing auth routes. Client IPs are resolved with
|
||||||
|
// clientIP, so they honour X-Forwarded-For only from TRUSTED_PROXIES.
|
||||||
|
const (
|
||||||
|
authIPLimit = 30
|
||||||
|
authIPWindow = time.Minute
|
||||||
|
loginFailureLimit = 10
|
||||||
|
loginFailureWindow = 15 * time.Minute
|
||||||
|
// loginBodyLimit matches the body cap AuthGuard's login handler reads.
|
||||||
|
loginBodyLimit = 128 * 1024
|
||||||
|
// rateLimiterMaxKeys bounds memory held for distinct keys.
|
||||||
|
rateLimiterMaxKeys = 10000
|
||||||
|
)
|
||||||
|
|
||||||
|
// rateLimiter counts events per key in fixed windows. It lives in process, so
|
||||||
|
// the budgets apply to one server instance.
|
||||||
|
type rateLimiter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
limit int
|
||||||
|
window time.Duration
|
||||||
|
maxKeys int
|
||||||
|
now func() time.Time
|
||||||
|
counts map[string]*rateWindow
|
||||||
|
}
|
||||||
|
|
||||||
|
type rateWindow struct {
|
||||||
|
start time.Time
|
||||||
|
count int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
|
||||||
|
return &rateLimiter{
|
||||||
|
limit: limit,
|
||||||
|
window: window,
|
||||||
|
maxKeys: rateLimiterMaxKeys,
|
||||||
|
now: time.Now,
|
||||||
|
counts: make(map[string]*rateWindow),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blocked reports whether key has spent its budget in the current window, and
|
||||||
|
// how long until that window ends.
|
||||||
|
func (l *rateLimiter) Blocked(key string) (bool, time.Duration) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
now := l.now()
|
||||||
|
window, ok := l.counts[key]
|
||||||
|
if !ok || now.Sub(window.start) >= l.window || window.count < l.limit {
|
||||||
|
return false, 0
|
||||||
|
}
|
||||||
|
return true, window.start.Add(l.window).Sub(now)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hit counts one event for key in the current window.
|
||||||
|
func (l *rateLimiter) Hit(key string) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
now := l.now()
|
||||||
|
window, ok := l.counts[key]
|
||||||
|
if !ok || now.Sub(window.start) >= l.window {
|
||||||
|
if !ok && len(l.counts) >= l.maxKeys {
|
||||||
|
l.evictLocked(now)
|
||||||
|
}
|
||||||
|
window = &rateWindow{start: now}
|
||||||
|
l.counts[key] = window
|
||||||
|
}
|
||||||
|
window.count++
|
||||||
|
}
|
||||||
|
|
||||||
|
// evictLocked drops expired windows. If every window is still live, it clears
|
||||||
|
// the map rather than let memory grow without bound. That can reset budgets
|
||||||
|
// under a flood of distinct keys, which is the cost of a bounded map.
|
||||||
|
func (l *rateLimiter) evictLocked(now time.Time) {
|
||||||
|
for key, window := range l.counts {
|
||||||
|
if now.Sub(window.start) >= l.window {
|
||||||
|
delete(l.counts, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(l.counts) >= l.maxKeys {
|
||||||
|
clear(l.counts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeRateLimited answers 429 with a Retry-After in whole seconds.
|
||||||
|
func writeRateLimited(w http.ResponseWriter, retryAfter time.Duration) {
|
||||||
|
seconds := int(math.Ceil(retryAfter.Seconds()))
|
||||||
|
if seconds < 1 {
|
||||||
|
seconds = 1
|
||||||
|
}
|
||||||
|
w.Header().Set("Retry-After", strconv.Itoa(seconds))
|
||||||
|
writeJSONError(w, http.StatusTooManyRequests, "Too many attempts. Try again later.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// authRateLimits holds the budgets for the auth routes. A fresh set is built
|
||||||
|
// per route registration, so tests start with empty counters.
|
||||||
|
type authRateLimits struct {
|
||||||
|
trusted []*net.IPNet
|
||||||
|
ip *rateLimiter
|
||||||
|
failures *rateLimiter
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAuthRateLimits(trusted []*net.IPNet) *authRateLimits {
|
||||||
|
return &authRateLimits{
|
||||||
|
trusted: trusted,
|
||||||
|
ip: newRateLimiter(authIPLimit, authIPWindow),
|
||||||
|
failures: newRateLimiter(loginFailureLimit, loginFailureWindow),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// perClient counts every request against the client's IP and refuses it once
|
||||||
|
// the IP has spent its budget. Used on setup, TOTP and token regeneration.
|
||||||
|
func (l *authRateLimits) perClient(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
key := clientIP(r, l.trusted)
|
||||||
|
if blocked, retryAfter := l.ip.Blocked(key); blocked {
|
||||||
|
writeRateLimited(w, retryAfter)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.ip.Hit(key)
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// login applies two budgets. Every attempt counts against the client IP. Failed
|
||||||
|
// attempts (401) count against the account named in the body, so guessing one
|
||||||
|
// password is capped even when the attacker rotates addresses.
|
||||||
|
func (l *authRateLimits) login(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
key := clientIP(r, l.trusted)
|
||||||
|
if blocked, retryAfter := l.ip.Blocked(key); blocked {
|
||||||
|
writeRateLimited(w, retryAfter)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.ip.Hit(key)
|
||||||
|
|
||||||
|
account := loginAccount(r)
|
||||||
|
if account != "" {
|
||||||
|
if blocked, retryAfter := l.failures.Blocked(account); blocked {
|
||||||
|
writeRateLimited(w, retryAfter)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
next.ServeHTTP(recorder, r)
|
||||||
|
if account != "" && recorder.status == http.StatusUnauthorized {
|
||||||
|
l.failures.Hit(account)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// loginAccount returns the normalised identifier from a login body and restores
|
||||||
|
// the body for the handler. It returns "" when the body names no account.
|
||||||
|
func loginAccount(r *http.Request) string {
|
||||||
|
if r.Body == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
raw, err := io.ReadAll(io.LimitReader(r.Body, loginBodyLimit))
|
||||||
|
_ = r.Body.Close()
|
||||||
|
r.Body = io.NopCloser(bytes.NewReader(raw))
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
Identifier string `json:"identifier"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(raw, &input) != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
identifier := strings.TrimSpace(input.Identifier)
|
||||||
|
if identifier == "" {
|
||||||
|
identifier = strings.TrimSpace(input.Email)
|
||||||
|
}
|
||||||
|
return strings.ToLower(identifier)
|
||||||
|
}
|
||||||
|
|
||||||
|
// statusRecorder notes the status code a handler writes, so login can tell a
|
||||||
|
// rejected password from other outcomes.
|
||||||
|
type statusRecorder struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
wroteHeader bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *statusRecorder) WriteHeader(status int) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.status = status
|
||||||
|
w.wroteHeader = true
|
||||||
|
}
|
||||||
|
w.ResponseWriter.WriteHeader(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *statusRecorder) Write(p []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
return w.ResponseWriter.Write(p)
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRateLimiterBlocksAfterLimitAndResetsWithWindow(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
|
||||||
|
limiter := newRateLimiter(3, time.Minute)
|
||||||
|
limiter.now = func() time.Time { return now }
|
||||||
|
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if blocked, _ := limiter.Blocked("a"); blocked {
|
||||||
|
t.Fatalf("hit %d blocked before the budget was spent", i+1)
|
||||||
|
}
|
||||||
|
limiter.Hit("a")
|
||||||
|
}
|
||||||
|
blocked, retryAfter := limiter.Blocked("a")
|
||||||
|
if !blocked {
|
||||||
|
t.Fatal("fourth attempt was not blocked")
|
||||||
|
}
|
||||||
|
if retryAfter != time.Minute {
|
||||||
|
t.Fatalf("retryAfter = %s, want 1m0s", retryAfter)
|
||||||
|
}
|
||||||
|
if blocked, _ := limiter.Blocked("b"); blocked {
|
||||||
|
t.Fatal("budget for one key blocked another key")
|
||||||
|
}
|
||||||
|
|
||||||
|
now = now.Add(30 * time.Second)
|
||||||
|
if blocked, retryAfter := limiter.Blocked("a"); !blocked || retryAfter != 30*time.Second {
|
||||||
|
t.Fatalf("mid-window Blocked() = %v, %s; want true, 30s", blocked, retryAfter)
|
||||||
|
}
|
||||||
|
|
||||||
|
now = now.Add(31 * time.Second)
|
||||||
|
if blocked, _ := limiter.Blocked("a"); blocked {
|
||||||
|
t.Fatal("budget did not reset when the window ended")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRateLimiterBoundsDistinctKeys(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
|
||||||
|
limiter := newRateLimiter(5, time.Minute)
|
||||||
|
limiter.maxKeys = 4
|
||||||
|
limiter.now = func() time.Time { return now }
|
||||||
|
|
||||||
|
for i := 0; i < 20; i++ {
|
||||||
|
limiter.Hit("ip-" + strconv.Itoa(i))
|
||||||
|
if len(limiter.counts) > limiter.maxKeys {
|
||||||
|
t.Fatalf("tracked %d keys, want at most %d", len(limiter.counts), limiter.maxKeys)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Once the windows have expired, a new key evicts them instead of clearing live ones.
|
||||||
|
now = now.Add(2 * time.Minute)
|
||||||
|
limiter.Hit("fresh")
|
||||||
|
if len(limiter.counts) != 1 {
|
||||||
|
t.Fatalf("after expiry tracked %d keys, want 1", len(limiter.counts))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPerClientBudgetCountsEveryRequest(t *testing.T) {
|
||||||
|
limits := newAuthRateLimits(nil)
|
||||||
|
reached := 0
|
||||||
|
handler := limits.perClient(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
reached++
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
|
||||||
|
for i := 0; i < authIPLimit+1; i++ {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/auth/totp/enable", nil))
|
||||||
|
if i < authIPLimit && recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("request %d status = %d, want 200", i+1, recorder.Code)
|
||||||
|
}
|
||||||
|
if i == authIPLimit {
|
||||||
|
if recorder.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("request %d status = %d, want 429", i+1, recorder.Code)
|
||||||
|
}
|
||||||
|
if recorder.Header().Get("Retry-After") == "" {
|
||||||
|
t.Fatal("429 response has no Retry-After header")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reached != authIPLimit {
|
||||||
|
t.Fatalf("handler ran %d times, want %d", reached, authIPLimit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loginRequest sends one login attempt from the given address and returns the status.
|
||||||
|
func loginRequest(handler http.Handler, remoteAddr, forwardedFor, body string) int {
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body))
|
||||||
|
request.RemoteAddr = remoteAddr
|
||||||
|
if forwardedFor != "" {
|
||||||
|
request.Header.Set("X-Forwarded-For", forwardedFor)
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
return recorder.Code
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginLocksAccountAfterFailuresAcrossAddresses(t *testing.T) {
|
||||||
|
limits := newAuthRateLimits(nil)
|
||||||
|
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// The handler must still see the body that the limiter read.
|
||||||
|
raw, _ := io.ReadAll(r.Body)
|
||||||
|
if !strings.Contains(string(raw), `"password":"wrong"`) {
|
||||||
|
t.Errorf("handler body = %q, want the original login body", raw)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
}))
|
||||||
|
|
||||||
|
body := `{"identifier":" Alice@Example.com ","password":"wrong"}`
|
||||||
|
for i := 0; i < loginFailureLimit; i++ {
|
||||||
|
// A new address each time, so only the per-account budget can trip.
|
||||||
|
addr := "198.51.100." + strconv.Itoa(i+1) + ":5000"
|
||||||
|
if status := loginRequest(handler, addr, "", body); status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("failed attempt %d status = %d, want 401", i+1, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if status := loginRequest(handler, "203.0.113.50:5000", "", body); status != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt after lockout status = %d, want 429", status)
|
||||||
|
}
|
||||||
|
other := `{"identifier":"bob@example.com","password":"wrong"}`
|
||||||
|
if status := loginRequest(handler, "203.0.113.51:5000", "", other); status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("different account status = %d, want 401", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginSuccessesDoNotCountAgainstAccount(t *testing.T) {
|
||||||
|
limits := newAuthRateLimits(nil)
|
||||||
|
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
body := `{"email":"carol@example.com","password":"right"}`
|
||||||
|
for i := 0; i < loginFailureLimit+5; i++ {
|
||||||
|
if status := loginRequest(handler, "198.51.100.9:5000", "", body); status != http.StatusOK {
|
||||||
|
t.Fatalf("successful attempt %d status = %d, want 200", i+1, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginIPBudgetUsesForwardedClientOnlyFromTrustedProxy(t *testing.T) {
|
||||||
|
trusted := mustTrusted(t, "10.0.0.1")
|
||||||
|
body := `{"identifier":"someone","password":"x"}`
|
||||||
|
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||||
|
|
||||||
|
// Behind the trusted proxy, each forwarded client has its own budget.
|
||||||
|
proxied := newAuthRateLimits(trusted).login(ok)
|
||||||
|
for i := 0; i < authIPLimit+10; i++ {
|
||||||
|
forwarded := "203.0.113." + strconv.Itoa(i+1)
|
||||||
|
if status := loginRequest(proxied, "10.0.0.1:5000", forwarded, body); status != http.StatusOK {
|
||||||
|
t.Fatalf("forwarded client %s status = %d, want 200", forwarded, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A caller that is not a trusted proxy cannot pick its own address.
|
||||||
|
direct := newAuthRateLimits(trusted).login(ok)
|
||||||
|
statuses := make(map[int]int)
|
||||||
|
for i := 0; i < authIPLimit+10; i++ {
|
||||||
|
forwarded := "203.0.113." + strconv.Itoa(i+1)
|
||||||
|
statuses[loginRequest(direct, "192.0.2.9:5000", forwarded, body)]++
|
||||||
|
}
|
||||||
|
if statuses[http.StatusTooManyRequests] == 0 {
|
||||||
|
t.Fatalf("forged X-Forwarded-For bypassed the IP budget: %v", statuses)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegisterRoutesLimitsLoginPerClient(t *testing.T) {
|
||||||
|
// Auth is disabled, so login answers 200 without touching the database.
|
||||||
|
server := &Server{auth: newAuthService(nil, "", false, true)}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
server.registerRoutes(mux, webFS)
|
||||||
|
|
||||||
|
body := `{"identifier":"admin","password":"x"}`
|
||||||
|
for i := 0; i < authIPLimit; i++ {
|
||||||
|
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusOK {
|
||||||
|
t.Fatalf("attempt %d status = %d, want 200", i+1, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt over the budget status = %d, want 429", status)
|
||||||
|
}
|
||||||
|
if status := loginRequest(mux, "192.0.2.21:5000", "", body); status != http.StatusOK {
|
||||||
|
t.Fatalf("other client status = %d, want 200", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithHTTPSRequiredRefusesPlainHTTP(t *testing.T) {
|
||||||
|
trusted := mustTrusted(t, "10.0.0.1")
|
||||||
|
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||||
|
handler := withHTTPSRequired(trusted, ok)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
remoteAddr string
|
||||||
|
proto string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{name: "plain request refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", want: http.StatusForbidden},
|
||||||
|
{name: "health probe stays open", path: "/health", remoteAddr: "192.0.2.9:5000", want: http.StatusOK},
|
||||||
|
{name: "trusted proxy over https allowed", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "https", want: http.StatusOK},
|
||||||
|
{name: "trusted proxy over http refused", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "http", want: http.StatusForbidden},
|
||||||
|
{name: "untrusted https claim refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", proto: "https", want: http.StatusForbidden},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||||
|
request.RemoteAddr = tc.remoteAddr
|
||||||
|
if tc.proto != "" {
|
||||||
|
request.Header.Set("X-Forwarded-Proto", tc.proto)
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
if recorder.Code != tc.want {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"maps"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Legacy user remap
|
||||||
|
// =================
|
||||||
|
//
|
||||||
|
// Before the AuthGuard migration, list_memberships.user_id and api_tokens.user_id
|
||||||
|
// held IDs from this database's own auth_users table. Identity now comes from
|
||||||
|
// AuthGuard, whose IDs come from a different sequence, so the same person signs in
|
||||||
|
// with a different ID and sees none of the lists they owned. This one-time tool
|
||||||
|
// rewrites each legacy ID to the AuthGuard ID of the same person.
|
||||||
|
//
|
||||||
|
// Stop the server first, and run the tool before any AuthGuard account signs in.
|
||||||
|
// Once accounts sign in, new rows are keyed by AuthGuard IDs, and they cannot be
|
||||||
|
// told apart from legacy rows that happen to share the same number:
|
||||||
|
//
|
||||||
|
// collabtable-server remap-users --authguard-users users.json # dry run
|
||||||
|
// collabtable-server remap-users --authguard-users users.json --apply
|
||||||
|
//
|
||||||
|
// users.json is the array GET /api/auth/users returns, copied while signed in to
|
||||||
|
// the dashboard as an AuthGuard admin. A legacy user is matched by email, or by
|
||||||
|
// username when the legacy account has no email. Anything unmatched or ambiguous
|
||||||
|
// needs a --map entry: a JSON object from legacy ID to AuthGuard ID, such as
|
||||||
|
// {"3": 12}.
|
||||||
|
//
|
||||||
|
// The plan refuses to write while a legacy user who still owns rows has no
|
||||||
|
// mapping, so no data is left keyed to an ID nobody can use. The write is one
|
||||||
|
// transaction that also records each mapping in collabtable_user_remap. A database
|
||||||
|
// that already has recorded mappings is refused, because a second pass would move
|
||||||
|
// rows that the first pass already moved.
|
||||||
|
|
||||||
|
// legacyUser is one row of the pre-migration auth_users table.
|
||||||
|
type legacyUser struct {
|
||||||
|
ID int64
|
||||||
|
Username string
|
||||||
|
Email string
|
||||||
|
}
|
||||||
|
|
||||||
|
// authGuardAccount is one entry of the AuthGuard user list the operator exports.
|
||||||
|
type authGuardAccount struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownedRows counts the rows one identity holds in the two tables the remap rewrites.
|
||||||
|
type ownedRows struct {
|
||||||
|
Memberships int64
|
||||||
|
Tokens int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o ownedRows) total() int64 {
|
||||||
|
return o.Memberships + o.Tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapEntry is the decision for one legacy user. Target is nil when the user is not
|
||||||
|
// mapped. Status says how the decision was made: matched, override, unmatched or
|
||||||
|
// ambiguous.
|
||||||
|
type remapEntry struct {
|
||||||
|
Legacy legacyUser
|
||||||
|
Target *authGuardAccount
|
||||||
|
Status string
|
||||||
|
Owned ownedRows
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapPair is one legacy ID and the AuthGuard ID its rows move to.
|
||||||
|
type remapPair struct {
|
||||||
|
Legacy int64
|
||||||
|
AuthGuard int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapPlan is what a dry run prints. Problems stop --apply; warnings do not.
|
||||||
|
type remapPlan struct {
|
||||||
|
Entries []remapEntry
|
||||||
|
Problems []string
|
||||||
|
Warnings []string
|
||||||
|
}
|
||||||
|
|
||||||
|
var errUserRemapApplied = errors.New("the legacy user remap has already been applied to this database")
|
||||||
|
|
||||||
|
// planUserRemap decides where each legacy user goes. It reads only its arguments, so
|
||||||
|
// the rules can be tested without a database. legacy must be sorted by ID. owned is
|
||||||
|
// keyed by user ID across both tables.
|
||||||
|
func planUserRemap(legacy []legacyUser, accounts []authGuardAccount, overrides map[int64]int64, owned map[int64]ownedRows, acceptOverlap bool) remapPlan {
|
||||||
|
var plan remapPlan
|
||||||
|
accountByID := make(map[int64]authGuardAccount, len(accounts))
|
||||||
|
for _, account := range accounts {
|
||||||
|
accountByID[account.ID] = account
|
||||||
|
}
|
||||||
|
legacyByID := make(map[int64]legacyUser, len(legacy))
|
||||||
|
for _, user := range legacy {
|
||||||
|
legacyByID[user.ID] = user
|
||||||
|
}
|
||||||
|
for _, id := range slices.Sorted(maps.Keys(overrides)) {
|
||||||
|
if _, ok := legacyByID[id]; !ok {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("--map names legacy user %d, which is not in auth_users", id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
claimedBy := make(map[int64]int64)
|
||||||
|
for _, user := range legacy {
|
||||||
|
entry := remapEntry{Legacy: user, Owned: owned[user.ID]}
|
||||||
|
if target, ok := overrides[user.ID]; ok {
|
||||||
|
entry.Status = "override"
|
||||||
|
if account, found := accountByID[target]; found {
|
||||||
|
entry.Target = &account
|
||||||
|
} else {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("--map sends legacy user %d to AuthGuard %d, which is not in the account list", user.ID, target))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
matches := matchAuthGuardAccounts(user, accounts)
|
||||||
|
switch len(matches) {
|
||||||
|
case 0:
|
||||||
|
entry.Status = "unmatched"
|
||||||
|
case 1:
|
||||||
|
entry.Status = "matched"
|
||||||
|
entry.Target = &matches[0]
|
||||||
|
default:
|
||||||
|
entry.Status = "ambiguous"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Target == nil && entry.Owned.total() > 0 {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("legacy user %d (%s) owns %d rows but is %s; map it with --map", user.ID, user.Username, entry.Owned.total(), entry.Status))
|
||||||
|
}
|
||||||
|
if target := entry.Target; target != nil {
|
||||||
|
if other, taken := claimedBy[target.ID]; taken {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("legacy users %d and %d both map to AuthGuard %d", other, user.ID, target.ID))
|
||||||
|
}
|
||||||
|
claimedBy[target.ID] = user.ID
|
||||||
|
if _, clash := accountByID[user.ID]; clash && target.ID != user.ID && entry.Owned.total() > 0 {
|
||||||
|
message := fmt.Sprintf("rows keyed %d may belong to AuthGuard account %d, which has that ID", user.ID, user.ID)
|
||||||
|
if acceptOverlap {
|
||||||
|
plan.Warnings = append(plan.Warnings, message)
|
||||||
|
} else {
|
||||||
|
plan.Problems = append(plan.Problems, message+"; if that account has never signed in, pass --accept-id-overlap")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
plan.Entries = append(plan.Entries, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
var unknown []int64
|
||||||
|
for _, id := range slices.Sorted(maps.Keys(owned)) {
|
||||||
|
if _, isLegacy := legacyByID[id]; !isLegacy && id != 0 {
|
||||||
|
unknown = append(unknown, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
plan.Warnings = append(plan.Warnings, fmt.Sprintf("rows keyed by IDs that are not legacy users are left unchanged: %v", unknown))
|
||||||
|
}
|
||||||
|
return plan
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchAuthGuardAccounts returns the AuthGuard accounts that identify the same person
|
||||||
|
// as a legacy user: the same email when the legacy account has one, otherwise the
|
||||||
|
// same username.
|
||||||
|
func matchAuthGuardAccounts(user legacyUser, accounts []authGuardAccount) []authGuardAccount {
|
||||||
|
var matches []authGuardAccount
|
||||||
|
for _, account := range accounts {
|
||||||
|
same := sameText(account.Username, user.Username)
|
||||||
|
if strings.TrimSpace(user.Email) != "" {
|
||||||
|
same = sameText(account.Email, user.Email)
|
||||||
|
}
|
||||||
|
if same {
|
||||||
|
matches = append(matches, account)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
// sameText compares ignoring case and surrounding spaces. An empty value never matches.
|
||||||
|
func sameText(a, b string) bool {
|
||||||
|
a, b = strings.TrimSpace(a), strings.TrimSpace(b)
|
||||||
|
return a != "" && strings.EqualFold(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadAuthGuardAccounts reads the AuthGuard account list. IDs must be positive and
|
||||||
|
// unique, since either problem would make the matching meaningless.
|
||||||
|
func loadAuthGuardAccounts(path string) ([]authGuardAccount, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read --authguard-users: %w", err)
|
||||||
|
}
|
||||||
|
var accounts []authGuardAccount
|
||||||
|
if err := json.Unmarshal(data, &accounts); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse --authguard-users: expected a JSON array of accounts: %w", err)
|
||||||
|
}
|
||||||
|
seen := make(map[int64]bool, len(accounts))
|
||||||
|
for _, account := range accounts {
|
||||||
|
if account.ID <= 0 {
|
||||||
|
return nil, fmt.Errorf("--authguard-users contains an account with ID %d", account.ID)
|
||||||
|
}
|
||||||
|
if seen[account.ID] {
|
||||||
|
return nil, fmt.Errorf("--authguard-users lists AuthGuard ID %d twice", account.ID)
|
||||||
|
}
|
||||||
|
seen[account.ID] = true
|
||||||
|
}
|
||||||
|
return accounts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadRemapOverrides reads the optional --map file, a JSON object from legacy ID to
|
||||||
|
// AuthGuard ID. An empty path means no overrides.
|
||||||
|
func loadRemapOverrides(path string) (map[int64]int64, error) {
|
||||||
|
overrides := make(map[int64]int64)
|
||||||
|
if path == "" {
|
||||||
|
return overrides, nil
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read --map: %w", err)
|
||||||
|
}
|
||||||
|
var raw map[string]int64
|
||||||
|
if err := json.Unmarshal(data, &raw); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse --map: expected a JSON object of legacy ID to AuthGuard ID: %w", err)
|
||||||
|
}
|
||||||
|
for key, target := range raw {
|
||||||
|
id, err := strconv.ParseInt(key, 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
return nil, fmt.Errorf("--map key %q is not a legacy user ID", key)
|
||||||
|
}
|
||||||
|
if target <= 0 {
|
||||||
|
return nil, fmt.Errorf("--map value for legacy user %d must be a positive AuthGuard ID", id)
|
||||||
|
}
|
||||||
|
overrides[id] = target
|
||||||
|
}
|
||||||
|
return overrides, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// legacyUsers reads the pre-migration accounts, oldest first.
|
||||||
|
func (d *DB) legacyUsers(ctx context.Context) ([]legacyUser, error) {
|
||||||
|
rows, err := d.pool.Query(ctx, `SELECT id, username, email FROM auth_users ORDER BY id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read auth_users: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
users := make([]legacyUser, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var user legacyUser
|
||||||
|
if err := rows.Scan(&user.ID, &user.Username, &user.Email); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
users = append(users, user)
|
||||||
|
}
|
||||||
|
return users, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownedRowCounts counts rows per user ID in list_memberships and api_tokens.
|
||||||
|
func (d *DB) ownedRowCounts(ctx context.Context) (map[int64]ownedRows, error) {
|
||||||
|
memberships, err := d.countRowsByUser(ctx, `SELECT user_id, count(*) FROM list_memberships GROUP BY user_id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tokens, err := d.countRowsByUser(ctx, `SELECT user_id, count(*) FROM api_tokens GROUP BY user_id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
owned := make(map[int64]ownedRows)
|
||||||
|
for id, count := range memberships {
|
||||||
|
row := owned[id]
|
||||||
|
row.Memberships = count
|
||||||
|
owned[id] = row
|
||||||
|
}
|
||||||
|
for id, count := range tokens {
|
||||||
|
row := owned[id]
|
||||||
|
row.Tokens = count
|
||||||
|
owned[id] = row
|
||||||
|
}
|
||||||
|
return owned, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) countRowsByUser(ctx context.Context, query string) (map[int64]int64, error) {
|
||||||
|
rows, err := d.pool.Query(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("count rows by user: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
counts := make(map[int64]int64)
|
||||||
|
for rows.Next() {
|
||||||
|
var id, count int64
|
||||||
|
if err := rows.Scan(&id, &count); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
counts[id] = count
|
||||||
|
}
|
||||||
|
return counts, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// userRemapAppliedCount reports how many mappings an earlier run recorded. The table
|
||||||
|
// is created on the first apply, so a database that was never remapped has none.
|
||||||
|
func (d *DB) userRemapAppliedCount(ctx context.Context) (int64, error) {
|
||||||
|
var exists bool
|
||||||
|
if err := d.pool.QueryRow(ctx, `SELECT to_regclass('collabtable_user_remap') IS NOT NULL`).Scan(&exists); err != nil {
|
||||||
|
return 0, fmt.Errorf("check collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM collabtable_user_remap`).Scan(&count); err != nil {
|
||||||
|
return 0, fmt.Errorf("count collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyUserRemap moves every row keyed by a legacy ID to its AuthGuard ID in one
|
||||||
|
// transaction, then records the mappings. The plan was read before this runs, and
|
||||||
|
// the server may have written since, so the stranded-row rule is checked again under
|
||||||
|
// the lock.
|
||||||
|
func (d *DB) applyUserRemap(ctx context.Context, pairs []remapPair) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
// SHARE ROW EXCLUSIVE blocks concurrent writers while rows move and still lets
|
||||||
|
// readers run.
|
||||||
|
if _, err := tx.Exec(ctx, `LOCK TABLE list_memberships, api_tokens IN SHARE ROW EXCLUSIVE MODE`); err != nil {
|
||||||
|
return fmt.Errorf("lock identity tables: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS collabtable_user_remap (
|
||||||
|
legacy_id BIGINT PRIMARY KEY,
|
||||||
|
authguard_id BIGINT NOT NULL,
|
||||||
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)`); err != nil {
|
||||||
|
return fmt.Errorf("create collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
var applied int64
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT count(*) FROM collabtable_user_remap`).Scan(&applied); err != nil {
|
||||||
|
return fmt.Errorf("read collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
if applied > 0 {
|
||||||
|
return errUserRemapApplied
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tx.Exec(ctx, `CREATE TEMP TABLE remap_pairs (old_id BIGINT PRIMARY KEY, new_id BIGINT NOT NULL) ON COMMIT DROP`); err != nil {
|
||||||
|
return fmt.Errorf("create remap_pairs: %w", err)
|
||||||
|
}
|
||||||
|
for _, pair := range pairs {
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO remap_pairs (old_id, new_id) VALUES ($1, $2)`, pair.Legacy, pair.AuthGuard); err != nil {
|
||||||
|
return fmt.Errorf("stage remap %d to %d: %w", pair.Legacy, pair.AuthGuard, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var stranded int64
|
||||||
|
if err := tx.QueryRow(ctx, `
|
||||||
|
SELECT count(*) FROM (
|
||||||
|
SELECT user_id FROM list_memberships
|
||||||
|
UNION ALL
|
||||||
|
SELECT user_id FROM api_tokens
|
||||||
|
) AS owned
|
||||||
|
WHERE owned.user_id IN (SELECT id FROM auth_users)
|
||||||
|
AND owned.user_id NOT IN (SELECT old_id FROM remap_pairs)`).Scan(&stranded); err != nil {
|
||||||
|
return fmt.Errorf("check for unmapped legacy rows: %w", err)
|
||||||
|
}
|
||||||
|
if stranded > 0 {
|
||||||
|
return fmt.Errorf("%d rows are keyed by legacy IDs with no mapping", stranded)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows leave list_memberships in one statement and return in the next. If the
|
||||||
|
// two were one statement, an insert could conflict with a row that the same
|
||||||
|
// statement is deleting, when a legacy ID maps onto another legacy ID.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
CREATE TEMP TABLE moved_memberships (
|
||||||
|
listid TEXT NOT NULL,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
is_owner BOOLEAN NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
) ON COMMIT DROP`); err != nil {
|
||||||
|
return fmt.Errorf("create moved_memberships: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
WITH moved AS (
|
||||||
|
DELETE FROM list_memberships AS m
|
||||||
|
USING remap_pairs AS p
|
||||||
|
WHERE m.user_id = p.old_id
|
||||||
|
RETURNING m.listid, p.new_id AS user_id, m.is_owner, m.created_at
|
||||||
|
)
|
||||||
|
INSERT INTO moved_memberships (listid, user_id, is_owner, created_at)
|
||||||
|
SELECT listid, user_id, is_owner, created_at FROM moved`); err != nil {
|
||||||
|
return fmt.Errorf("move memberships: %w", err)
|
||||||
|
}
|
||||||
|
// An AuthGuard account that already holds a row on the same list keeps that row.
|
||||||
|
// Ownership from either side is kept.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO list_memberships (listid, user_id, is_owner, created_at)
|
||||||
|
SELECT listid, user_id, is_owner, created_at FROM moved_memberships
|
||||||
|
ON CONFLICT (listid, user_id) DO UPDATE SET is_owner = list_memberships.is_owner OR EXCLUDED.is_owner`); err != nil {
|
||||||
|
return fmt.Errorf("restore memberships: %w", err)
|
||||||
|
}
|
||||||
|
// Tokens move with their owner. Sync resolves a device token to the same
|
||||||
|
// identity its memberships use, so the two must change together.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
UPDATE api_tokens AS t
|
||||||
|
SET user_id = p.new_id
|
||||||
|
FROM remap_pairs AS p
|
||||||
|
WHERE t.user_id = p.old_id`); err != nil {
|
||||||
|
return fmt.Errorf("move API tokens: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO collabtable_user_remap (legacy_id, authguard_id)
|
||||||
|
SELECT old_id, new_id FROM remap_pairs`); err != nil {
|
||||||
|
return fmt.Errorf("record remap: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runRemapUsers implements `collabtable-server remap-users` and returns the exit code.
|
||||||
|
func runRemapUsers(args []string, out io.Writer) int {
|
||||||
|
flags := flag.NewFlagSet("remap-users", flag.ContinueOnError)
|
||||||
|
accountsPath := flags.String("authguard-users", "", "JSON array of AuthGuard accounts, as returned by GET /api/auth/users (required)")
|
||||||
|
overridesPath := flags.String("map", "", `optional JSON object from legacy ID to AuthGuard ID, for example {"3": 12}`)
|
||||||
|
apply := flags.Bool("apply", false, "write the remap; without it only the plan is printed")
|
||||||
|
acceptOverlap := flags.Bool("accept-id-overlap", false, "acknowledge the ID-overlap problems after checking that those AuthGuard accounts have never signed in")
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if *accountsPath == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: --authguard-users is required")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
accounts, err := loadAuthGuardAccounts(*accountsPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
overrides, err := loadRemapOverrides(*overridesPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if connectionString == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: DATABASE_URL environment variable is required")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
database, err := connectDB(ctx, connectionString)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: connect: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
defer database.close()
|
||||||
|
|
||||||
|
applied, err := database.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if applied > 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v (%d mappings recorded); nothing to do\n", errUserRemapApplied, applied)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
legacy, err := database.legacyUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
owned, err := database.ownedRowCounts(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, overrides, owned, *acceptOverlap)
|
||||||
|
printRemapPlan(out, plan)
|
||||||
|
if len(plan.Problems) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: not writing; resolve the problems above first")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !*apply {
|
||||||
|
fmt.Fprintln(out, "dry run: nothing written. Re-run with --apply to write the remap.")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var pairs []remapPair
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
if entry.Target != nil {
|
||||||
|
pairs = append(pairs, remapPair{Legacy: entry.Legacy.ID, AuthGuard: entry.Target.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(pairs) == 0 {
|
||||||
|
fmt.Fprintln(out, "no legacy users are mapped; nothing to write")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if err := database.applyUserRemap(ctx, pairs); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v; nothing was written\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(out, "remapped %d legacy users\n", len(pairs))
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// printRemapPlan writes the plan as a table, then its warnings and problems.
|
||||||
|
func printRemapPlan(out io.Writer, plan remapPlan) {
|
||||||
|
table := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(table, "LEGACY\tUSERNAME\tEMAIL\tAUTHGUARD\tAUTHGUARD USERNAME\tSTATUS\tMEMBERSHIPS\tTOKENS")
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
target, targetName := "-", "-"
|
||||||
|
if entry.Target != nil {
|
||||||
|
target = strconv.FormatInt(entry.Target.ID, 10)
|
||||||
|
targetName = entry.Target.Username
|
||||||
|
}
|
||||||
|
fmt.Fprintf(table, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%d\n",
|
||||||
|
entry.Legacy.ID, entry.Legacy.Username, entry.Legacy.Email, target, targetName,
|
||||||
|
entry.Status, entry.Owned.Memberships, entry.Owned.Tokens)
|
||||||
|
}
|
||||||
|
_ = table.Flush()
|
||||||
|
for _, warning := range plan.Warnings {
|
||||||
|
fmt.Fprintf(out, "warning: %s\n", warning)
|
||||||
|
}
|
||||||
|
for _, problem := range plan.Problems {
|
||||||
|
fmt.Fprintf(out, "problem: %s\n", problem)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"maps"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPlanUserRemapMatchesByEmailThenUsername(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice", Email: "Alice@Example.com"},
|
||||||
|
{ID: 2, Username: "bob"},
|
||||||
|
{ID: 3, Username: "carol", Email: "carol@old.example"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 10, Username: "alice2", Email: "alice@example.com"},
|
||||||
|
{ID: 11, Username: "Bob", Email: "bob@example.com"},
|
||||||
|
{ID: 12, Username: "carol", Email: "carol@new.example"},
|
||||||
|
}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, nil, nil, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("unexpected problems: %v", plan.Problems)
|
||||||
|
}
|
||||||
|
want := []struct {
|
||||||
|
status string
|
||||||
|
target int64
|
||||||
|
}{{"matched", 10}, {"matched", 11}, {"unmatched", 0}}
|
||||||
|
for i, entry := range plan.Entries {
|
||||||
|
if entry.Status != want[i].status || entryTargetID(entry) != want[i].target {
|
||||||
|
t.Fatalf("legacy %d: got status %q target %d, want %q target %d",
|
||||||
|
entry.Legacy.ID, entry.Status, entryTargetID(entry), want[i].status, want[i].target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapBlocksAmbiguousOwners(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 4, Username: "dave", Email: "dave@example.com"},
|
||||||
|
{ID: 5, Username: "erin"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 20, Username: "dave-a", Email: "dave@example.com"},
|
||||||
|
{ID: 21, Username: "dave-b", Email: "dave@example.com"},
|
||||||
|
}
|
||||||
|
owned := map[int64]ownedRows{4: {Memberships: 2}}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, nil, owned, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 1 || !strings.Contains(plan.Problems[0], "ambiguous") {
|
||||||
|
t.Fatalf("want one ambiguous-owner problem, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
if plan.Entries[1].Status != "unmatched" {
|
||||||
|
t.Fatalf("erin owns nothing, so an unmatched user must not block; got %+v", plan.Entries[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapGuardsIDOverlap(t *testing.T) {
|
||||||
|
// Each legacy user's new ID is the other's legacy ID, so rows keyed 1 and 2
|
||||||
|
// could belong to either person.
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice", Email: "alice@example.com"},
|
||||||
|
{ID: 2, Username: "bob", Email: "bob@example.com"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 1, Username: "bob", Email: "bob@example.com"},
|
||||||
|
{ID: 2, Username: "alice", Email: "alice@example.com"},
|
||||||
|
}
|
||||||
|
owned := map[int64]ownedRows{1: {Memberships: 1}, 2: {Tokens: 1}}
|
||||||
|
|
||||||
|
blocked := planUserRemap(legacy, accounts, nil, owned, false)
|
||||||
|
if len(blocked.Problems) != 2 || !strings.Contains(blocked.Problems[0], "--accept-id-overlap") {
|
||||||
|
t.Fatalf("want two overlap problems without acceptance, got %v", blocked.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
accepted := planUserRemap(legacy, accounts, nil, owned, true)
|
||||||
|
if len(accepted.Problems) != 0 || len(accepted.Warnings) != 2 {
|
||||||
|
t.Fatalf("want two warnings and no problems with acceptance, got problems %v warnings %v",
|
||||||
|
accepted.Problems, accepted.Warnings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapRejectsDuplicateTargets(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice"},
|
||||||
|
{ID: 2, Username: "bob"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{{ID: 9, Username: "shared"}}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, map[int64]int64{1: 9, 2: 9}, nil, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 1 || !strings.Contains(plan.Problems[0], "both map to AuthGuard 9") {
|
||||||
|
t.Fatalf("want one duplicate-target problem, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapOverrides(t *testing.T) {
|
||||||
|
legacy := []legacyUser{{ID: 3, Username: "carol", Email: "carol@old.example"}}
|
||||||
|
accounts := []authGuardAccount{{ID: 12, Username: "carol", Email: "carol@new.example"}}
|
||||||
|
owned := map[int64]ownedRows{3: {Memberships: 1}}
|
||||||
|
|
||||||
|
mapped := planUserRemap(legacy, accounts, map[int64]int64{3: 12}, owned, false)
|
||||||
|
if len(mapped.Problems) != 0 || mapped.Entries[0].Status != "override" || entryTargetID(mapped.Entries[0]) != 12 {
|
||||||
|
t.Fatalf("override should map 3 to 12 without problems, got %+v problems %v", mapped.Entries, mapped.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
missingAccount := planUserRemap(legacy, accounts, map[int64]int64{3: 99}, owned, false)
|
||||||
|
if len(missingAccount.Problems) == 0 || !strings.Contains(missingAccount.Problems[0], "not in the account list") {
|
||||||
|
t.Fatalf("override to an unknown AuthGuard ID must be a problem, got %v", missingAccount.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
unknownLegacy := planUserRemap(legacy, accounts, map[int64]int64{8: 12}, nil, false)
|
||||||
|
if len(unknownLegacy.Problems) != 1 || !strings.Contains(unknownLegacy.Problems[0], "not in auth_users") {
|
||||||
|
t.Fatalf("override naming an unknown legacy user must be a problem, got %v", unknownLegacy.Problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapReportsUnknownOwnersWithoutBlocking(t *testing.T) {
|
||||||
|
owned := map[int64]ownedRows{0: {Memberships: 1}, 77: {Tokens: 1}}
|
||||||
|
|
||||||
|
plan := planUserRemap(nil, nil, nil, owned, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("unknown owners must not block the remap, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
want := "rows keyed by IDs that are not legacy users are left unchanged: [77]"
|
||||||
|
if len(plan.Warnings) != 1 || plan.Warnings[0] != want {
|
||||||
|
t.Fatalf("got warnings %v, want [%q]", plan.Warnings, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyUserRemapMovesIdentitiesAndRefusesSecondRun seeds a swap (1 to 2 and 2 to 1,
|
||||||
|
// which only works if every row moves in one pass), a merge onto an AuthGuard account
|
||||||
|
// that already has a row, and a device token that must follow its owner.
|
||||||
|
func TestApplyUserRemapMovesIdentitiesAndRefusesSecondRun(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedRemapFixture(t, db)
|
||||||
|
|
||||||
|
legacy, err := db.legacyUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
owned, err := db.ownedRowCounts(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
plan := planUserRemap(legacy, remapFixtureAccounts(), nil, owned, true)
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("fixture plan blocked: %v", plan.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.applyUserRemap(ctx, remapPairsFromPlan(plan)); err != nil {
|
||||||
|
t.Fatalf("apply: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertMembershipOwners(t, db, "l-alice", map[int64]bool{2: true})
|
||||||
|
assertMembershipOwners(t, db, "l-bob", map[int64]bool{1: true})
|
||||||
|
assertMembershipOwners(t, db, "l-shared", map[int64]bool{1: true, 2: false})
|
||||||
|
assertMembershipOwners(t, db, "l-merge", map[int64]bool{7: true})
|
||||||
|
assertTokenOwner(t, db, "alice-device", 2)
|
||||||
|
assertTokenOwner(t, db, "bob-device", 1)
|
||||||
|
|
||||||
|
var leftover int64
|
||||||
|
if err := db.pool.QueryRow(ctx, `SELECT count(*) FROM list_memberships WHERE user_id = 3`).Scan(&leftover); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if leftover != 0 {
|
||||||
|
t.Fatalf("%d membership rows still keyed by legacy ID 3", leftover)
|
||||||
|
}
|
||||||
|
|
||||||
|
recorded, err := db.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorded != 3 {
|
||||||
|
t.Fatalf("recorded %d mappings, want 3", recorded)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.applyUserRemap(ctx, remapPairsFromPlan(plan))
|
||||||
|
if !errors.Is(err, errUserRemapApplied) {
|
||||||
|
t.Fatalf("second apply: got %v, want errUserRemapApplied", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyUserRemapRollsBackWhenAnOwnerIsUnmapped checks that a write which would
|
||||||
|
// strand rows writes nothing at all.
|
||||||
|
func TestApplyUserRemapRollsBackWhenAnOwnerIsUnmapped(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedRemapFixture(t, db)
|
||||||
|
|
||||||
|
err := db.applyUserRemap(ctx, []remapPair{{Legacy: 1, AuthGuard: 2}})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "no mapping") {
|
||||||
|
t.Fatalf("apply with unmapped owners: got %v, want a no-mapping error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertMembershipOwners(t, db, "l-bob", map[int64]bool{2: true})
|
||||||
|
assertTokenOwner(t, db, "bob-device", 2)
|
||||||
|
recorded, err := db.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorded != 0 {
|
||||||
|
t.Fatalf("failed apply recorded %d mappings", recorded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func entryTargetID(entry remapEntry) int64 {
|
||||||
|
if entry.Target == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return entry.Target.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func remapPairsFromPlan(plan remapPlan) []remapPair {
|
||||||
|
var pairs []remapPair
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
if entry.Target != nil {
|
||||||
|
pairs = append(pairs, remapPair{Legacy: entry.Legacy.ID, AuthGuard: entry.Target.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pairs
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapFixtureAccounts are the AuthGuard accounts for the fixture below. Legacy 1 and 2
|
||||||
|
// swap IDs, and legacy 3 keeps its email.
|
||||||
|
func remapFixtureAccounts() []authGuardAccount {
|
||||||
|
return []authGuardAccount{
|
||||||
|
{ID: 1, Username: "bob", Email: "bob@example.com"},
|
||||||
|
{ID: 2, Username: "alice", Email: "alice@example.com"},
|
||||||
|
{ID: 7, Username: "carol", Email: "carol@example.com"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedRemapFixture(t *testing.T, db *DB) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
exec := func(query string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := db.pool.Exec(ctx, query, args...); err != nil {
|
||||||
|
t.Fatalf("seed %q: %v", query, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exec(`INSERT INTO auth_users (id, username, email, password_hash) VALUES
|
||||||
|
(1, 'alice', 'alice@example.com', 'x'),
|
||||||
|
(2, 'bob', 'bob@example.com', 'x'),
|
||||||
|
(3, 'carol', 'carol@example.com', 'x')`)
|
||||||
|
for _, id := range []string{"l-alice", "l-bob", "l-shared", "l-merge"} {
|
||||||
|
exec(`INSERT INTO lists (id, name, createdat, updatedat) VALUES ($1, $1, $2, $2)`, id, t0)
|
||||||
|
}
|
||||||
|
exec(`INSERT INTO list_memberships (listid, user_id, is_owner) VALUES
|
||||||
|
('l-alice', 1, TRUE),
|
||||||
|
('l-bob', 2, TRUE),
|
||||||
|
('l-shared', 1, FALSE),
|
||||||
|
('l-shared', 2, TRUE),
|
||||||
|
('l-merge', 3, FALSE),
|
||||||
|
('l-merge', 7, TRUE)`)
|
||||||
|
exec(`INSERT INTO api_tokens (user_id, token_hash) VALUES (1, $1), (2, $2)`,
|
||||||
|
hashToken("alice-device"), hashToken("bob-device"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertMembershipOwners(t *testing.T, db *DB, listID string, want map[int64]bool) {
|
||||||
|
t.Helper()
|
||||||
|
rows, err := db.pool.Query(context.Background(), `SELECT user_id, is_owner FROM list_memberships WHERE listid = $1`, listID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
got := make(map[int64]bool)
|
||||||
|
for rows.Next() {
|
||||||
|
var userID int64
|
||||||
|
var owner bool
|
||||||
|
if err := rows.Scan(&userID, &owner); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got[userID] = owner
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !maps.Equal(got, want) {
|
||||||
|
t.Fatalf("%s memberships: got %v, want %v", listID, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertTokenOwner(t *testing.T, db *DB, device string, want int64) {
|
||||||
|
t.Helper()
|
||||||
|
got, err := db.getAPITokenUserID(context.Background(), hashToken(device))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("%s token owner: got %d, want %d", device, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-2
@@ -2,10 +2,35 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRegisterRoutes(t *testing.T) {
|
func TestRegisterRoutes(t *testing.T) {
|
||||||
server := &Server{auth: newAuthService(nil, "", false, false)}
|
// Auth is disabled and there is no database, so these checks only touch
|
||||||
server.registerRoutes(http.NewServeMux(), webFS)
|
// routes that answer before any query runs.
|
||||||
|
server := &Server{auth: newAuthService(nil, "", false, true)}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
server.registerRoutes(mux, webFS)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
method string
|
||||||
|
path string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{name: "health is public", method: http.MethodGet, path: "/health", want: http.StatusOK},
|
||||||
|
{name: "sync needs a bearer token", method: http.MethodPost, path: "/api/sync", want: http.StatusUnauthorized},
|
||||||
|
{name: "lists need a bearer token", method: http.MethodGet, path: "/api/lists", want: http.StatusUnauthorized},
|
||||||
|
{name: "managed users pass the role gate when auth is disabled", method: http.MethodGet, path: "/api/auth/users", want: http.StatusOK},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil))
|
||||||
|
if recorder.Code != tc.want {
|
||||||
|
t.Fatalf("%s %s status = %d, want %d", tc.method, tc.path, recorder.Code, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Executable
BIN
Binary file not shown.
+214
-49
@@ -1,12 +1,15 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"compress/gzip"
|
||||||
"context"
|
"context"
|
||||||
"embed"
|
"embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
@@ -17,8 +20,8 @@ import (
|
|||||||
_ "github.com/joho/godotenv/autoload"
|
_ "github.com/joho/godotenv/autoload"
|
||||||
|
|
||||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
|
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -35,25 +38,52 @@ type Server struct {
|
|||||||
startTime time.Time
|
startTime time.Time
|
||||||
internalServiceSecret string
|
internalServiceSecret string
|
||||||
coreConfig *coreconfig.Store
|
coreConfig *coreconfig.Store
|
||||||
carrierNode *carriernodeclient.Client
|
syncSlots chan struct{}
|
||||||
|
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
|
||||||
|
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
|
||||||
|
trustedProxies []*net.IPNet
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Request body limits per route. Sync pushes can carry many rows at once, so
|
||||||
|
// they keep the larger limit; single-entity writes get the smaller one.
|
||||||
|
const (
|
||||||
|
jsonBodyLimit = 2 << 20
|
||||||
|
syncBodyLimit = 50 << 20
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
|
||||||
|
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
|
||||||
|
}
|
||||||
|
log.SetOutput(io.MultiWriter(os.Stderr, omniShipper.Writer()))
|
||||||
port := envOrDefault("PORT", "8080")
|
port := envOrDefault("PORT", "8080")
|
||||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
if connectionString == "" {
|
if connectionString == "" {
|
||||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
logErrorln(logshipper.LevelCritical, "DATABASE_URL environment variable is required")
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
||||||
|
|
||||||
|
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
||||||
|
if err != nil {
|
||||||
|
logErrorln(logshipper.LevelCritical, err)
|
||||||
|
exitAfterFlush(1)
|
||||||
|
}
|
||||||
|
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
||||||
|
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
||||||
|
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
||||||
|
if production && len(trustedProxies) == 0 {
|
||||||
|
logErrorln(logshipper.LevelCritical, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
||||||
|
exitAfterFlush(1)
|
||||||
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
database, err := connectWithRetry(ctx, connectionString)
|
database, err := connectWithRetry(ctx, connectionString)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "database initialization failed: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
defer database.close()
|
defer database.close()
|
||||||
go database.pruneExpiredSessions(ctx)
|
go database.pruneExpiredSessions(ctx)
|
||||||
@@ -71,11 +101,11 @@ func main() {
|
|||||||
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
||||||
switch {
|
switch {
|
||||||
case authDisabled:
|
case authDisabled:
|
||||||
fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
logPrintln(logshipper.LevelWarn, "auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
||||||
case authGuardURL != "":
|
case authGuardURL != "":
|
||||||
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
|
logPrintf(logshipper.LevelInfo, "auth: AuthGuard at %s\n", authGuardURL)
|
||||||
default:
|
default:
|
||||||
fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
logPrintln(logshipper.LevelWarn, "auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
||||||
}
|
}
|
||||||
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
||||||
|
|
||||||
@@ -88,47 +118,53 @@ func main() {
|
|||||||
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
||||||
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
||||||
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
||||||
|
omniShipper.Follow(coreConfig)
|
||||||
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
||||||
if info.AuthGuardURL != "" {
|
if info.AuthGuardURL != "" {
|
||||||
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string {
|
|
||||||
return coreConfig.CarrierNodeURL()
|
|
||||||
})
|
|
||||||
|
|
||||||
server := &Server{
|
server := &Server{
|
||||||
db: database,
|
db: database,
|
||||||
auth: auth,
|
auth: auth,
|
||||||
startTime: time.Now(),
|
startTime: time.Now(),
|
||||||
internalServiceSecret: internalServiceSecret,
|
internalServiceSecret: internalServiceSecret,
|
||||||
coreConfig: coreConfig,
|
coreConfig: coreConfig,
|
||||||
carrierNode: carrierNode,
|
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||||
|
trustedProxies: trustedProxies,
|
||||||
}
|
}
|
||||||
|
|
||||||
webRoot, err := fs.Sub(webFS, "web")
|
webRoot, err := fs.Sub(webFS, "web")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "embedded web assets missing: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
server.registerRoutes(mux, webRoot)
|
server.registerRoutes(mux, webRoot)
|
||||||
|
|
||||||
|
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
||||||
|
if production {
|
||||||
|
handler = withHTTPSRequired(trustedProxies, handler)
|
||||||
|
logPrintln(logshipper.LevelInfo, "PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
||||||
|
} else {
|
||||||
|
logErrorln(logshipper.LevelWarn, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
||||||
|
}
|
||||||
|
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
Addr: ":" + port,
|
Addr: ":" + port,
|
||||||
Handler: withCORS(mux),
|
Handler: handler,
|
||||||
ReadHeaderTimeout: 10 * time.Second,
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
ReadTimeout: 60 * time.Second,
|
ReadTimeout: 60 * time.Second,
|
||||||
WriteTimeout: 60 * time.Second,
|
WriteTimeout: 60 * time.Second,
|
||||||
IdleTimeout: 120 * time.Second,
|
IdleTimeout: 120 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
logPrintf(logshipper.LevelInfo, "CollabTable Go server listening on :%s\n", port)
|
||||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
logPrintf(logshipper.LevelInfo, "Database: PostgreSQL (pgx)\n")
|
||||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "server error: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +176,7 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||||
if attempt > 1 {
|
if attempt > 1 {
|
||||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
logPrintf(logshipper.LevelInfo, "[DB] Connected after %d attempt(s)\n", attempt)
|
||||||
}
|
}
|
||||||
return database, nil
|
return database, nil
|
||||||
} else {
|
} else {
|
||||||
@@ -149,11 +185,11 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
logErrorf(logshipper.LevelWarn, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||||
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval)
|
logPrintf(logshipper.LevelWarn, "[DB] Retrying in %s...\n", retryOptions.Interval)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
@@ -163,6 +199,10 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||||
|
// Budgets for setup, login, TOTP and token regeneration, keyed by client IP
|
||||||
|
// (and by account for failed logins). See ratelimit.go.
|
||||||
|
limits := newAuthRateLimits(s.trustedProxies)
|
||||||
|
|
||||||
// Health and auth bootstrap routes are intentionally public.
|
// Health and auth bootstrap routes are intentionally public.
|
||||||
mux.HandleFunc("GET /health", s.handleHealth)
|
mux.HandleFunc("GET /health", s.handleHealth)
|
||||||
mux.HandleFunc("GET /api/info", s.handleInfo)
|
mux.HandleFunc("GET /api/info", s.handleInfo)
|
||||||
@@ -170,22 +210,23 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
|||||||
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
|
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
|
||||||
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
|
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
|
||||||
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
|
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
|
||||||
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
|
mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup)))
|
||||||
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
|
mux.Handle("POST /api/auth/login", limits.login(http.HandlerFunc(s.auth.Login)))
|
||||||
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
|
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
|
||||||
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
|
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
|
||||||
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
|
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
|
||||||
mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers)))
|
// Managed-user routes check the caller's role here, not only in AuthGuard.
|
||||||
mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers)))
|
||||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
||||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||||
mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))
|
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
||||||
mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))
|
mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))))
|
||||||
mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))
|
mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))))
|
||||||
mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))
|
mux.Handle("POST /api/auth/totp/enable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify))))
|
||||||
|
mux.Handle("POST /api/auth/totp/disable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable))))
|
||||||
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
|
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
|
||||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate)))
|
mux.Handle("POST /api/auth/token/regenerate", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate))))
|
||||||
|
|
||||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||||
// user's devices. This is deliberately separate from browser sessions.
|
// user's devices. This is deliberately separate from browser sessions.
|
||||||
@@ -237,8 +278,7 @@ func (s *Server) handleInfo(w http.ResponseWriter, _ *http.Request) {
|
|||||||
"ok": true,
|
"ok": true,
|
||||||
"name": "CollabTable",
|
"name": "CollabTable",
|
||||||
"tabs": []map[string]string{
|
"tabs": []map[string]string{
|
||||||
{"label": "Overview", "token": "/"},
|
{"key": "overview", "label": "Overview", "token": "/"},
|
||||||
{"label": "About", "token": "/about"},
|
|
||||||
},
|
},
|
||||||
"mountTypes": []string{},
|
"mountTypes": []string{},
|
||||||
})
|
})
|
||||||
@@ -251,12 +291,24 @@ func envOrDefault(name, fallback string) string {
|
|||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
func decodeJSON(r *http.Request, target any) error {
|
func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
|
||||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
return decodeJSONLimit(w, r, target, jsonBodyLimit)
|
||||||
if err := decoder.Decode(target); err != nil {
|
}
|
||||||
return err
|
|
||||||
|
// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails
|
||||||
|
// with *http.MaxBytesError, which writeDecodeError turns into 413.
|
||||||
|
func decodeJSONLimit(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
|
||||||
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
|
||||||
|
return decoder.Decode(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDecodeError(w http.ResponseWriter, err error, message string) {
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
writeJSONError(w, http.StatusRequestEntityTooLarge, "Request body too large")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return nil
|
writeJSONError(w, http.StatusBadRequest, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
@@ -272,17 +324,42 @@ func writeJSONError(w http.ResponseWriter, status int, message string) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func withCORS(next http.Handler) http.Handler {
|
// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser
|
||||||
|
// origins that may call the API cross-origin with credentials. It is empty by
|
||||||
|
// default: the dashboard is same-origin and needs no CORS headers.
|
||||||
|
func allowedOriginsFromEnv() []string {
|
||||||
|
var origins []string
|
||||||
|
for _, origin := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") {
|
||||||
|
if origin = strings.TrimSpace(origin); origin != "" {
|
||||||
|
origins = append(origins, origin)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return origins
|
||||||
|
}
|
||||||
|
|
||||||
|
// withCORS sends CORS headers only for origins in allowedOrigins. Any other
|
||||||
|
// origin gets no Access-Control-Allow-Origin and no credentials header, so a
|
||||||
|
// browser refuses its cross-origin reads.
|
||||||
|
func withCORS(allowedOrigins []string, next http.Handler) http.Handler {
|
||||||
|
allowed := make(map[string]bool, len(allowedOrigins))
|
||||||
|
for _, origin := range allowedOrigins {
|
||||||
|
allowed[origin] = true
|
||||||
|
}
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
origin := r.Header.Get("Origin")
|
origin := r.Header.Get("Origin")
|
||||||
if origin != "" {
|
if origin != "" {
|
||||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
||||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
||||||
w.Header().Add("Vary", "Origin")
|
w.Header().Add("Vary", "Origin")
|
||||||
}
|
}
|
||||||
|
permitted := origin != "" && allowed[origin]
|
||||||
|
if permitted {
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||||
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||||
|
}
|
||||||
if r.Method == http.MethodOptions {
|
if r.Method == http.MethodOptions {
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
if permitted {
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||||
|
}
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -290,6 +367,82 @@ func withCORS(next http.Handler) http.Handler {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// withSecurityHeaders sets headers that stop the dashboard and API from being
|
||||||
|
// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the
|
||||||
|
// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set
|
||||||
|
// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security.
|
||||||
|
func withSecurityHeaders(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
headers := w.Header()
|
||||||
|
headers.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
headers.Set("X-Frame-Options", "DENY")
|
||||||
|
headers.Set("Content-Security-Policy", "frame-ancestors 'none'")
|
||||||
|
headers.Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// withHTTPSRequired is the PRODUCTION=true profile: a request that did not
|
||||||
|
// arrive over TLS, directly or through a trusted proxy, gets 403. The health
|
||||||
|
// probe is exempt so local container checks keep working.
|
||||||
|
func withHTTPSRequired(trusted []*net.IPNet, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/health" || requestIsHTTPS(r, trusted) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSONError(w, http.StatusForbidden, "HTTPS is required on this server")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// gzipResponseWriter compresses a response body when the client accepts gzip.
|
||||||
|
// Responses that carry no body (204, 304) are passed through unchanged.
|
||||||
|
type gzipResponseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
gzipWriter *gzip.Writer
|
||||||
|
wroteHeader bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *gzipResponseWriter) WriteHeader(status int) {
|
||||||
|
if w.wroteHeader {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.wroteHeader = true
|
||||||
|
// Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream.
|
||||||
|
if status != http.StatusNoContent && status != http.StatusNotModified && status != http.StatusPartialContent {
|
||||||
|
w.Header().Set("Content-Encoding", "gzip")
|
||||||
|
w.Header().Del("Content-Length")
|
||||||
|
w.gzipWriter = gzip.NewWriter(w.ResponseWriter)
|
||||||
|
}
|
||||||
|
w.ResponseWriter.WriteHeader(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *gzipResponseWriter) Write(p []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
if w.gzipWriter == nil {
|
||||||
|
return w.ResponseWriter.Write(p)
|
||||||
|
}
|
||||||
|
return w.gzipWriter.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// withGzip compresses responses for clients that send Accept-Encoding: gzip.
|
||||||
|
func withGzip(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Add("Vary", "Accept-Encoding")
|
||||||
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
compressed := &gzipResponseWriter{ResponseWriter: w}
|
||||||
|
next.ServeHTTP(compressed, r)
|
||||||
|
if compressed.gzipWriter != nil {
|
||||||
|
_ = compressed.gzipWriter.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func spaFileServer(root fs.FS) http.Handler {
|
func spaFileServer(root fs.FS) http.Handler {
|
||||||
fileServer := http.FileServer(http.FS(root))
|
fileServer := http.FileServer(http.FS(root))
|
||||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -299,10 +452,15 @@ func spaFileServer(root fs.FS) http.Handler {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Content-Security-Policy", dashboardCSP(data))
|
||||||
_, _ = w.Write(data)
|
_, _ = w.Write(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// The path is cleaned as a rooted URL path, and it is only read from webRoot,
|
||||||
|
// an embed.FS, so it cannot name a file outside the embedded build.
|
||||||
|
// nosemgrep: go.lang.security.filepath-clean-misuse.filepath-clean-misuse
|
||||||
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
||||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||||
serveIndex(w, r)
|
serveIndex(w, r)
|
||||||
@@ -312,6 +470,13 @@ func spaFileServer(root fs.FS) http.Handler {
|
|||||||
serveIndex(w, r)
|
serveIndex(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// SvelteKit names its content-hashed bundle files under _app/immutable/, so
|
||||||
|
// those can be cached for a long time. Everything else is revalidated.
|
||||||
|
if strings.HasPrefix(cleanPath, "_app/immutable/") {
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
}
|
||||||
fileServer.ServeHTTP(w, r)
|
fileServer.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"compress/gzip"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWithCORSAllowsOnlyListedOrigins(t *testing.T) {
|
||||||
|
const listed = "https://dashboard.example.com"
|
||||||
|
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
})
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
allowed []string
|
||||||
|
origin string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "listed origin is echoed", allowed: []string{listed}, origin: listed, want: listed},
|
||||||
|
{name: "unlisted origin gets no header", allowed: []string{listed}, origin: "https://evil.example", want: ""},
|
||||||
|
{name: "no allow list means no CORS", allowed: nil, origin: listed, want: ""},
|
||||||
|
{name: "no origin header means no CORS", allowed: []string{listed}, origin: "", want: ""},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||||
|
if tc.origin != "" {
|
||||||
|
request.Header.Set("Origin", tc.origin)
|
||||||
|
}
|
||||||
|
withCORS(tc.allowed, next).ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if got := recorder.Header().Get("Access-Control-Allow-Origin"); got != tc.want {
|
||||||
|
t.Fatalf("Access-Control-Allow-Origin = %q, want %q", got, tc.want)
|
||||||
|
}
|
||||||
|
wantCredentials := ""
|
||||||
|
if tc.want != "" {
|
||||||
|
wantCredentials = "true"
|
||||||
|
}
|
||||||
|
if got := recorder.Header().Get("Access-Control-Allow-Credentials"); got != wantCredentials {
|
||||||
|
t.Fatalf("Access-Control-Allow-Credentials = %q, want %q", got, wantCredentials)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithCORSPreflightAllowsPatchForListedOrigin(t *testing.T) {
|
||||||
|
const listed = "https://dashboard.example.com"
|
||||||
|
handler := withCORS([]string{listed}, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodOptions, "/api/auth/users/1", nil)
|
||||||
|
request.Header.Set("Origin", listed)
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent)
|
||||||
|
}
|
||||||
|
if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, "PATCH") {
|
||||||
|
t.Fatalf("Access-Control-Allow-Methods = %q, want PATCH included", methods)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithSecurityHeadersSetsFramingAndSniffingDefaults(t *testing.T) {
|
||||||
|
handler := withSecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||||
|
|
||||||
|
want := map[string]string{
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"X-Frame-Options": "DENY",
|
||||||
|
"Content-Security-Policy": "frame-ancestors 'none'",
|
||||||
|
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||||
|
}
|
||||||
|
for name, value := range want {
|
||||||
|
if got := recorder.Header().Get(name); got != value {
|
||||||
|
t.Fatalf("%s = %q, want %q", name, got, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithGzipCompressesOnlyWhenAccepted(t *testing.T) {
|
||||||
|
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
|
}))
|
||||||
|
|
||||||
|
accepted := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||||
|
request.Header.Set("Accept-Encoding", "gzip, deflate")
|
||||||
|
handler.ServeHTTP(accepted, request)
|
||||||
|
if got := accepted.Header().Get("Content-Encoding"); got != "gzip" {
|
||||||
|
t.Fatalf("Content-Encoding = %q, want gzip", got)
|
||||||
|
}
|
||||||
|
reader, err := gzip.NewReader(accepted.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("gzip.NewReader() error = %v", err)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading gzip body error = %v", err)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(string(body)); got != `{"ok":true}` {
|
||||||
|
t.Fatalf("decompressed body = %q, want the JSON document", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
plain := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/web/data", nil))
|
||||||
|
if got := plain.Header().Get("Content-Encoding"); got != "" {
|
||||||
|
t.Fatalf("Content-Encoding without Accept-Encoding = %q, want none", got)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(plain.Body.String()); got != `{"ok":true}` {
|
||||||
|
t.Fatalf("plain body = %q, want the JSON document", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithGzipLeavesNotModifiedWithoutBody(t *testing.T) {
|
||||||
|
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.Header().Set("ETag", `W/"abc"`)
|
||||||
|
w.WriteHeader(http.StatusNotModified)
|
||||||
|
}))
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||||
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusNotModified {
|
||||||
|
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusNotModified)
|
||||||
|
}
|
||||||
|
if got := recorder.Header().Get("Content-Encoding"); got != "" {
|
||||||
|
t.Fatalf("Content-Encoding on 304 = %q, want none", got)
|
||||||
|
}
|
||||||
|
if recorder.Body.Len() != 0 {
|
||||||
|
t.Fatalf("304 body length = %d, want 0", recorder.Body.Len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSPAFileServerCachesHashedAssetsLong(t *testing.T) {
|
||||||
|
root := fstest.MapFS{
|
||||||
|
"index.html": {Data: []byte("<html></html>")},
|
||||||
|
"favicon.svg": {Data: []byte("<svg></svg>")},
|
||||||
|
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
|
||||||
|
}
|
||||||
|
handler := spaFileServer(root)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
path string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{path: "/", want: "no-cache"},
|
||||||
|
{path: "/favicon.svg", want: "no-cache"},
|
||||||
|
{path: "/_app/immutable/app.abc.js", want: "public, max-age=31536000, immutable"},
|
||||||
|
{path: "/lists/123", want: "no-cache"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.path, func(t *testing.T) {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, tc.path, nil))
|
||||||
|
if got := recorder.Header().Get("Cache-Control"); got != tc.want {
|
||||||
|
t.Fatalf("Cache-Control = %q, want %q", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeJSONLimitRejectsOversizedBodies(t *testing.T) {
|
||||||
|
type payload struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
small := httptest.NewRecorder()
|
||||||
|
var ok payload
|
||||||
|
if err := decodeJSONLimit(small, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{"name":"a"}`)), &ok, 64); err != nil {
|
||||||
|
t.Fatalf("decodeJSONLimit() within limit error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
large := httptest.NewRecorder()
|
||||||
|
var tooBig payload
|
||||||
|
body := `{"name":"` + strings.Repeat("a", 256) + `"}`
|
||||||
|
err := decodeJSONLimit(large, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(body)), &tooBig, 64)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("decodeJSONLimit() over limit returned no error")
|
||||||
|
}
|
||||||
|
answer := httptest.NewRecorder()
|
||||||
|
writeDecodeError(answer, err, "Invalid JSON body")
|
||||||
|
if answer.Code != http.StatusRequestEntityTooLarge {
|
||||||
|
t.Fatalf("status for oversized body = %d, want %d", answer.Code, http.StatusRequestEntityTooLarge)
|
||||||
|
}
|
||||||
|
|
||||||
|
malformed := httptest.NewRecorder()
|
||||||
|
err = decodeJSONLimit(malformed, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{`)), &tooBig, 64)
|
||||||
|
writeDecodeError(malformed, err, "Invalid JSON body")
|
||||||
|
if malformed.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("status for malformed body = %d, want %d", malformed.Code, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
}
|
||||||
+397
-182
@@ -1,14 +1,22 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
||||||
|
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
||||||
|
const maxConcurrentSyncs = 4
|
||||||
|
const syncPageSize = 500
|
||||||
|
|
||||||
func syncMaxFutureSkew() int64 {
|
func syncMaxFutureSkew() int64 {
|
||||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||||
if value < 0 {
|
if value < 0 {
|
||||||
@@ -42,208 +50,415 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
|||||||
return created, updated
|
return created, updated
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// valueReferences returns the list ID of each field and the existence of each
|
||||||
|
// item that the values refer to, using one statement per table.
|
||||||
|
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]string, error) {
|
||||||
|
fieldLists := make(map[string]string)
|
||||||
|
itemLists := make(map[string]string)
|
||||||
|
if len(values) == 0 {
|
||||||
|
return fieldLists, itemLists, nil
|
||||||
|
}
|
||||||
|
fieldIDs := make([]string, 0, len(values))
|
||||||
|
itemIDs := make([]string, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
fieldIDs = append(fieldIDs, value.FieldID)
|
||||||
|
itemIDs = append(itemIDs, value.ItemID)
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldRows, err := tx.Query(ctx, `SELECT id, listid FROM fields WHERE id = ANY($1)`, fieldIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
defer fieldRows.Close()
|
||||||
|
for fieldRows.Next() {
|
||||||
|
var fieldID, listID string
|
||||||
|
if err := fieldRows.Scan(&fieldID, &listID); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
fieldLists[fieldID] = listID
|
||||||
|
}
|
||||||
|
if err := fieldRows.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
itemRows, err := tx.Query(ctx, `SELECT id, listid FROM items WHERE id = ANY($1)`, itemIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
defer itemRows.Close()
|
||||||
|
for itemRows.Next() {
|
||||||
|
var itemID, listID string
|
||||||
|
if err := itemRows.Scan(&itemID, &listID); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
itemLists[itemID] = listID
|
||||||
|
}
|
||||||
|
if err := itemRows.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return fieldLists, itemLists, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// changeEventType names a synced change for the notification feed: a tombstone
|
||||||
|
// is "deleted", a first sync reports "created", and anything else "updated".
|
||||||
|
func changeEventType(initialSync, deleted bool) string {
|
||||||
|
if deleted {
|
||||||
|
return "deleted"
|
||||||
|
}
|
||||||
|
if initialSync {
|
||||||
|
return "created"
|
||||||
|
}
|
||||||
|
return "updated"
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncBatch holds what every row of one sync request shares.
|
||||||
|
type syncBatch struct {
|
||||||
|
now int64
|
||||||
|
userID int64
|
||||||
|
initialSync bool
|
||||||
|
deviceID string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) {
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt))
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyLists upserts the pushed lists. A write older than the stored row
|
||||||
|
// changes nothing, so it triggers no cascade or notification.
|
||||||
|
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
||||||
|
for _, list := range lists {
|
||||||
|
member, err := authorizeList(ctx, tx, batch.userID, list.ID, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
||||||
|
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
if err := addListOwner(ctx, tx, batch.userID, list.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !applied {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt)
|
||||||
|
|
||||||
|
if list.IsDeleted {
|
||||||
|
if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureEntityList(ctx context.Context, tx pgx.Tx, table, id, listID string) error {
|
||||||
|
var storedListID string
|
||||||
|
err := tx.QueryRow(ctx, `SELECT listid FROM `+table+` WHERE id = $1`, id).Scan(&storedListID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if storedListID != listID {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||||
|
for _, field := range fields {
|
||||||
|
if err := ensureEntityList(ctx, tx, "fields", field.ID, field.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||||
|
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !applied {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt)
|
||||||
|
|
||||||
|
if field.IsDeleted {
|
||||||
|
if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||||
|
for _, item := range items {
|
||||||
|
if err := ensureEntityList(ctx, tx, "items", item.ID, item.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, item.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||||
|
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !applied {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt)
|
||||||
|
if item.IsDeleted {
|
||||||
|
if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyValues upserts the pushed item values and returns the ones it could not
|
||||||
|
// place. Items are read after applyItems has run, so a request's own item inserts
|
||||||
|
// are visible.
|
||||||
|
func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) {
|
||||||
|
orphans := make([]OrphanValue, 0)
|
||||||
|
// Resolve the fields and items the values refer to once per request, not once
|
||||||
|
// per value.
|
||||||
|
fieldLists, itemLists, err := valueReferences(ctx, tx, values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range values {
|
||||||
|
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now)
|
||||||
|
listID, ok := fieldLists[value.FieldID]
|
||||||
|
if !ok {
|
||||||
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
|
||||||
|
itemListID, itemExists := itemLists[value.ItemID]
|
||||||
|
if !itemExists {
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $3, 0)
|
||||||
|
ON CONFLICT (id) DO NOTHING
|
||||||
|
`, value.ItemID, listID, updatedAt); err != nil {
|
||||||
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
itemLists[value.ItemID] = listID
|
||||||
|
} else if itemListID != listID {
|
||||||
|
itemMember, err := hasListMembership(ctx, tx, batch.userID, itemListID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !itemMember {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "itemFieldListMismatch"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !applied {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt)
|
||||||
|
}
|
||||||
|
return orphans, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applySyncRequest writes everything a device pushed, parents before children.
|
||||||
|
func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) {
|
||||||
|
if err := applyLists(ctx, tx, request.Lists, batch); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := applyFields(ctx, tx, request.Fields, batch); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := applyItems(ctx, tx, request.Items, batch); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return applyValues(ctx, tx, request.ItemValues, batch)
|
||||||
|
}
|
||||||
|
|
||||||
|
type syncChange struct {
|
||||||
|
token int64
|
||||||
|
kind string
|
||||||
|
value any
|
||||||
|
}
|
||||||
|
|
||||||
|
type trailingTokenScanner struct {
|
||||||
|
row rowScanner
|
||||||
|
token int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *trailingTokenScanner) Scan(dest ...any) error {
|
||||||
|
return s.row.Scan(append(dest, &s.token)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// changesSince returns a bounded page from one repeatable-read snapshot. Each
|
||||||
|
// data write takes the clock row lock before touching a row, so a later commit
|
||||||
|
// cannot publish a lower token than a cursor already returned to a device.
|
||||||
|
func (d *DB) changesSince(ctx context.Context, userID int64, cursor int64) (SyncResponse, error) {
|
||||||
|
tx, err := d.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||||
|
if err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
var serverToken int64
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&serverToken); err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
if cursor > serverToken {
|
||||||
|
cursor = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
queries := []struct {
|
||||||
|
kind string
|
||||||
|
stmt string
|
||||||
|
scan func(rowScanner) (any, error)
|
||||||
|
}{
|
||||||
|
{kind: "list", stmt: `SELECT lists.id, lists.name, lists.createdat, lists.updatedat, COALESCE(lists.isdeleted, 0), lists.change_token FROM lists JOIN list_memberships m ON m.listid = lists.id WHERE m.user_id = $1 AND lists.change_token > $2 ORDER BY lists.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanList(row) }},
|
||||||
|
{kind: "field", stmt: `SELECT fields.id, fields.name, fields.fieldtype, COALESCE(fields.fieldoptions, ''), COALESCE(fields.alignment, 'start'), fields.listid, fields."order", fields.createdat, fields.updatedat, COALESCE(fields.isdeleted, 0), fields.change_token FROM fields JOIN list_memberships m ON m.listid = fields.listid WHERE m.user_id = $1 AND fields.change_token > $2 ORDER BY fields.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanField(row) }},
|
||||||
|
{kind: "item", stmt: `SELECT items.id, items.listid, items.createdat, items.updatedat, COALESCE(items.isdeleted, 0), items.change_token FROM items JOIN list_memberships m ON m.listid = items.listid WHERE m.user_id = $1 AND items.change_token > $2 ORDER BY items.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItem(row) }},
|
||||||
|
{kind: "value", stmt: `SELECT item_values.id, item_values.itemid, item_values.fieldid, COALESCE(item_values.value, ''), item_values.updatedat, item_values.change_token FROM item_values JOIN items i ON i.id = item_values.itemid JOIN list_memberships m ON m.listid = i.listid WHERE m.user_id = $1 AND item_values.change_token > $2 ORDER BY item_values.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItemValue(row) }},
|
||||||
|
}
|
||||||
|
changes := make([]syncChange, 0, syncPageSize*2)
|
||||||
|
for _, query := range queries {
|
||||||
|
rows, err := tx.Query(ctx, query.stmt, userID, cursor, syncPageSize+1)
|
||||||
|
if err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
scanner := trailingTokenScanner{row: rows}
|
||||||
|
value, err := query.scan(&scanner)
|
||||||
|
if err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
changes = append(changes, syncChange{token: scanner.token, kind: query.kind, value: value})
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
}
|
||||||
|
sort.Slice(changes, func(i, j int) bool { return changes[i].token < changes[j].token })
|
||||||
|
hasMore := len(changes) > syncPageSize
|
||||||
|
if hasMore {
|
||||||
|
changes = changes[:syncPageSize]
|
||||||
|
}
|
||||||
|
nextToken := serverToken
|
||||||
|
if hasMore {
|
||||||
|
nextToken = changes[len(changes)-1].token
|
||||||
|
}
|
||||||
|
response := SyncResponse{
|
||||||
|
Lists: make([]List, 0),
|
||||||
|
Fields: make([]Field, 0),
|
||||||
|
Items: make([]Item, 0),
|
||||||
|
ItemValues: make([]ItemValue, 0),
|
||||||
|
ServerChangeToken: serverToken,
|
||||||
|
NextSyncToken: nextToken,
|
||||||
|
HasMore: hasMore,
|
||||||
|
}
|
||||||
|
for _, change := range changes {
|
||||||
|
switch change.kind {
|
||||||
|
case "list":
|
||||||
|
response.Lists = append(response.Lists, change.value.(List))
|
||||||
|
case "field":
|
||||||
|
response.Fields = append(response.Fields, change.value.(Field))
|
||||||
|
case "item":
|
||||||
|
response.Items = append(response.Items, change.value.(Item))
|
||||||
|
case "value":
|
||||||
|
response.ItemValues = append(response.ItemValues, change.value.(ItemValue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Bound the number of syncs in flight, so large bodies and transactions cannot
|
||||||
|
// take every database connection at once.
|
||||||
|
select {
|
||||||
|
case s.syncSlots <- struct{}{}:
|
||||||
|
defer func() { <-s.syncSlots }()
|
||||||
|
case <-r.Context().Done():
|
||||||
|
writeJSONError(w, http.StatusServiceUnavailable, "Sync busy")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var request SyncRequest
|
var request SyncRequest
|
||||||
if err := decodeJSON(r, &request); err != nil {
|
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
writeDecodeError(w, err, "Invalid sync request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.LastSyncToken == nil || *request.LastSyncToken < 0 {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, "lastSyncToken is required; update the CollabTable client")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
batch := syncBatch{now: now, userID: requestUserID(r), initialSync: *request.LastSyncToken == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||||
deviceID := requestDeviceID(r, request.DeviceID)
|
|
||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||||
if incoming > 0 {
|
if incoming > 0 {
|
||||||
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
logPrintf(logshipper.LevelInfo, "[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
for _, list := range request.Lists {
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
return err
|
||||||
if _, err := tx.Exec(r.Context(), `
|
|
||||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
ON CONFLICT (id) DO UPDATE
|
|
||||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
|
||||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
event := "updated"
|
|
||||||
if lastSync == 0 {
|
|
||||||
event = "created"
|
|
||||||
}
|
|
||||||
if list.IsDeleted {
|
|
||||||
event = "deleted"
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
|
|
||||||
|
|
||||||
if list.IsDeleted {
|
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
var err error
|
||||||
for _, field := range request.Fields {
|
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
return err
|
||||||
fieldType := field.FieldType
|
|
||||||
if fieldType == "" {
|
|
||||||
fieldType = "TEXT"
|
|
||||||
}
|
|
||||||
alignment := field.Alignment
|
|
||||||
if alignment == "" {
|
|
||||||
alignment = "start"
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `
|
|
||||||
INSERT INTO fields
|
|
||||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
||||||
ON CONFLICT (id) DO UPDATE
|
|
||||||
SET name = EXCLUDED.name,
|
|
||||||
fieldtype = EXCLUDED.fieldtype,
|
|
||||||
fieldoptions = EXCLUDED.fieldoptions,
|
|
||||||
alignment = EXCLUDED.alignment,
|
|
||||||
"order" = EXCLUDED."order",
|
|
||||||
updatedat = EXCLUDED.updatedat,
|
|
||||||
isdeleted = EXCLUDED.isdeleted
|
|
||||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
event := "updated"
|
|
||||||
if lastSync == 0 {
|
|
||||||
event = "created"
|
|
||||||
}
|
|
||||||
if field.IsDeleted {
|
|
||||||
event = "deleted"
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
|
|
||||||
|
|
||||||
if field.IsDeleted {
|
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var remaining int
|
|
||||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if remaining == 0 {
|
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, item := range request.Items {
|
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
|
|
||||||
if _, err := tx.Exec(r.Context(), `
|
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
ON CONFLICT (id) DO UPDATE
|
|
||||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
|
||||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
event := "updated"
|
|
||||||
if lastSync == 0 {
|
|
||||||
event = "created"
|
|
||||||
}
|
|
||||||
if item.IsDeleted {
|
|
||||||
event = "deleted"
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
|
|
||||||
if item.IsDeleted {
|
|
||||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, value := range request.ItemValues {
|
|
||||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
|
||||||
var listID string
|
|
||||||
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
|
|
||||||
if errors.Is(fieldErr, pgx.ErrNoRows) {
|
|
||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if fieldErr != nil {
|
|
||||||
return fieldErr
|
|
||||||
}
|
|
||||||
|
|
||||||
var itemExists bool
|
|
||||||
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !itemExists {
|
|
||||||
if _, err := tx.Exec(r.Context(), `
|
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
|
||||||
VALUES ($1, $2, $3, $3, 0)
|
|
||||||
ON CONFLICT (id) DO NOTHING
|
|
||||||
`, value.ItemID, listID, updatedAt); err != nil {
|
|
||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, err := tx.Exec(r.Context(), `
|
|
||||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
ON CONFLICT (id) DO UPDATE
|
|
||||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
|
||||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logPrintf(logshipper.LevelError, "[SYNC] Failed: %v\n", err)
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var since *int64
|
response, err := s.db.changesSince(r.Context(), requestUserID(r), *request.LastSyncToken)
|
||||||
if lastSync != 0 {
|
|
||||||
since = &lastSync
|
|
||||||
}
|
|
||||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
response.OrphanItemValues = orphans
|
||||||
if err != nil {
|
response.ServerTimestamp = time.Now().UnixMilli()
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSON(w, http.StatusOK, response)
|
||||||
return
|
|
||||||
}
|
|
||||||
items, err := s.db.queryItems(r.Context(), true, since, "")
|
|
||||||
if err != nil {
|
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
values, err := s.db.queryValues(r.Context(), since, "")
|
|
||||||
if err != nil {
|
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, SyncResponse{
|
|
||||||
Lists: lists,
|
|
||||||
Fields: fields,
|
|
||||||
Items: items,
|
|
||||||
ItemValues: values,
|
|
||||||
OrphanItemValues: orphans,
|
|
||||||
ServerTimestamp: time.Now().UnixMilli(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -25,3 +25,24 @@ func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
|
|||||||
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
|
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestChangeEventTypeNamesEachChange(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
initialSync bool
|
||||||
|
deleted bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "first sync creates", initialSync: true, want: "created"},
|
||||||
|
{name: "later edit updates", initialSync: false, want: "updated"},
|
||||||
|
{name: "tombstone is deleted on first sync", initialSync: true, deleted: true, want: "deleted"},
|
||||||
|
{name: "tombstone is deleted later", initialSync: false, deleted: true, want: "deleted"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
if got := changeEventType(tc.initialSync, tc.deleted); got != tc.want {
|
||||||
|
t.Fatalf("changeEventType(%v, %v) = %q, want %q", tc.initialSync, tc.deleted, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
-12
@@ -1,28 +1,36 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
s.writeWebData(w, r, requestUserID(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) writeWebData(w http.ResponseWriter, r *http.Request, userID int64) {
|
||||||
|
lists, err := s.db.queryLists(r.Context(), userID, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
values, err := s.db.queryValues(r.Context(), userID, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
@@ -71,10 +79,7 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
|||||||
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
payload := map[string]any{
|
||||||
w.Header().Set("Pragma", "no-cache")
|
|
||||||
w.Header().Set("Expires", "0")
|
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
|
||||||
"lists": webLists,
|
"lists": webLists,
|
||||||
"fields": fields,
|
"fields": fields,
|
||||||
"items": items,
|
"items": items,
|
||||||
@@ -85,8 +90,41 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
|||||||
"items": len(items),
|
"items": len(items),
|
||||||
"values": len(values),
|
"values": len(values),
|
||||||
},
|
},
|
||||||
"timestamp": time.Now().UnixMilli(),
|
}
|
||||||
})
|
// The ETag covers the data only; the timestamp is added after hashing because
|
||||||
|
// it changes on every request.
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(body)
|
||||||
|
etag := `W/"` + hex.EncodeToString(digest[:]) + `"`
|
||||||
|
// Browsers may keep this per-user response, but revalidate it on every poll,
|
||||||
|
// so an unchanged dashboard gets a 304 instead of the full body.
|
||||||
|
w.Header().Set("Cache-Control", "private, no-cache")
|
||||||
|
w.Header().Set("ETag", etag)
|
||||||
|
if etagMatches(r.Header.Get("If-None-Match"), etag) {
|
||||||
|
w.WriteHeader(http.StatusNotModified)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload["timestamp"] = time.Now().UnixMilli()
|
||||||
|
writeJSON(w, http.StatusOK, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
// etagMatches reports whether an If-None-Match header matches etag under the
|
||||||
|
// weak comparison of RFC 9110, which ignores the W/ prefix.
|
||||||
|
func etagMatches(ifNoneMatch, etag string) bool {
|
||||||
|
if strings.TrimSpace(ifNoneMatch) == "*" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
want := strings.TrimPrefix(etag, "W/")
|
||||||
|
for _, candidate := range strings.Split(ifNoneMatch, ",") {
|
||||||
|
if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == want {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -100,10 +138,14 @@ func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request)
|
|||||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||||
FROM notifications
|
FROM notifications
|
||||||
WHERE createdat > $1
|
WHERE createdat > $1
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM list_memberships m
|
||||||
|
WHERE m.listid = notifications.listid AND m.user_id = $2
|
||||||
|
)
|
||||||
`
|
`
|
||||||
args := []any{since}
|
args := []any{since, requestUserID(r)}
|
||||||
if deviceID != "" {
|
if deviceID != "" {
|
||||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
|
||||||
args = append(args, deviceID)
|
args = append(args, deviceID)
|
||||||
}
|
}
|
||||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestEtagMatchesUsesWeakComparison(t *testing.T) {
|
||||||
|
const etag = `W/"abc"`
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
ifNoneMatch string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "missing header", ifNoneMatch: "", want: false},
|
||||||
|
{name: "same weak tag", ifNoneMatch: `W/"abc"`, want: true},
|
||||||
|
{name: "strong form of same tag", ifNoneMatch: `"abc"`, want: true},
|
||||||
|
{name: "one of several tags", ifNoneMatch: `"x", W/"abc"`, want: true},
|
||||||
|
{name: "different tag", ifNoneMatch: `W/"def"`, want: false},
|
||||||
|
{name: "wildcard", ifNoneMatch: "*", want: true},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
if got := etagMatches(tc.ifNoneMatch, etag); got != tc.want {
|
||||||
|
t.Fatalf("etagMatches(%q) = %v, want %v", tc.ifNoneMatch, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -8,7 +8,7 @@ COPY shared/package.json shared/package-lock.json /shared/
|
|||||||
COPY shared/packages/design-tokens/package.json /shared/packages/design-tokens/
|
COPY shared/packages/design-tokens/package.json /shared/packages/design-tokens/
|
||||||
COPY shared/packages/node-backend/package.json /shared/packages/node-backend/
|
COPY shared/packages/node-backend/package.json /shared/packages/node-backend/
|
||||||
COPY shared/packages/web-ui/package.json /shared/packages/web-ui/
|
COPY shared/packages/web-ui/package.json /shared/packages/web-ui/
|
||||||
RUN npm ci --prefix /shared --ignore-scripts --no-audit --no-fund --omit=dev
|
RUN npm ci --prefix /shared --ignore-scripts --no-audit --no-fund
|
||||||
RUN --mount=type=cache,target=/root/.npm \
|
RUN --mount=type=cache,target=/root/.npm \
|
||||||
for attempt in 1 2 3 4 5; do \
|
for attempt in 1 2 3 4 5; do \
|
||||||
npm ci && break; \
|
npm ci && break; \
|
||||||
@@ -20,6 +20,7 @@ RUN --mount=type=cache,target=/root/.npm \
|
|||||||
COPY shared/packages/design-tokens /shared/packages/design-tokens
|
COPY shared/packages/design-tokens /shared/packages/design-tokens
|
||||||
COPY shared/packages/node-backend /shared/packages/node-backend
|
COPY shared/packages/node-backend /shared/packages/node-backend
|
||||||
COPY shared/packages/web-ui /shared/packages/web-ui
|
COPY shared/packages/web-ui /shared/packages/web-ui
|
||||||
|
RUN npm run build --prefix /shared
|
||||||
COPY frontend/ ./
|
COPY frontend/ ./
|
||||||
RUN rm -rf /frontend/node_modules/@gabriel20xx/web-ui && \
|
RUN rm -rf /frontend/node_modules/@gabriel20xx/web-ui && \
|
||||||
ln -s /shared/packages/web-ui /frontend/node_modules/@gabriel20xx/web-ui
|
ln -s /shared/packages/web-ui /frontend/node_modules/@gabriel20xx/web-ui
|
||||||
@@ -43,6 +44,5 @@ COPY --from=builder /app/server /server
|
|||||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||||
USER 65534:65534
|
USER 65534:65534
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
VOLUME ["/data"]
|
|
||||||
ENV PORT=8080
|
ENV PORT=8080
|
||||||
ENTRYPOINT ["/server"]
|
ENTRYPOINT ["/server"]
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
{
|
{
|
||||||
"extends": "./.svelte-kit/tsconfig.json",
|
"extends": "$app/tsconfig",
|
||||||
|
"include": ["src", "test", "*"],
|
||||||
|
"exclude": ["src/service-worker"],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"checkJs": false,
|
"checkJs": false,
|
||||||
|
|||||||
Generated
+181
-251
@@ -8,6 +8,7 @@
|
|||||||
"name": "collabtable-server-frontend",
|
"name": "collabtable-server-frontend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
@@ -18,8 +19,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "latest",
|
"@eslint/js": "latest",
|
||||||
"@sveltejs/adapter-static": "latest",
|
"@sveltejs/adapter-static": "^4.0.1",
|
||||||
"@sveltejs/kit": "latest",
|
"@sveltejs/kit": "^3.1.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "latest",
|
"@sveltejs/vite-plugin-svelte": "latest",
|
||||||
"@tailwindcss/vite": "latest",
|
"@tailwindcss/vite": "latest",
|
||||||
"eslint": "latest",
|
"eslint": "latest",
|
||||||
@@ -27,13 +28,18 @@
|
|||||||
"eslint-plugin-svelte": "latest",
|
"eslint-plugin-svelte": "latest",
|
||||||
"prettier": "latest",
|
"prettier": "latest",
|
||||||
"prettier-plugin-svelte": "latest",
|
"prettier-plugin-svelte": "latest",
|
||||||
"svelte": "latest",
|
"svelte": "^5.57.3",
|
||||||
"svelte-check": "latest",
|
"svelte-check": "latest",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
"vite": "latest"
|
"vite": "^8.3.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"../shared/packages/design-tokens": {
|
||||||
|
"name": "@gabriel20xx/design-tokens",
|
||||||
|
"version": "0.1.1",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"../shared/packages/web-ui": {
|
"../shared/packages/web-ui": {
|
||||||
"name": "@gabriel20xx/web-ui",
|
"name": "@gabriel20xx/web-ui",
|
||||||
"version": "0.1.1",
|
"version": "0.1.1",
|
||||||
@@ -52,37 +58,6 @@
|
|||||||
"svelte": "^5.0.0"
|
"svelte": "^5.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@emnapi/core": {
|
|
||||||
"version": "2.0.0-alpha.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz",
|
|
||||||
"integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@emnapi/wasi-threads": "2.0.1",
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/runtime": {
|
|
||||||
"version": "2.0.0-alpha.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz",
|
|
||||||
"integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/wasi-threads": {
|
|
||||||
"version": "2.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz",
|
|
||||||
"integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@eslint-community/eslint-utils": {
|
"node_modules/@eslint-community/eslint-utils": {
|
||||||
"version": "4.10.1",
|
"version": "4.10.1",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
||||||
@@ -236,6 +211,10 @@
|
|||||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@gabriel20xx/design-tokens": {
|
||||||
|
"resolved": "../shared/packages/design-tokens",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/@gabriel20xx/web-ui": {
|
"node_modules/@gabriel20xx/web-ui": {
|
||||||
"resolved": "../shared/packages/web-ui",
|
"resolved": "../shared/packages/web-ui",
|
||||||
"link": true
|
"link": true
|
||||||
@@ -346,9 +325,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@jridgewell/sourcemap-codec": {
|
"node_modules/@jridgewell/sourcemap-codec": {
|
||||||
"version": "1.5.5",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
|
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||||
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
|
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@jridgewell/trace-mapping": {
|
"node_modules/@jridgewell/trace-mapping": {
|
||||||
@@ -370,35 +349,14 @@
|
|||||||
"svelte": "^5"
|
"svelte": "^5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@napi-rs/wasm-runtime": {
|
|
||||||
"version": "1.2.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
|
|
||||||
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@tybys/wasm-util": "^0.10.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
|
|
||||||
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@oxc-project/types": {
|
"node_modules/@oxc-project/types": {
|
||||||
"version": "0.142.0",
|
"version": "0.155.0",
|
||||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz",
|
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
|
||||||
"integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
|
"integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/Boshen"
|
"url": "https://github.com/sponsors/oxc-project"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@polka/url": {
|
"node_modules/@polka/url": {
|
||||||
@@ -408,10 +366,26 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||||
|
"version": "1.2.15",
|
||||||
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz",
|
||||||
|
"integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/binding-android-arm64": {
|
"node_modules/@rolldown/binding-android-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA==",
|
"integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -425,9 +399,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA==",
|
"integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -441,9 +415,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-x64": {
|
"node_modules/@rolldown/binding-darwin-x64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz",
|
||||||
"integrity": "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ==",
|
"integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -457,9 +431,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz",
|
||||||
"integrity": "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg==",
|
"integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -473,9 +447,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz",
|
||||||
"integrity": "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA==",
|
"integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
@@ -489,9 +463,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg==",
|
"integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -508,9 +482,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz",
|
||||||
"integrity": "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A==",
|
"integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -527,9 +501,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg==",
|
"integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
@@ -546,9 +520,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ==",
|
"integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
@@ -565,9 +539,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==",
|
"integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -584,9 +558,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz",
|
||||||
"integrity": "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A==",
|
"integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -603,9 +577,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw==",
|
"integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -618,25 +592,10 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
|
||||||
"version": "1.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.1.tgz",
|
|
||||||
"integrity": "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@emnapi/core": "2.0.0-alpha.3",
|
|
||||||
"@emnapi/runtime": "2.0.0-alpha.3",
|
|
||||||
"@napi-rs/wasm-runtime": "^1.2.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz",
|
||||||
"integrity": "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw==",
|
"integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -650,9 +609,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz",
|
||||||
"integrity": "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ==",
|
"integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -680,56 +639,53 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/acorn-typescript": {
|
"node_modules/@sveltejs/acorn-typescript": {
|
||||||
"version": "1.0.11",
|
"version": "1.0.13",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
|
||||||
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
|
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"acorn": "^8.9.0"
|
"acorn": "^8.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/adapter-static": {
|
"node_modules/@sveltejs/adapter-static": {
|
||||||
"version": "3.0.10",
|
"version": "4.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-3.0.10.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-4.0.1.tgz",
|
||||||
"integrity": "sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==",
|
"integrity": "sha512-svOU1OcBiJ9Kn1cdxHDmJIsBy1/iQe9STPvUFkO2/iinxPFS7r8fc9TiCaWWUgbrE+7ox6Bt4MURv3RPi7sunQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@sveltejs/kit": "^2.0.0"
|
"@sveltejs/kit": "^3.0.0-next.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/kit": {
|
"node_modules/@sveltejs/kit": {
|
||||||
"version": "2.70.2",
|
"version": "3.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.2.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-3.2.0.tgz",
|
||||||
"integrity": "sha512-RzRoRpuR2KXqc5yMO0akQHDZeT4AslOlznGITURsqHaVbtyYP4Wn3eE3gxj9JcDyNYO0crkxhdwFHc+2vkVm6w==",
|
"integrity": "sha512-zhb8GTeFd/6BwfqaY4wKIF7eFACYOgn/KNppV6UHFBHk174B4d7xTtN7x0PxaPPlwnCTgbnpaYF6r9lirz0Biw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/spec": "^1.0.0",
|
"@jridgewell/trace-mapping": "^0.3.31",
|
||||||
"@sveltejs/acorn-typescript": "^1.0.9",
|
"@rolldown/pluginutils": "^1.0.1",
|
||||||
"@types/cookie": "^0.6.0",
|
"@standard-schema/spec": "^1.1.0",
|
||||||
"acorn": "^8.16.0",
|
"cookie": "^2.0.1",
|
||||||
"cookie": "^0.6.0",
|
"devalue": "^5.9.4",
|
||||||
"devalue": "^5.8.1",
|
|
||||||
"esm-env": "^1.2.2",
|
"esm-env": "^1.2.2",
|
||||||
"kleur": "^4.1.5",
|
"magic-string": "^1.2.3",
|
||||||
"magic-string": "^0.30.5",
|
"mrmime": "^2.0.1",
|
||||||
"mrmime": "^2.0.0",
|
"sirv": "^3.0.2"
|
||||||
"set-cookie-parser": "^3.0.0",
|
|
||||||
"sirv": "^3.0.0"
|
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"svelte-kit": "svelte-kit.js"
|
"svelte-kit": "svelte-kit.js"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.13"
|
"node": ">=22.17"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@opentelemetry/api": "^1.0.0",
|
"@opentelemetry/api": "^1.0.0",
|
||||||
"@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0",
|
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||||
"svelte": "^4.0.0 || ^5.0.0-next.0",
|
"svelte": "^5.57.1",
|
||||||
"typescript": "^5.3.3 || ^6.0.0",
|
"typescript": "^6.0.0",
|
||||||
"vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0"
|
"vite": "^8.0.12"
|
||||||
},
|
},
|
||||||
"peerDependenciesMeta": {
|
"peerDependenciesMeta": {
|
||||||
"@opentelemetry/api": {
|
"@opentelemetry/api": {
|
||||||
@@ -740,6 +696,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@sveltejs/kit/node_modules/magic-string": {
|
||||||
|
"version": "1.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
|
||||||
|
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@sveltejs/load-config": {
|
"node_modules/@sveltejs/load-config": {
|
||||||
"version": "0.2.1",
|
"version": "0.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz",
|
||||||
@@ -1156,23 +1122,6 @@
|
|||||||
"svelte": "^5.25.0"
|
"svelte": "^5.25.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@tybys/wasm-util": {
|
|
||||||
"version": "0.10.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
|
|
||||||
"integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/cookie": {
|
|
||||||
"version": "0.6.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
|
|
||||||
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/esrecurse": {
|
"node_modules/@types/esrecurse": {
|
||||||
"version": "4.3.1",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
|
||||||
@@ -1193,12 +1142,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/trusted-types": {
|
|
||||||
"version": "2.0.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
|
||||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.18.0",
|
"version": "8.18.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
||||||
@@ -1291,9 +1234,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/brace-expansion": {
|
"node_modules/brace-expansion": {
|
||||||
"version": "5.0.9",
|
"version": "5.0.12",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -1341,13 +1284,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
"node_modules/cookie": {
|
||||||
"version": "0.6.0",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz",
|
||||||
"integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==",
|
"integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.6"
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
@@ -1433,9 +1380,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/devalue": {
|
"node_modules/devalue": {
|
||||||
"version": "5.9.0",
|
"version": "5.9.4",
|
||||||
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
|
||||||
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==",
|
"integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/enhanced-resolve": {
|
"node_modules/enhanced-resolve": {
|
||||||
@@ -1644,9 +1591,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/esrap": {
|
"node_modules/esrap": {
|
||||||
"version": "2.3.0",
|
"version": "2.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
|
||||||
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
|
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jridgewell/sourcemap-codec": "^1.4.15"
|
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||||
@@ -1936,16 +1883,6 @@
|
|||||||
"json-buffer": "3.0.1"
|
"json-buffer": "3.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/kleur": {
|
|
||||||
"version": "4.1.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
|
|
||||||
"integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/known-css-properties": {
|
"node_modules/known-css-properties": {
|
||||||
"version": "0.37.0",
|
"version": "0.37.0",
|
||||||
"resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz",
|
"resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz",
|
||||||
@@ -2334,9 +2271,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.16",
|
"version": "3.3.20",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -2451,9 +2388,9 @@
|
|||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/picomatch": {
|
"node_modules/picomatch": {
|
||||||
"version": "4.0.5",
|
"version": "4.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||||
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -2464,9 +2401,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.25",
|
"version": "8.5.32",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
|
||||||
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
"integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -2484,9 +2421,9 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.16",
|
"nanoid": "^3.3.20",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
"source-map-js": "^1.2.1"
|
"source-map-js": "^1.2.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^10 || ^12 || >=14"
|
"node": "^10 || ^12 || >=14"
|
||||||
@@ -2665,13 +2602,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/rolldown": {
|
"node_modules/rolldown": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz",
|
||||||
"integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==",
|
"integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oxc-project/types": "=0.142.0",
|
"@oxc-project/types": "=0.155.0",
|
||||||
"@rolldown/pluginutils": "^1.0.0"
|
"@rolldown/pluginutils": "^1.0.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -2681,21 +2618,21 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@rolldown/binding-android-arm64": "1.2.1",
|
"@rolldown/binding-android-arm-eabi": "1.2.15",
|
||||||
"@rolldown/binding-darwin-arm64": "1.2.1",
|
"@rolldown/binding-android-arm64": "1.2.15",
|
||||||
"@rolldown/binding-darwin-x64": "1.2.1",
|
"@rolldown/binding-darwin-arm64": "1.2.15",
|
||||||
"@rolldown/binding-freebsd-x64": "1.2.1",
|
"@rolldown/binding-darwin-x64": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.1",
|
"@rolldown/binding-freebsd-x64": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm64-gnu": "1.2.1",
|
"@rolldown/binding-linux-arm-gnueabihf": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm64-musl": "1.2.1",
|
"@rolldown/binding-linux-arm64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.1",
|
"@rolldown/binding-linux-arm64-musl": "1.2.15",
|
||||||
"@rolldown/binding-linux-s390x-gnu": "1.2.1",
|
"@rolldown/binding-linux-ppc64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-x64-gnu": "1.2.1",
|
"@rolldown/binding-linux-s390x-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-x64-musl": "1.2.1",
|
"@rolldown/binding-linux-x64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-openharmony-arm64": "1.2.1",
|
"@rolldown/binding-linux-x64-musl": "1.2.15",
|
||||||
"@rolldown/binding-wasm32-wasi": "1.2.1",
|
"@rolldown/binding-openharmony-arm64": "1.2.15",
|
||||||
"@rolldown/binding-win32-arm64-msvc": "1.2.1",
|
"@rolldown/binding-win32-arm64-msvc": "1.2.15",
|
||||||
"@rolldown/binding-win32-x64-msvc": "1.2.1"
|
"@rolldown/binding-win32-x64-msvc": "1.2.15"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/runed": {
|
"node_modules/runed": {
|
||||||
@@ -2748,13 +2685,6 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/set-cookie-parser": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/shebang-command": {
|
"node_modules/shebang-command": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
@@ -2794,9 +2724,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
|
||||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "BSD-3-Clause",
|
"license": "BSD-3-Clause",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -2813,23 +2743,22 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/svelte": {
|
"node_modules/svelte": {
|
||||||
"version": "5.56.8",
|
"version": "5.57.3",
|
||||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
|
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
|
||||||
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
|
"integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jridgewell/remapping": "^2.3.4",
|
"@jridgewell/remapping": "^2.3.5",
|
||||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
"@jridgewell/sourcemap-codec": "^1.6.0",
|
||||||
"@sveltejs/acorn-typescript": "^1.0.10",
|
"@sveltejs/acorn-typescript": "^1.0.13",
|
||||||
"@types/estree": "^1.0.5",
|
"@types/estree": "^1.0.9",
|
||||||
"@types/trusted-types": "^2.0.7",
|
"acorn": "^8.18.0",
|
||||||
"acorn": "^8.12.1",
|
|
||||||
"aria-query": "5.3.1",
|
"aria-query": "5.3.1",
|
||||||
"axobject-query": "^4.1.0",
|
"axobject-query": "^4.1.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"devalue": "^5.8.1",
|
"devalue": "^5.9.2",
|
||||||
"esm-env": "^1.2.1",
|
"esm-env": "^1.2.1",
|
||||||
"esrap": "^2.2.12",
|
"esrap": "^2.3.6",
|
||||||
"is-reference": "^3.0.3",
|
"is-reference": "^3.0.3",
|
||||||
"locate-character": "^3.0.0",
|
"locate-character": "^3.0.0",
|
||||||
"magic-string": "^0.30.11",
|
"magic-string": "^0.30.11",
|
||||||
@@ -3031,7 +2960,8 @@
|
|||||||
"version": "2.8.1",
|
"version": "2.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"license": "0BSD"
|
"license": "0BSD",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/tw-animate-css": {
|
"node_modules/tw-animate-css": {
|
||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
@@ -3089,16 +3019,16 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "8.2.0",
|
"version": "8.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz",
|
||||||
"integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
|
"integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lightningcss": "^1.33.0",
|
"lightningcss": "^1.33.0",
|
||||||
"picomatch": "^4.0.5",
|
"picomatch": "^4.0.7",
|
||||||
"postcss": "^8.5.23",
|
"postcss": "^8.5.28",
|
||||||
"rolldown": "~1.2.0",
|
"rolldown": "~1.2.11",
|
||||||
"tinyglobby": "^0.2.17"
|
"tinyglobby": "^0.2.17"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -3115,7 +3045,7 @@
|
|||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/node": "^20.19.0 || >=22.12.0",
|
"@types/node": "^20.19.0 || >=22.12.0",
|
||||||
"@vitejs/devtools": "^0.4.0",
|
"@vitejs/devtools": "^0.7.1",
|
||||||
"esbuild": "^0.27.0 || ^0.28.0",
|
"esbuild": "^0.27.0 || ^0.28.0",
|
||||||
"jiti": ">=1.21.0",
|
"jiti": ">=1.21.0",
|
||||||
"less": "^4.0.0",
|
"less": "^4.0.0",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
|
"test": "node --test",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
@@ -14,8 +15,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "latest",
|
"@eslint/js": "latest",
|
||||||
"@sveltejs/adapter-static": "latest",
|
"@sveltejs/adapter-static": "^4.0.1",
|
||||||
"@sveltejs/kit": "latest",
|
"@sveltejs/kit": "^3.1.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "latest",
|
"@sveltejs/vite-plugin-svelte": "latest",
|
||||||
"@tailwindcss/vite": "latest",
|
"@tailwindcss/vite": "latest",
|
||||||
"eslint": "latest",
|
"eslint": "latest",
|
||||||
@@ -23,14 +24,15 @@
|
|||||||
"eslint-plugin-svelte": "latest",
|
"eslint-plugin-svelte": "latest",
|
||||||
"prettier": "latest",
|
"prettier": "latest",
|
||||||
"prettier-plugin-svelte": "latest",
|
"prettier-plugin-svelte": "latest",
|
||||||
"svelte": "latest",
|
"svelte": "^5.57.3",
|
||||||
"svelte-check": "latest",
|
"svelte-check": "latest",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
"vite": "latest"
|
"vite": "^8.3.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
"bits-ui": "latest",
|
"bits-ui": "latest",
|
||||||
|
|||||||
@@ -120,12 +120,13 @@ export async function logout() {
|
|||||||
// always be the account's current values when the caller isn't actually
|
// always be the account's current values when the caller isn't actually
|
||||||
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
||||||
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
||||||
// on hand. newPassword remains genuinely optional (omitted/blank leaves the
|
// on hand. When changing the password, the shared ProfileDialog also supplies
|
||||||
// password unchanged).
|
// currentPassword and (when enabled) totpToken for sharedauth's reauthentication
|
||||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
// check. newPassword remains optional when it is not being changed.
|
||||||
|
export async function updateCredentials({ newUsername, newEmail, newPassword, currentPassword, totpToken }) {
|
||||||
return request('/api/auth/credentials', {
|
return request('/api/auth/credentials', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword }),
|
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword, currentPassword, totpToken }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
|
||||||
|
import { updateCredentials } from './api.js';
|
||||||
|
|
||||||
|
test('updateCredentials forwards current password and TOTP proof', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (url, options) => {
|
||||||
|
captured = { url, options };
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({
|
||||||
|
newUsername: 'owner',
|
||||||
|
newEmail: 'owner@example.com',
|
||||||
|
newPassword: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(captured.url, '/api/auth/credentials');
|
||||||
|
assert.deepEqual(JSON.parse(captured.options.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
password: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('updateCredentials omits reauthentication proof when password is unchanged', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (_url, options) => {
|
||||||
|
captured = options;
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({ newUsername: 'owner', newEmail: 'owner@example.com' });
|
||||||
|
assert.deepEqual(JSON.parse(captured.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<script>
|
<script>
|
||||||
import ListCard from './ListCard.svelte';
|
import ListCard from './ListCard.svelte';
|
||||||
|
|
||||||
let { lists, fields, items, onSelect } = $props();
|
let { lists, fieldsByList, itemsByList, onSelect } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if lists.length === 0}
|
{#if lists.length === 0}
|
||||||
@@ -12,7 +12,12 @@
|
|||||||
{:else}
|
{:else}
|
||||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
{#each lists as list (list.id)}
|
{#each lists as list (list.id)}
|
||||||
<ListCard {list} {fields} {items} onClick={onSelect} />
|
<ListCard
|
||||||
|
{list}
|
||||||
|
fields={fieldsByList.get(list.id) ?? []}
|
||||||
|
items={itemsByList.get(list.id) ?? []}
|
||||||
|
onClick={onSelect}
|
||||||
|
/>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<script>
|
<script>
|
||||||
import ListRow from './ListRow.svelte';
|
import ListRow from './ListRow.svelte';
|
||||||
|
|
||||||
let { lists, fields, items, onSelect } = $props();
|
let { lists, fieldsByList, itemsByList, onSelect } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<table class="w-full text-left text-sm">
|
<table class="w-full text-left text-sm">
|
||||||
@@ -15,7 +15,12 @@
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{#each lists as list (list.id)}
|
{#each lists as list (list.id)}
|
||||||
<ListRow {list} {fields} {items} onClick={onSelect} />
|
<ListRow
|
||||||
|
{list}
|
||||||
|
fields={fieldsByList.get(list.id) ?? []}
|
||||||
|
items={itemsByList.get(list.id) ?? []}
|
||||||
|
onClick={onSelect}
|
||||||
|
/>
|
||||||
{/each}
|
{/each}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -2,14 +2,7 @@
|
|||||||
import { DropdownMenu } from 'bits-ui';
|
import { DropdownMenu } from 'bits-ui';
|
||||||
import { cn } from '$lib/utils/cn.js';
|
import { cn } from '$lib/utils/cn.js';
|
||||||
|
|
||||||
let {
|
let { ref = $bindable(null), class: className, sideOffset = 6, align = 'end', children, ...restProps } = $props();
|
||||||
ref = $bindable(null),
|
|
||||||
class: className,
|
|
||||||
sideOffset = 6,
|
|
||||||
align = 'end',
|
|
||||||
children,
|
|
||||||
...restProps
|
|
||||||
} = $props();
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<DropdownMenu.Portal>
|
<DropdownMenu.Portal>
|
||||||
|
|||||||
@@ -30,6 +30,8 @@
|
|||||||
newUsername: input.username.trim(),
|
newUsername: input.username.trim(),
|
||||||
newEmail: input.email.trim(),
|
newEmail: input.email.trim(),
|
||||||
newPassword: input.password || undefined,
|
newPassword: input.password || undefined,
|
||||||
|
currentPassword: input.currentPassword,
|
||||||
|
totpToken: input.totpToken,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -68,7 +68,6 @@
|
|||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={layoutState.wide}
|
checked={layoutState.wide}
|
||||||
onchange={(event) => layoutState.setWide(event.currentTarget.checked)}
|
onchange={(event) => layoutState.setWide(event.currentTarget.checked)}
|
||||||
class="size-4 rounded border-border accent-primary"
|
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div class="sc-form-actions">
|
<div class="sc-form-actions">
|
||||||
|
|||||||
@@ -6,8 +6,20 @@ export function listItemsFor(items, listId) {
|
|||||||
return items.filter((i) => i.listId === listId && !i.isDeleted);
|
return items.filter((i) => i.listId === listId && !i.isDeleted);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function itemValuesFor(values, itemId) {
|
// groupByKey indexes rows by keyOf in one pass. Build it once per data change in a
|
||||||
return values.filter((v) => v.itemId === itemId);
|
// $derived, then look rows up per card, row or cell instead of rescanning the data.
|
||||||
|
export function groupByKey(rows, keyOf) {
|
||||||
|
const groups = new Map();
|
||||||
|
for (const row of rows) {
|
||||||
|
const key = keyOf(row);
|
||||||
|
const group = groups.get(key);
|
||||||
|
if (group) {
|
||||||
|
group.push(row);
|
||||||
|
} else {
|
||||||
|
groups.set(key, [row]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function valueFor(values, itemId, fieldId) {
|
export function valueFor(values, itemId, fieldId) {
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
|
||||||
|
import { fmtDate, groupByKey, listFieldsFor, listItemsFor, valueFor } from './listHelpers.js';
|
||||||
|
|
||||||
|
test('listFieldsFor keeps the list’s live fields in display order', () => {
|
||||||
|
const fields = [
|
||||||
|
{ id: 'c', listId: 'l1', order: 2 },
|
||||||
|
{ id: 'gone', listId: 'l1', order: 0, isDeleted: true },
|
||||||
|
{ id: 'other', listId: 'l2', order: 0 },
|
||||||
|
{ id: 'a', listId: 'l1', order: 0 },
|
||||||
|
{ id: 'unordered', listId: 'l1' },
|
||||||
|
{ id: 'b', listId: 'l1', order: 1 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ids = listFieldsFor(fields, 'l1').map((f) => f.id);
|
||||||
|
|
||||||
|
// A field without an order sorts as 0, and the sort is stable.
|
||||||
|
assert.deepEqual(ids, ['a', 'unordered', 'b', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listFieldsFor does not reorder the array it was given', () => {
|
||||||
|
const fields = [
|
||||||
|
{ id: 'b', listId: 'l1', order: 1 },
|
||||||
|
{ id: 'a', listId: 'l1', order: 0 },
|
||||||
|
];
|
||||||
|
listFieldsFor(fields, 'l1');
|
||||||
|
assert.deepEqual(
|
||||||
|
fields.map((f) => f.id),
|
||||||
|
['b', 'a'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listItemsFor keeps only the list’s live items', () => {
|
||||||
|
const items = [
|
||||||
|
{ id: 'i1', listId: 'l1' },
|
||||||
|
{ id: 'i2', listId: 'l1', isDeleted: true },
|
||||||
|
{ id: 'i3', listId: 'l2' },
|
||||||
|
];
|
||||||
|
assert.deepEqual(
|
||||||
|
listItemsFor(items, 'l1').map((i) => i.id),
|
||||||
|
['i1'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(listItemsFor(items, 'missing'), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('groupByKey indexes rows by key and keeps their order', () => {
|
||||||
|
const rows = [
|
||||||
|
{ id: 1, listId: 'a' },
|
||||||
|
{ id: 2, listId: 'b' },
|
||||||
|
{ id: 3, listId: 'a' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const groups = groupByKey(rows, (row) => row.listId);
|
||||||
|
|
||||||
|
assert.deepEqual([...groups.keys()], ['a', 'b']);
|
||||||
|
assert.deepEqual(
|
||||||
|
groups.get('a').map((row) => row.id),
|
||||||
|
[1, 3],
|
||||||
|
);
|
||||||
|
assert.equal(groups.get('missing'), undefined);
|
||||||
|
assert.equal(groupByKey([], (row) => row.listId).size, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valueFor finds the value in one cell, or null', () => {
|
||||||
|
const values = [
|
||||||
|
{ itemId: 'i1', fieldId: 'f1', value: 'milk' },
|
||||||
|
{ itemId: 'i1', fieldId: 'f2', value: '' },
|
||||||
|
{ itemId: 'i2', fieldId: 'f1', value: 'eggs' },
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.equal(valueFor(values, 'i1', 'f1'), 'milk');
|
||||||
|
assert.equal(valueFor(values, 'i2', 'f1'), 'eggs');
|
||||||
|
// An empty value is a value, not a missing one.
|
||||||
|
assert.equal(valueFor(values, 'i1', 'f2'), '');
|
||||||
|
assert.equal(valueFor(values, 'i2', 'f2'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fmtDate shows a dash for missing or invalid dates', () => {
|
||||||
|
assert.equal(fmtDate(null), '—');
|
||||||
|
assert.equal(fmtDate(undefined), '—');
|
||||||
|
assert.equal(fmtDate('not a date'), '—');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fmtDate formats a millisecond timestamp for the reader’s locale', () => {
|
||||||
|
const ms = 1_700_000_000_000;
|
||||||
|
assert.equal(fmtDate(ms), new Date(ms).toLocaleString());
|
||||||
|
assert.notEqual(fmtDate(ms), '—');
|
||||||
|
});
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
export const languages = [
|
export const languages = [
|
||||||
{ id: 'ar', label: 'العربية' },
|
{ id: 'ar', label: 'العربية' },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
const STORAGE_KEY = 'collabtable-wide-layout';
|
const STORAGE_KEY = 'collabtable-wide-layout';
|
||||||
|
|
||||||
@@ -11,6 +11,14 @@ function loadInitialWide() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function applyWide(value) {
|
||||||
|
if (value) {
|
||||||
|
document.documentElement.setAttribute('data-wide-layout', 'true');
|
||||||
|
} else {
|
||||||
|
document.documentElement.removeAttribute('data-wide-layout');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let wide = $state(loadInitialWide());
|
let wide = $state(loadInitialWide());
|
||||||
|
|
||||||
export const layoutState = {
|
export const layoutState = {
|
||||||
@@ -21,7 +29,7 @@ export const layoutState = {
|
|||||||
wide = next;
|
wide = next;
|
||||||
if (!browser) return;
|
if (!browser) return;
|
||||||
|
|
||||||
document.documentElement.toggleAttribute('data-wide-layout', next);
|
applyWide(next);
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(STORAGE_KEY, String(next));
|
localStorage.setItem(STORAGE_KEY, String(next));
|
||||||
} catch {
|
} catch {
|
||||||
@@ -33,4 +41,4 @@ export const layoutState = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if (browser) document.documentElement.toggleAttribute('data-wide-layout', wide);
|
if (browser) applyWide(wide);
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
const STORAGE_KEY = 'collabtable-theme';
|
const STORAGE_KEY = 'collabtable-theme';
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { ArrowDown, ArrowUp, LayoutGrid, List, Search, X } from '@lucide/svelte';
|
import { ArrowDown, ArrowUp, LayoutGrid, List, Search, X } from '@lucide/svelte';
|
||||||
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
|
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
|
||||||
|
import { groupByKey } from '$lib/features/lists/listHelpers.js';
|
||||||
import { searchState, filterListsBySearch } from '$lib/search.svelte.js';
|
import { searchState, filterListsBySearch } from '$lib/search.svelte.js';
|
||||||
import { createDashboardViewMode } from '$lib/preferences/viewMode.svelte.js';
|
import { createDashboardViewMode } from '$lib/preferences/viewMode.svelte.js';
|
||||||
import Button from '$lib/components/ui/button.svelte';
|
import Button from '$lib/components/ui/button.svelte';
|
||||||
@@ -42,6 +43,10 @@
|
|||||||
let searched = $derived(filterListsBySearch(overview.lists, searchState.query));
|
let searched = $derived(filterListsBySearch(overview.lists, searchState.query));
|
||||||
let sorted = $derived(sortLists(searched, sortField, sortDir));
|
let sorted = $derived(sortLists(searched, sortField, sortDir));
|
||||||
let pageItems = $derived(sorted.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize));
|
let pageItems = $derived(sorted.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize));
|
||||||
|
// Index fields and items by list once per data change, so each visible card or row
|
||||||
|
// reads its own slice instead of scanning every field and item.
|
||||||
|
let fieldsByList = $derived(groupByKey(overview.fields, (f) => f.listId));
|
||||||
|
let itemsByList = $derived(groupByKey(overview.items, (i) => i.listId));
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
void searchState.query;
|
void searchState.query;
|
||||||
@@ -148,9 +153,9 @@
|
|||||||
|
|
||||||
<div class="overflow-x-auto rounded-lg border border-border bg-bg p-3">
|
<div class="overflow-x-auto rounded-lg border border-border bg-bg p-3">
|
||||||
{#if viewMode.mode === 'list'}
|
{#if viewMode.mode === 'list'}
|
||||||
<ListsTable lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
|
<ListsTable lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
|
||||||
{:else}
|
{:else}
|
||||||
<ListsGrid lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
|
<ListsGrid lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
import Button from '$lib/components/ui/button.svelte';
|
import Button from '$lib/components/ui/button.svelte';
|
||||||
import { Pagination } from '@gabriel20xx/web-ui';
|
import { Pagination } from '@gabriel20xx/web-ui';
|
||||||
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
|
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
|
||||||
import { listFieldsFor, listItemsFor, itemValuesFor, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js';
|
import { listFieldsFor, listItemsFor, groupByKey, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js';
|
||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
|
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
const list = $derived(overview.lists.find((l) => l.id === data.id));
|
const list = $derived(overview.lists.find((l) => l.id === data.id));
|
||||||
const listFields = $derived(listFieldsFor(overview.fields, data.id));
|
const listFields = $derived(listFieldsFor(overview.fields, data.id));
|
||||||
const listItems = $derived(listItemsFor(overview.items, data.id));
|
const listItems = $derived(listItemsFor(overview.items, data.id));
|
||||||
|
const valuesByItem = $derived(groupByKey(overview.values, (v) => v.itemId));
|
||||||
|
|
||||||
let page = $state(1);
|
let page = $state(1);
|
||||||
let pageSize = $state(24);
|
let pageSize = $state(24);
|
||||||
@@ -91,7 +92,7 @@
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{#each pageItems as item (item.id)}
|
{#each pageItems as item (item.id)}
|
||||||
{@const itemValues = itemValuesFor(overview.values, item.id)}
|
{@const itemValues = valuesByItem.get(item.id) ?? []}
|
||||||
<tr class="border-t border-border">
|
<tr class="border-t border-border">
|
||||||
<td class="py-2 pl-3 font-mono text-xs text-muted-fg">{item.id.slice(0, 8)}…</td>
|
<td class="py-2 pl-3 font-mono text-xs text-muted-fg">{item.id.slice(0, 8)}…</td>
|
||||||
{#each listFields as f (f.id)}
|
{#each listFields as f (f.id)}
|
||||||
@@ -103,16 +104,18 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<Pagination
|
<div class="mt-4">
|
||||||
{page}
|
<Pagination
|
||||||
{pageSize}
|
{page}
|
||||||
pageLength={pageItems.length}
|
{pageSize}
|
||||||
totalLength={listItems.length}
|
pageLength={pageItems.length}
|
||||||
onPaging={(e) => {
|
totalLength={listItems.length}
|
||||||
page = e.page;
|
onPaging={(e) => {
|
||||||
pageSize = e.pageSize;
|
page = e.page;
|
||||||
}}
|
pageSize = e.pageSize;
|
||||||
/>
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
import adapter from '@sveltejs/adapter-static';
|
|
||||||
|
|
||||||
/** @type {import('@sveltejs/kit').Config} */
|
|
||||||
const config = {
|
|
||||||
kit: {
|
|
||||||
// Static SPA build: the Go server serves this output and falls back to
|
|
||||||
// index.html for any path so SvelteKit's client-side router can take over.
|
|
||||||
adapter: adapter({
|
|
||||||
fallback: 'index.html',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
+17
-1
@@ -3,6 +3,7 @@ import path from 'node:path';
|
|||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import { sveltekit } from '@sveltejs/kit/vite';
|
import { sveltekit } from '@sveltejs/kit/vite';
|
||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
|
import adapter from '@sveltejs/adapter-static';
|
||||||
|
|
||||||
// Real installed frontend dependency versions for the About page, resolved from
|
// Real installed frontend dependency versions for the About page, resolved from
|
||||||
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
||||||
@@ -29,7 +30,21 @@ const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) =
|
|||||||
});
|
});
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tailwindcss(), sveltekit()],
|
plugins: [
|
||||||
|
tailwindcss(),
|
||||||
|
sveltekit({
|
||||||
|
// SvelteKit 3 removed the $lib alias; keep it pointing at src/lib so imports stay unchanged.
|
||||||
|
alias: { $lib: 'src/lib' },
|
||||||
|
// Static SPA build: the Go server serves this output and falls back to
|
||||||
|
// index.html for any path so SvelteKit's client-side router can take over.
|
||||||
|
adapter: adapter({
|
||||||
|
fallback: 'index.html',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
resolve: {
|
||||||
|
preserveSymlinks: true,
|
||||||
|
},
|
||||||
define: {
|
define: {
|
||||||
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||||
},
|
},
|
||||||
@@ -38,6 +53,7 @@ export default defineConfig({
|
|||||||
proxy: {
|
proxy: {
|
||||||
'/web': 'http://localhost:8080',
|
'/web': 'http://localhost:8080',
|
||||||
'/health': 'http://localhost:8080',
|
'/health': 'http://localhost:8080',
|
||||||
|
'/api': 'http://localhost:8080',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Keep the shared header full width when the wide-page setting is on. The `data-wide-layout` rule no longer narrows `.sc-header` with `calc(100% - 2rem)` and auto margins, which left a gap on both sides of the header. Only `.sc-main` widens now, so the header looks the same in every application whether or not the page is wide.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
`Header` no longer renders the primary navigation tab, or the mobile menu toggle, when `navItems` has only one entry. A lone item is just the app's home page, so projects like OmniLogger and OutdoorGames no longer show a single "Dashboard" tab in the header.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix `MediaPlayer` controls not fading away during playback when the pointer stays still. Pointer movement now counts as activity anywhere over the player, including over a picture drawn on a canvas stacked above the frame, so the controls fade after a few seconds and come back when the pointer moves over the player again. The `autoHideControls` doc comment now describes its real behavior: `true` (the default) fades the controls, `false` keeps them visible.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Open the mobile navigation menu as an overlay below the header instead of inserting it into the header row. Opening the menu no longer pushes the page content down, and long menus scroll within the viewport.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/node-backend": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Adds `LogShipper`, `createLogShipperFromEnv` and `mirrorConsole` (`src/logshipper.js`): batches log entries and sends them to OmniLogger's `/api/logs`. Shipping is enabled only when `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set, and otherwise the factory returns `null`.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
`Pagination` no longer adds a 1rem top margin, so it sits evenly inside whichever container holds it. Its page-size select now shows its arrow at the same text size as the count, the controls line up with the select, and on phones the count sits on its own centred line above the page size and buttons.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix the primary color chosen in `PrimaryColorPicker` not reaching the app's UI. The choice is now applied through a stylesheet that also targets `[data-theme]` elements, such as the `AppShell` root, so it takes effect immediately everywhere instead of being hidden by those elements' own theme tokens. The picker also sets the `--sc-*` primary, accent, and hover tokens the shared components read.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Remove the `PageHeader` title card. `AppShell` no longer renders a per-page title/description card, and its `showPageHeader` and `pageHeaderActions` props are gone, as are the `PageHeader` export and the `.sc-page-header` styles. Buttons or status pills that lived in the title card now belong in a card inside the page content.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": minor
|
||||||
|
---
|
||||||
|
|
||||||
|
`UserManagement` is removed from the package, along with its `UserListRequest`, `UserCreateRequest`, `UserUpdateRequest`, and `UserDeleteRequest` types and its `.sc-user-*` styles. The component was only used by AuthGuard, which now owns a copy in `features/users`. Applications that still render it should keep their own copy or build their own user table. `KnownRole`, `ManagedUser`, `UserCreateInput`, and `UserUpdateInput` remain exported.
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
"@gabriel20xx/web-ui": minor
|
|
||||||
---
|
|
||||||
|
|
||||||
`UserManagement` accepts an optional `projects` prop (`KnownProject[]`): when present, each account gets a per-project login-access picker (checkboxes in the edit row, a summary in the read-only row) and `onUpdate` receives a `projects: string[]` field. Only AuthGuard's own admin UI passes this prop today; every other consumer is unaffected.
|
|
||||||
@@ -26,6 +26,17 @@ jobs:
|
|||||||
go-version-file: backend/go.mod
|
go-version-file: backend/go.mod
|
||||||
cache: false
|
cache: false
|
||||||
|
|
||||||
|
- name: Check formatting and vet the Go module
|
||||||
|
working-directory: backend
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
mapfile -d '' go_files < <(find . -type f -name '*.go' -print0)
|
||||||
|
if ((${#go_files[@]})); then
|
||||||
|
test -z "$(gofmt -l "${go_files[@]}")"
|
||||||
|
fi
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
- name: Test Go module
|
- name: Test Go module
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
run: go test ./...
|
run: go test ./...
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ jobs:
|
|||||||
npm ci
|
npm ci
|
||||||
npm run build
|
npm run build
|
||||||
|
|
||||||
|
- name: Run the lint and test checks that gate pull requests
|
||||||
|
run: |
|
||||||
|
npm run lint
|
||||||
|
npm test
|
||||||
|
|
||||||
- name: Configure Gitea npm registry
|
- name: Configure Gitea npm registry
|
||||||
env:
|
env:
|
||||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
|
|
||||||
|
- name: Run the lint and test checks that gate pull requests
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python -m pip install --disable-pip-version-check --upgrade pip ruff -e "packages/python-backend[fastapi]"
|
||||||
|
ruff check packages/python-backend/src packages/python-backend/tests
|
||||||
|
python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
|
||||||
|
|
||||||
- name: Build and publish package
|
- name: Build and publish package
|
||||||
env:
|
env:
|
||||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
|||||||
Regular → Executable
+6
@@ -1,6 +1,12 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Consumer synchronization is opt-in. It commits into every registered consumer repository, so it
|
||||||
|
# runs only for a commit made with SHARED_SYNC_COMMIT=1 in the environment.
|
||||||
|
if [ "${SHARED_SYNC_COMMIT:-0}" != "1" ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
repo_root="$(git rev-parse --show-toplevel)"
|
repo_root="$(git rev-parse --show-toplevel)"
|
||||||
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
||||||
|
|
||||||
|
|||||||
Vendored
+6
@@ -43,8 +43,14 @@ jobs:
|
|||||||
cache-dependency-path: package-lock.json
|
cache-dependency-path: package-lock.json
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
- name: Check the generated root stylesheet is current
|
||||||
|
run: git diff --exit-code -- shared-styles.css
|
||||||
|
- name: Check for skipped tests
|
||||||
|
run: npm run media:enforce:no-skipped-tests
|
||||||
- name: Run Node/Svelte lint checks
|
- name: Run Node/Svelte lint checks
|
||||||
run: npm run lint
|
run: npm run lint
|
||||||
|
- name: Check Prettier formatting
|
||||||
|
run: npm run format:check
|
||||||
|
|
||||||
go:
|
go:
|
||||||
name: Lint (Go)
|
name: Lint (Go)
|
||||||
|
|||||||
+155
@@ -0,0 +1,155 @@
|
|||||||
|
name: Security
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ['**']
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
schedule:
|
||||||
|
# Daily, for the Trivy job, so advisories published after the last push still get reported.
|
||||||
|
- cron: '23 5 * * *'
|
||||||
|
# Weekly, for the secrets and code jobs. Each job's if: condition picks the entry that runs it.
|
||||||
|
- cron: '23 5 * * 1'
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
secrets:
|
||||||
|
name: Secrets (gitleaks)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
# Full history, so a secret that was committed and later removed is still found.
|
||||||
|
fetch-depth: 0
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: stable
|
||||||
|
# gitleaks runs at a pinned version. go run checks the module against the Go checksum
|
||||||
|
# database. Known false positives go in .gitleaks.toml at the repo root, which gitleaks reads
|
||||||
|
# on its own.
|
||||||
|
- name: Scan git history for secrets
|
||||||
|
run: go run github.com/zricethezav/gitleaks/v8@v8.30.1 git --no-banner --redact --exit-code 1 .
|
||||||
|
|
||||||
|
code:
|
||||||
|
name: Code (Semgrep)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- name: Install Semgrep
|
||||||
|
run: pip install semgrep==1.182.1
|
||||||
|
# Fails on ERROR findings from Semgrep's default rules. WARNING findings are not gated.
|
||||||
|
- name: Scan code
|
||||||
|
run: semgrep scan --config p/default --severity ERROR --error --metrics=off .
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
name: Dependencies (Trivy)
|
||||||
|
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * *'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
submodules: false
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- name: Install uv
|
||||||
|
run: pip install uv==0.13.5
|
||||||
|
- name: Install Trivy
|
||||||
|
# Always the newest Trivy release. The version is read from the release redirect when the job
|
||||||
|
# runs, and the download is checked against that release's published checksums. The
|
||||||
|
# aquasecurity/trivy-action version tags were repointed to malicious commits in March 2026,
|
||||||
|
# so that action is not used.
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
latest_url=$(curl --fail --location --silent --show-error --retry 5 --retry-delay 2 \
|
||||||
|
--output /dev/null --write-out '%{url_effective}' https://github.com/aquasecurity/trivy/releases/latest)
|
||||||
|
TRIVY_VERSION=${latest_url##*/tag/v}
|
||||||
|
if [[ ! "$TRIVY_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "Could not read the latest Trivy version from $latest_url" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Installing Trivy $TRIVY_VERSION"
|
||||||
|
archive="trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||||
|
base_url="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}"
|
||||||
|
|
||||||
|
curl --fail --location --retry 5 --retry-delay 2 \
|
||||||
|
--output "$RUNNER_TEMP/$archive" "$base_url/$archive"
|
||||||
|
curl --fail --location --retry 5 --retry-delay 2 \
|
||||||
|
--output "$RUNNER_TEMP/trivy_checksums.txt" "$base_url/trivy_${TRIVY_VERSION}_checksums.txt"
|
||||||
|
|
||||||
|
(cd "$RUNNER_TEMP" && grep -F " $archive" trivy_checksums.txt > trivy_checksum.txt \
|
||||||
|
&& sha256sum -c trivy_checksum.txt)
|
||||||
|
|
||||||
|
tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" trivy
|
||||||
|
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
|
||||||
|
"$RUNNER_TEMP/trivy" --version
|
||||||
|
# Trivy audits lockfiles and skips bare manifests. For each manifest with no lockfile in its
|
||||||
|
# own folder or any parent folder, resolve one here so its dependencies get scanned. These
|
||||||
|
# lockfiles are made only for this run and are not committed.
|
||||||
|
- name: Resolve manifests that have no lockfile
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
has_lockfile() {
|
||||||
|
local dir=$1
|
||||||
|
shift
|
||||||
|
while true; do
|
||||||
|
for lockfile in "$@"; do
|
||||||
|
if [ -f "$dir/$lockfile" ]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ "$dir" = "." ]; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
dir=$(dirname "$dir")
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
while IFS= read -r -d '' manifest; do
|
||||||
|
dir=$(dirname "$manifest")
|
||||||
|
if ! has_lockfile "$dir" package-lock.json yarn.lock pnpm-lock.yaml; then
|
||||||
|
echo "Resolving npm dependencies in $dir"
|
||||||
|
(cd "$dir" && npm install --package-lock-only --ignore-scripts --no-audit --no-fund)
|
||||||
|
fi
|
||||||
|
done < <(find . -name node_modules -prune -o -name package.json -print0)
|
||||||
|
|
||||||
|
while IFS= read -r -d '' manifest; do
|
||||||
|
dir=$(dirname "$manifest")
|
||||||
|
if ! has_lockfile "$dir" uv.lock poetry.lock Pipfile.lock; then
|
||||||
|
echo "Resolving Python dependencies in $dir"
|
||||||
|
(cd "$dir" && uv lock)
|
||||||
|
fi
|
||||||
|
done < <(find . -name node_modules -prune -o -name .venv -prune -o -name pyproject.toml -print0)
|
||||||
|
# Fails on HIGH and CRITICAL vulnerabilities that have a fixed version. Vulnerabilities with no
|
||||||
|
# fix are left out, because nothing can be changed to clear them. Development dependencies are
|
||||||
|
# included, since build and test tooling runs in CI.
|
||||||
|
# --offline-scan: Maven Central rate-limits the lookups Trivy makes for pom.xml, so Maven
|
||||||
|
# dependencies are read from their declared versions only. Transitive ones are not resolved.
|
||||||
|
- name: Scan dependencies for known vulnerabilities
|
||||||
|
run: >-
|
||||||
|
trivy fs --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --include-dev-deps
|
||||||
|
--offline-scan --exit-code 1 --timeout 15m .
|
||||||
Vendored
+51
-2
@@ -54,6 +54,26 @@ jobs:
|
|||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
|
# A throwaway PostgreSQL for the tests that need a real database (the auth store, the
|
||||||
|
# platform-user SQL, the media routes and the migrate package). Without these two
|
||||||
|
# variables those tests skip themselves.
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: scratch
|
||||||
|
ports:
|
||||||
|
- 5432/tcp
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U postgres"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
|
||||||
|
SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -62,8 +82,16 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version-file: backend/go.mod
|
go-version-file: backend/go.mod
|
||||||
cache: true
|
cache: true
|
||||||
|
# -p 1 runs one package at a time, because the database tests share one scratch database.
|
||||||
- name: Run Go tests
|
- name: Run Go tests
|
||||||
run: go test ./...
|
shell: bash
|
||||||
|
run: |
|
||||||
|
# Gitea Actions runs jobs in a container, where the service is reached by its label.
|
||||||
|
if [ "${GITEA_ACTIONS:-}" = "true" ]; then
|
||||||
|
export DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
|
||||||
|
export SHARED_TEST_DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
|
||||||
|
fi
|
||||||
|
go test -p 1 ./...
|
||||||
|
|
||||||
python:
|
python:
|
||||||
name: Test (Python)
|
name: Test (Python)
|
||||||
@@ -78,6 +106,27 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- name: Install package
|
- name: Install package
|
||||||
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]"
|
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi,test]"
|
||||||
- name: Run Python tests
|
- name: Run Python tests
|
||||||
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
|
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
|
||||||
|
|
||||||
|
java:
|
||||||
|
name: Test (Java)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: packages/java-backend
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up JDK
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '17'
|
||||||
|
cache: maven
|
||||||
|
cache-dependency-path: packages/java-backend/pom.xml
|
||||||
|
- name: Run Java tests
|
||||||
|
run: mvn -B test
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# gitleaks configuration. gitleaks reads this file from the repository root.
|
||||||
|
|
||||||
|
[extend]
|
||||||
|
useDefault = true
|
||||||
|
|
||||||
|
[allowlist]
|
||||||
|
description = "Test fixtures that contain placeholder credentials, not real secrets"
|
||||||
|
paths = [
|
||||||
|
'''(^|/)(tests?|__tests__)/''',
|
||||||
|
'''_test\.go$''',
|
||||||
|
'''\.test\.[jt]sx?$''',
|
||||||
|
'''\.spec\.[jt]sx?$''',
|
||||||
|
'''(^|/)test_[^/]*\.py$''',
|
||||||
|
'''Test\.java$''',
|
||||||
|
'''(^|/)contract/auth-contract\.json$''',
|
||||||
|
]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
**/dist/
|
||||||
|
**/.svelte-kit/
|
||||||
|
**/node_modules/
|
||||||
|
backend/
|
||||||
|
packages/java-backend/
|
||||||
|
packages/python-backend/
|
||||||
|
shared-styles.css
|
||||||
|
package-lock.json
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 120,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"plugins": ["prettier-plugin-svelte"],
|
||||||
|
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Semgrep skips test code and fixtures. Tests hold placeholder credentials on purpose.
|
||||||
|
# auth-contract.json holds bcrypt hashes of test passwords shared by every service's tests.
|
||||||
|
auth-contract.json
|
||||||
|
test/
|
||||||
|
tests/
|
||||||
|
__tests__/
|
||||||
|
*_test.go
|
||||||
|
*.test.js
|
||||||
|
*.test.ts
|
||||||
|
*.test.tsx
|
||||||
|
*.spec.js
|
||||||
|
*.spec.ts
|
||||||
|
test_*.py
|
||||||
|
*Test.java
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Performance Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
|
||||||
|
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
|
||||||
|
- **Updated:** 2026-10-20 — the two-second session-validation cache remains enabled by owner decision; code comments and README now state its revocation window and same-client logout behavior.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
|
| High | 1 | 1 | 0 | 0 |
|
||||||
|
| Medium | 4 | 4 | 0 | 0 |
|
||||||
|
| Low | 4 | 0 | 0 | 4 |
|
||||||
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
|
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High** · Fixed
|
||||||
|
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
|
||||||
|
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
|
||||||
|
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
|
||||||
|
- **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the `playAt`, `playAtLocalMs` and `capturedAtMs` maps are trimmed to `maxSyncSessions` (1000) after each `sync:update` write, and `ServeWebSocket` refuses connections past `maxSyncConnections` (1000) by closing with 1013 Try Again Later. Over the cap, entries are dropped arbitrarily, as `states` already is, instead of being removed on last-peer exit; per-IP and per-peer message-rate limits are not added. Behaviour change: an 1001st concurrent websocket is closed at once. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
|
### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session)
|
||||||
|
- **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session.
|
||||||
|
- **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session.
|
||||||
|
- **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Broadcast` marshals once and queues the message on a buffered per-peer channel without waiting on the network, a peer whose queue is full is dropped, and each peer now has a message-rate limit (120 messages per second; a faster client is closed with status 1008). Verifying it with a real stuck peer found that dropping the peer still blocked the caller: `conn.Close` waits up to five seconds for a close frame that a stuck peer never sends, and `Broadcast` (so `PUT /sync` and every other peer's read loop) ran that inline. `peer.drop` now closes the peer's `done` channel and runs the close handshake in its own goroutine, used by `Broadcast` and by the targeted send in `handleSyncUpdate`; a test fails without it (five seconds instead of microseconds). Behaviour change: none for well-behaved clients; a client sending over 120 messages in one second is disconnected. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/mediacore/mediacore.go`, `backend/mediacore/routes_test.go`.
|
||||||
|
|
||||||
|
### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction)
|
||||||
|
- **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids.
|
||||||
|
- **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access).
|
||||||
|
- **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `findMedia` and the thumbnail join match `media_key` and only a canonical decimal `id` (`canonicalMediaID`), so the id comparison no longer casts the column. Playlist reorder is one `UPDATE ... FROM unnest(...)` in a transaction, its error is checked, and requests above 10,000 ids are refused. Not measured: no database was available, so the `EXPLAIN` check on a populated table is still needed. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`.
|
||||||
|
|
||||||
|
### P-004 · Password hashing blocks the event loop · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module)
|
||||||
|
- **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU.
|
||||||
|
- **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem.
|
||||||
|
- **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Node exports `hashPasswordAsync` and `verifyPasswordAsync` (async PBKDF2), and Python exports `hash_password_async` and `verify_password_async` (bcrypt in `asyncio.to_thread`). The sync helpers are unchanged, so consumers that hash inside request handlers must call the async variants. Files: `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/__init__.py`.
|
||||||
|
|
||||||
|
### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request)
|
||||||
|
- **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation.
|
||||||
|
- **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls.
|
||||||
|
- **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Go proxy caches the login-required flag, and the Go AuthGuard client caches validation results, for two seconds, positive and negative, bounded at 10,000 entries and keyed by the SHA-256 of the token. The Node and Python AuthGuard clients now cache `validate` the same way, drop the entry on `logout`, and clear the cache when the base URL changes. Behaviour change: a session revoked elsewhere can still validate for up to two seconds. Files: `backend/auth/proxy.go`, `backend/authclient/client.go`, `backend/authclient/validation_cache.go`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `packages/python-backend/src/shared_backend/authclient.py`, `packages/python-backend/tests/test_authclient.py`.
|
||||||
|
|
||||||
|
### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer)
|
||||||
|
- **Description:** The Python client performs blocking `urllib` calls through `asyncio.to_thread`, which uses the event loop's default executor shared with other `to_thread` users, and opens a new connection per call. In Node the abort timer is set at line 177; the review pass reports it is cleared once headers arrive, which would leave the body read without a deadline (needs verification at `authclient.js:186-188`).
|
||||||
|
- **Impact:** A slow AuthGuard can exhaust executor threads needed elsewhere in the process, and a stalled response body can hang a request.
|
||||||
|
- **Recommendation:** Use a pooled async HTTP client (httpx or aiohttp in Python; undici or a reused agent in Node), and keep the timeout active until the body is fully read, or apply an overall deadline.
|
||||||
|
|
||||||
|
### P-007 · Admin user operations over-fetch and make sequential calls; the Go store lists all users · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:644-652` (updating one user lists all users to find it), `packages/python-backend/src/shared_backend/authproxy.py:406-416` (`/status` makes two sequential AuthGuard calls), `backend/auth/store.go:294` (`ListUsers` returns every row with no limit)
|
||||||
|
- **Description:** After a user update the Python handler fetches the entire user list to locate one row. The status endpoint makes two independent AuthGuard calls one after the other. The Go store's `ListUsers` has no `LIMIT`, and the client list calls have no pagination.
|
||||||
|
- **Impact:** Latency and memory grow with the number of accounts.
|
||||||
|
- **Recommendation:** Add a get-by-id method (or return the updated record from the update call), run independent calls concurrently, and add pagination to the list endpoints.
|
||||||
|
|
||||||
|
### P-008 · CarrierNode client has no transport timeout; the media proxy depends on caller deadlines · **Low**
|
||||||
|
- **Location:** `backend/carriernodeclient/carriernodeclient.go:28-30` (package-level `http.Client` with no `Timeout`; the comment says callers set context deadlines), `backend/carriernodeclient/carriernodeclient.go:171-213` (`Proxy` uses the incoming request context), `backend/carriernodeclient/carriernodeclient.go:510-522` (thumbnail HEAD probe on the same client)
|
||||||
|
- **Description:** The shared client is deliberately timeout-free so that large media streams are not cut off. Control calls and the proxy paths rely on each caller to attach a deadline. Where a caller does not, a hung CarrierNode holds the request open indefinitely.
|
||||||
|
- **Impact:** Goroutines and client connections can be tied up by a slow upstream. The severity depends on consumers' server-level timeouts (needs verification).
|
||||||
|
- **Recommendation:** Set a `ResponseHeaderTimeout` on the transport so that stalled upstreams fail quickly while streams still work. Attach deadlines to control calls, and document the requirement for callers that use the proxy paths.
|
||||||
|
|
||||||
|
### P-009 · Status widget polls two endpoints every 15 seconds regardless of tab visibility · **Low**
|
||||||
|
- **Location:** `packages/web-ui/src/lib/components/StatusWidget.svelte:76-79` (`onMount` starts a 15 s interval that issues `/healthz` and `/ready` requests)
|
||||||
|
- **Description:** Each mounted `StatusWidget` polls both probes on a fixed interval, with no check for `document.hidden`. Consumers may mount the widget on several pages or in several open tabs. The cleanup on unmount is correct.
|
||||||
|
- **Impact:** Background tabs and multiple widgets add steady load to every backend that exposes these probes.
|
||||||
|
- **Recommendation:** Pause polling while `document.hidden` is true and refresh on `visibilitychange`. Consider a longer interval for `/ready`, which may query the database.
|
||||||
|
|
||||||
|
### P-010 · Info: the root `prepare` script builds on install, and CI runs the build twice · **Info**
|
||||||
|
- **Location:** `package.json` (`prepare` runs `npm run build` and `build-root-styles`; `test` runs `npm run build` before `test:node-backend`), `.github/workflows/tests.yml` (`npm ci` followed by `npm test`)
|
||||||
|
- **Description:** `npm ci` runs the root `prepare` script, which builds the web-ui package, and then `npm test` builds it again.
|
||||||
|
- **Impact:** Extra CI time on every run. No runtime impact.
|
||||||
|
- **Recommendation:** Either skip the duplicate build in `test`, or move the build out of `prepare` into an explicit CI step.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
|
||||||
|
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
|
||||||
|
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
|
||||||
|
- **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python, web-ui and Go checks passed; Java checks were unavailable because no JDK or Maven is installed.
|
||||||
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# Code Quality Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
|
||||||
|
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python, web-ui and Go suites/checks, web-ui package build and checks were run during this continuation; Java tools remain unavailable.
|
||||||
|
- **Updated:** 2026-10-20 — Q-008 fixed in the working tree: all password writers use bcrypt cost 12, legacy PBKDF2 verifies and upgrades after a successful login, and shared contract fixtures cover all runtimes. Node tests, web-ui tests, package build, Svelte check and Node syntax check passed.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count |
|
||||||
|
|---|---:|
|
||||||
|
| Critical | 0 |
|
||||||
|
| High | 0 |
|
||||||
|
| Medium | 9 |
|
||||||
|
| Low | 7 |
|
||||||
|
| Info | 0 |
|
||||||
|
|
||||||
|
The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-test code, no `any` or `@ts-ignore` in the web-ui, and parameterised SQL throughout. The weak spots are operational: several scripts and workflows no longer match the repository layout, Java and most Go packages are not tested in CI, the publish pipeline skips the checks that exist for pull requests, and the four AuthGuard clients have drifted apart in behaviour.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error)
|
||||||
|
- **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice.
|
||||||
|
- **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated.
|
||||||
|
- **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Database` attaches a logging `error` listener to the pool, so a failed idle client is logged instead of thrown. `query()` retries after a transient error only for plain read-only SELECTs, and a caller can opt a statement in with `{ retry: true }`. Behaviour change: a write that hits a transient error is no longer retried by default. Files: `packages/node-backend/src/db.js`, `packages/node-backend/test/db.test.js`.
|
||||||
|
|
||||||
|
### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium** · Fixed
|
||||||
|
- **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts)
|
||||||
|
- **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI.
|
||||||
|
- **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout.
|
||||||
|
- **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `lint-all.mjs` and `lint-all-json.mjs` point at `packages/web-ui`, `upgrade-deps.mjs` names the real local packages, and `enforce-no-skipped-tests.mjs` scans `packages/web-ui/src` and `packages/node-backend/test` and fails when it finds no files. The no-skipped-tests check now runs in `lint.yml`; `lint-all` is still not wired into CI because web-ui has no ESLint config (Q-009). Files: `scripts/media/lint-all.mjs`, `scripts/media/lint-all-json.mjs`, `scripts/media/upgrade-deps.mjs`, `scripts/media/enforce-no-skipped-tests.mjs`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
|
### Q-003 · Java package has tests, but no CI job runs them · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven)
|
||||||
|
- **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository.
|
||||||
|
- **Impact:** Java changes can break without detection.
|
||||||
|
- **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `tests.yml` has a `java` job that runs `mvn -B test` on JDK 17 in `packages/java-backend`. Not compiled or run: no JDK or Maven is available here, so the workflow and the Java test classes were checked by reading only. Files: `.github/workflows/tests.yml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
|
### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only)
|
||||||
|
- **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass).
|
||||||
|
- **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests.
|
||||||
|
- **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`).
|
||||||
|
- **Status:** Fixed 2026-10-19 — every gap the finding names now has tests. `syncsocket`: connection cap, origin handling, identity, the per-peer message rate (`allowMessage`, and a flooding client is closed with 1008), and a stuck peer being dropped without holding up `Broadcast`. `logshipper`: levels, the local line, ID scrubbing, batching, the bounded buffer, flush and close, and a failing sink never failing the caller. `config` and `migrate`: the environment helpers, the argument and connection errors, and real goose runs. `mediacore`: the auth gate on every `Require` route, the sync routes (validation, clamping, broadcast to the session only), and, against PostgreSQL, stream and thumbnail (hidden media, escaped and refused paths), likes, saves, views, tags, and playlists including reorder and ownership. `auth`: handler tests for Login, Signup, Logout, UpdateMe, the managed-user routes, the TOTP routes, the gating middlewares and `Me` against a fake AuthGuard, the platform-user SQL against PostgreSQL, and the new contract file. Writing them found and fixed two defects: `Broadcast` could block for five seconds in the close handshake of a stuck peer (see P-002), and `GET /media/{id}/tags` always answered an empty list because the query's `tag` column was ambiguous (`backend/mediacore/mediacore.go`). The PostgreSQL tests skip unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` names a scratch database; `.github/workflows/tests.yml` now provides one to the Go job (`go test -p 1 ./...`). Files: `backend/syncsocket/syncsocket_test.go`, `backend/logshipper/shipper_test.go`, `backend/config/config_test.go`, `backend/migrate/migrate_test.go`, `backend/mediacore/routes_test.go`, `backend/mediacore/routes_db_test.go`, `backend/auth/proxy_handlers_test.go`, `backend/auth/platform_users_integration_test.go`, `backend/auth/store_integration_test.go`, `backend/auth/contract_test.go`, `backend/auth/proxy_test.go`, `.github/workflows/tests.yml`.
|
||||||
|
|
||||||
|
### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium** · Fixed
|
||||||
|
- **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept)
|
||||||
|
- **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output.
|
||||||
|
- **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified.
|
||||||
|
- **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the build's token-import filter matches both quote styles and an optional semicolon, so the package import is stripped. Running the build reproduces `shared-styles.css` byte for byte, and `lint.yml` now runs `git diff --exit-code -- shared-styles.css` after `npm ci`. Files: `scripts/build-root-styles.mjs`, `shared-styles.css`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
|
### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium** · Fixed
|
||||||
|
- **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook)
|
||||||
|
- **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`).
|
||||||
|
- **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here.
|
||||||
|
- **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the post-commit hook runs the consumer sync only when `SHARED_SYNC_COMMIT=1` is set for that commit, and `sync-consumers.ps1` copies a dirty destination to a temp backup before `-Force` overwrites it. Behaviour change: an ordinary commit no longer syncs or commits into consumer repositories. Not run: PowerShell is not installed here, so the script change is unparsed. Files: `.githooks/post-commit`, `scripts/sync-consumers.ps1`, `scripts/install-sync-hook.ps1`.
|
||||||
|
|
||||||
|
### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium** · Fixed
|
||||||
|
- **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt)
|
||||||
|
- **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time.
|
||||||
|
- **Impact:** Broken or unlinted code can reach the shared registries that projects consume.
|
||||||
|
- **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run.
|
||||||
|
- **Status:** Fixed 2026-10-19 — each publish workflow runs the checks that gate pull requests before it uploads: npm runs `npm run lint` and `npm test`, Python runs ruff and the unittest suite, and Go runs gofmt and `go vet` before `go test`. Not run: no Gitea runner is available here. The Go gofmt step will fail until `backend/authclient/client.go` and `backend/syncsocket/syncsocket.go` are gofmt-clean; their in-progress hunks were not reformatted in this pass. Files: `.gitea/workflows/publish-npm.yml`, `.gitea/workflows/publish-python.yml`, `.gitea/workflows/publish-go.yml`.
|
||||||
|
|
||||||
|
### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium** · Open
|
||||||
|
- **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python
|
||||||
|
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
||||||
|
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
||||||
|
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
||||||
|
- **Status:** Fixed 2026-10-20 — Node now writes the same prefixed bcrypt cost-12 scheme as Go and Python, and each runtime verifies current/legacy bcrypt plus both legacy Node PBKDF2 formats. Successful legacy verification returns an upgraded hash; AuthGuard conditionally persists that upgrade after a successful login. Long legacy PBKDF2 passwords use the explicit `bcrypt-sha256$` scheme to avoid bcrypt truncation, while new passwords over 72 bytes are rejected. The Java AuthClient does not create or verify stored password hashes. Node also depends on `bcryptjs` to share the scheme. The shared contract covers current, low-cost, malformed, legacy and over-limit cases. Files: `backend/auth/password.go`, `backend/auth/contract_test.go`, `Central/AuthGuard/internal/httpapi/{auth.go,server.go,server_test.go}`, `packages/node-backend/{package.json,src/auth.js,test/auth.test.js,test/contract.test.js}`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/{test_core.py,test_contract.py}`, `contract/auth-contract.json`.
|
||||||
|
|
||||||
|
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
|
||||||
|
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
||||||
|
- **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified.
|
||||||
|
- **Impact:** Style drift and behavioural regressions in a UI library that several applications consume.
|
||||||
|
- **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers.
|
||||||
|
- **Status:** Fixed 2026-10-19 — ESLint (flat config `eslint.config.js`: `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`) now lints `packages/web-ui`, `packages/node-backend` and `scripts` with `--max-warnings=0`; it is part of `npm run lint` (so of `lint.yml` and the publish gate) and each package has a `lint` script. Prettier 3 with `prettier-plugin-svelte` is configured in `.prettierrc.json`, with `npm run format` and `format:check` (also a `lint.yml` step). `packages/web-ui` has a Vitest and `@testing-library/svelte` suite in `packages/web-ui/tests` (27 tests: `AuthPage` login, two-factor challenge, setup and reset flows; the notification store and `NotificationStack`; the primary-color helpers), run by `npm run test:web-ui`, which `npm test` and `release` now include. All of it is root `devDependencies` (`eslint`, `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`, `globals`, `prettier`, `prettier-plugin-svelte`, `vitest`, `jsdom`, `@testing-library/svelte`; no way to fix the finding without them), so `packages/web-ui/package.json`'s dependencies and the consumers' lockfile entries for it are unchanged; only a `lint` and a `test` script were added there. The existing code passes ESLint without code changes beyond three unused bindings in `scripts/media`; three Svelte rules that would change how shipped components render or hold state (`require-each-key`, `prefer-writable-derived`, `prefer-svelte-reactivity`) are turned off with a comment. Not done: Prettier is enforced only on the files written to its style (44 older files differ from it and were not reformatted, to keep the mirrored diff small), and Stylelint was not added. Files: `eslint.config.js`, `.prettierrc.json`, `.prettierignore`, `package.json`, `package-lock.json`, `packages/web-ui/{package.json,vitest.config.ts,tests/}`, `packages/node-backend/package.json`, `scripts/media/{lint-all,lint-all-json,list-skipped-tests,enforce-no-skipped-tests}.mjs`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
|
### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging)
|
||||||
|
- **Description:** An AuthGuard outage looks like a wrong authenticator code, so operators and users cannot tell the two apart. Logout clears the browser cookie even when the upstream call fails, which can leave a valid server-side session behind.
|
||||||
|
- **Impact:** Harder debugging, misleading user feedback, and possible sessions that survive a logout.
|
||||||
|
- **Recommendation:** Catch the specific error classes. Return 502 or 503 for upstream failures, log transport errors at warning level, and clear local cookies only after the upstream logout succeeds or fails in a known way.
|
||||||
|
|
||||||
|
### Q-011 · Node version drift between publish and CI · **Low**
|
||||||
|
- **Location:** `.gitea/workflows/publish-npm.yml:24` (`node-version: 22`), `.github/workflows/lint.yml` and `.github/workflows/tests.yml` (`node-version: '24'`), `packages/node-backend/package.json` (`engines` `>=20`)
|
||||||
|
- **Description:** The packages are published from a build on Node 22, while lint and tests run on Node 24, and the package claims support from Node 20.
|
||||||
|
- **Impact:** The published artifacts are built with a different toolchain from the one that is tested, and the supported range is not exercised.
|
||||||
|
- **Recommendation:** Use one Node version for build and publish that matches what CI tests, and add a matrix entry for the minimum supported version.
|
||||||
|
|
||||||
|
### Q-012 · Package export maps are incomplete, and the root `.` export points at the README · **Low**
|
||||||
|
- **Location:** `package.json:19` (`"." : "./README.md"`), `package.json:28-33` (no `./node-backend/coreconfig` export, though the file ships in `files`), `packages/node-backend/package.json` `exports` (no `./totp` or `./authclient`, although both files exist and are re-exported from `src/index.js`), `packages/python-backend/src/shared_backend/__init__.py` (does not re-export `APIError`)
|
||||||
|
- **Description:** The root package's main entry resolves to a documentation file. Subpath imports for `totp` and `authclient` fail with `ERR_PACKAGE_PATH_NOT_EXPORTED` even though the modules exist, and the root export map omits `coreconfig`.
|
||||||
|
- **Impact:** Consumers cannot import documented modules, and tooling that resolves the package main gets the README.
|
||||||
|
- **Recommendation:** Point `.` at a real index module or remove it, add the missing subpath exports, and add a smoke test that imports every exported path.
|
||||||
|
|
||||||
|
### Q-013 · Versioning and changeset hygiene · **Low**
|
||||||
|
- **Location:** `.changeset/config.json:11` (ignores `@gabriel20xx/shared-workspace`, which does not exist; the root package is `@gabriel20xx/shared-code`), `packages/java-backend/pom.xml:6` (`0.1.0`, while the npm and Python packages are `0.1.1`), `packages/python-backend/pyproject.toml` (`0.1.1`, versioned by hand)
|
||||||
|
- **Description:** Changesets cover only the npm packages. Python and Java versions are maintained by hand, and recent changes to those packages (for example commits `f5a20b7`, `de9b599` and `97a5ecd`) have no changeset. The ignore entry names a package that does not exist.
|
||||||
|
- **Impact:** Release notes and version numbers can drift between runtimes.
|
||||||
|
- **Recommendation:** Correct the ignore entry. Either add changesets for the Python and Java packages, or document that they are versioned by tag and record the tag in the changelog.
|
||||||
|
|
||||||
|
### Q-014 · Stale README and comments after the component removal and the monorepo extraction · **Low**
|
||||||
|
- **Location:** `README.md:31` ("22 components"; the working-tree removal leaves 20 exports in `packages/web-ui/src/lib/index.ts`), `README.md:24` (names a `mediaauth` package that is not in `backend/`), `backend/authproxy/authproxy.go:9` and `backend/mediacore/migrate.go:15` (refer to `mediaauth`), `.gitignore:4` (`webui/.svelte-kit/` targets a directory that was removed)
|
||||||
|
- **Description:** Documentation names a package and a count that no longer match the tree, and a `.gitignore` entry targets a directory that no longer exists.
|
||||||
|
- **Impact:** Misleading documentation for consumers and maintainers.
|
||||||
|
- **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry.
|
||||||
|
|
||||||
|
### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low**
|
||||||
|
- **Location:** `backend/auth/reset.go` (`ResetManager` is used by AuthGuard outside this repository), `backend/auth/totp.go` (`TOTPSecretLength` unused), `backend/auth/store.go` (legacy per-user project APIs and expired-session cleanup helper), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
|
||||||
|
- **Description:** Exported helpers with no workspace callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
|
||||||
|
- **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup.
|
||||||
|
- **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them.
|
||||||
|
- **Status:** Partly fixed 2026-10-20 — removed the unused `TOTPSecretLength` constant, legacy per-user project APIs and their schema creation, and unused `DeleteExpiredSessions` helper. No table drop was added; AuthGuard's existing migration continues to transfer legacy restriction rows into roles before clearing them from the old table. `ResetManager` remains because AuthGuard uses it; file splitting, duplicated helpers, and the remaining findings are open.
|
||||||
|
|
||||||
|
### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low**
|
||||||
|
- **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup)
|
||||||
|
- **Description:** The navigation list comes from a prop and is rendered without a key, so Svelte reconciles it by index. The sign-in field applies the setup minimum, so an account whose existing password is shorter cannot sign in through this form. Whether such accounts exist needs verification; the server enforces eight characters at setup (`backend/auth/proxy.go:1460`, `packages/node-backend/src/auth.js:57`, `packages/python-backend/src/shared_backend/auth.py:124`).
|
||||||
|
- **Impact:** Minor re-render inefficiency, and a possible lockout of legacy accounts.
|
||||||
|
- **Recommendation:** Key the each block by `item.href`, and apply `minlength` only when setup is required.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
|
||||||
|
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
|
||||||
|
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
|
||||||
|
- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go: `gofmt -l`, `go test ./...` and `go vet ./...` passed. Java tests were not run because no JDK or Maven is available. No database-backed integration test ran.
|
||||||
|
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
|
||||||
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
|
||||||
+64
-25
@@ -1,6 +1,6 @@
|
|||||||
# shared
|
# shared
|
||||||
|
|
||||||
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — including the media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub, ProjectConfigurator) — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore.
|
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — for example CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub and ProjectConfigurator — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -21,46 +21,78 @@ The single source of truth for code reused across every project in this workspac
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
|
||||||
| `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
|
| `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
|
||||||
| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets, kept for a handful of older pages. |
|
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, the `settings` table helpers, the `files` path-safety helpers, the `media` library routes, the `syncsocket` sync routes, the `carriernodeclient` client, and the account routes (TOTP and profile) on `auth`. |
|
||||||
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). |
|
|
||||||
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
|
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
|
||||||
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
|
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
|
||||||
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
|
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
|
||||||
|
|
||||||
### Public `web-ui` components
|
### Public `web-ui` components
|
||||||
|
|
||||||
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (23 components):
|
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components), grouped by purpose.
|
||||||
|
|
||||||
|
#### Layout and navigation
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
|
||||||
|
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
|
||||||
|
|
||||||
|
#### Buttons and controls
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
|
||||||
|
| `Pagination` | Page navigation and page-size selection with total/item counts. |
|
||||||
|
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
|
||||||
|
|
||||||
|
#### Dialogs
|
||||||
|
|
||||||
| Component | Includes |
|
| Component | Includes |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `AboutDialog` | About modal with application branding, description, version, links, and custom content. |
|
| `AboutDialog` | About modal with application branding, description, version, links, and custom content. |
|
||||||
| `AppShell` | Application layout that composes the header, page header, notification stack, theme, and primary-color handling. |
|
|
||||||
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
|
||||||
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
|
|
||||||
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
|
|
||||||
| `Card` | Styled content section for grouping application content. |
|
|
||||||
| `Dialog` | Generic modal dialog with title, description, body, footer, and bindable open state. |
|
| `Dialog` | Generic modal dialog with title, description, body, footer, and bindable open state. |
|
||||||
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
|
|
||||||
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
|
|
||||||
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
|
|
||||||
| `MediaPlayerControls` | Reusable media controls for playback, seeking, volume, quality, fullscreen, optional graph toggling, and custom end controls. |
|
|
||||||
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
|
|
||||||
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
|
|
||||||
| `PageHeader` | Page title with optional subtitle/description, child content, and action area. |
|
|
||||||
| `Pagination` | Page navigation and page-size selection with total/item counts. |
|
|
||||||
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
|
|
||||||
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
|
|
||||||
| `SectionTitle` | Section heading with optional description. |
|
|
||||||
| `SettingsDialog` | Generic settings modal with custom content or a default empty-settings message. |
|
| `SettingsDialog` | Generic settings modal with custom content or a default empty-settings message. |
|
||||||
|
|
||||||
|
#### Content and data display
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
|
||||||
|
| `Card` | Styled content section for grouping application content. |
|
||||||
|
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
|
||||||
|
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
|
||||||
|
| `SectionTitle` | Section heading with optional description. |
|
||||||
|
|
||||||
|
#### Feedback and status
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
|
||||||
| `StatusDialog` | Detailed service health/readiness status modal with refresh support. |
|
| `StatusDialog` | Detailed service health/readiness status modal with refresh support. |
|
||||||
| `StatusWidget` | Header-friendly health/readiness indicator that polls `/healthz` and `/ready` and opens `StatusDialog`. |
|
| `StatusWidget` | Header-friendly health/readiness indicator that polls `/healthz` and `/ready` and opens `StatusDialog`. |
|
||||||
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
|
||||||
| `UserManagement` | Role-aware user administration with listing, creation, editing, deletion, project scopes, and pagination. |
|
|
||||||
|
|
||||||
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update this table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the table aligned with that barrel file, and do not add internal or generated components to it.
|
#### Media
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `MediaPlayer` | Audio/video player with playback, seeking, volume, speed, quality, fullscreen, keyboard controls, custom end controls, and optional resume from the saved position (`storageKey`, per app). With `controls={false}` it is just the element, returned through `element`, for apps that drive playback themselves and set `src` on it. |
|
||||||
|
|
||||||
|
#### Accounts and access
|
||||||
|
|
||||||
|
| Component | Includes |
|
||||||
|
|---|---|
|
||||||
|
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
||||||
|
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. Changing a password asks for the current password and, when TOTP is enabled, a current authenticator code; `onSave` receives both proofs in `ProfileUpdateInput`. |
|
||||||
|
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
||||||
|
|
||||||
|
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
|
||||||
|
|
||||||
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
||||||
|
|
||||||
|
### AuthGuard session validation
|
||||||
|
|
||||||
|
The Go and Python `AuthClient.validate()` helpers cache both valid and invalid session results for two seconds. If a session is revoked directly in AuthGuard, a service using that cache may accept it for up to two more seconds. Calling logout through the same client clears its cached result immediately.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## How consumers actually use this
|
## How consumers actually use this
|
||||||
@@ -78,7 +110,7 @@ To pull the latest snapshot into every registered consumer:
|
|||||||
.\scripts\sync-consumers.ps1 -Commit -Push
|
.\scripts\sync-consumers.ps1 -Commit -Push
|
||||||
```
|
```
|
||||||
|
|
||||||
The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step.
|
The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) can run this automatically, with `-Commit` only and never `-Push`. It is opt-in: it does nothing unless the commit is made with `SHARED_SYNC_COMMIT=1` in the environment, so an ordinary commit here never writes to a consumer repository. Pushing the sync commits to each consumer remains a manual follow-up step. Running with `-Force` over a consumer that has local changes first copies the replaced `shared/` folder to a temporary backup directory, and the script prints its path.
|
||||||
|
|
||||||
### Published registry packages (for standalone/external use)
|
### Published registry packages (for standalone/external use)
|
||||||
|
|
||||||
@@ -91,8 +123,11 @@ The npm, Go, and Python packages are also published to this Gitea instance's pac
|
|||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm run check
|
npm run check
|
||||||
|
npm run lint # svelte-check, Node syntax check and ESLint
|
||||||
|
npm run format:check # Prettier, for the files written to its style (.prettierrc.json)
|
||||||
npm run build # builds packages/web-ui/dist (gitignored, not committed)
|
npm run build # builds packages/web-ui/dist (gitignored, not committed)
|
||||||
npm run test:node-backend
|
npm run test:node-backend
|
||||||
|
npm run test:web-ui # Vitest component and store tests (jsdom)
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -101,6 +136,10 @@ go test ./...
|
|||||||
go vet ./...
|
go vet ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, media and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`).
|
||||||
|
|
||||||
|
`contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses, and the internal-secret rule: minimum length and example placeholders) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Typical `web-ui` wiring
|
## Typical `web-ui` wiring
|
||||||
@@ -168,4 +207,4 @@ The Go module lives under `backend`, so its release tag uses the submodule prefi
|
|||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
|
`lint.yml` runs three jobs — Node/Svelte (svelte-check, ESLint, Prettier), Go, and Python; `tests.yml` runs four — Node/Svelte (including the web-ui Vitest suite), Go (against a PostgreSQL service), Python, and Java. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
# Security Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
|
||||||
|
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/Go/web-ui suites, Svelte check, Node lint, Ruff, formatting and web-ui package build. Java tools remain unavailable; no production service or real database was used.
|
||||||
|
- **Updated:** 2026-10-20 — shared decisions implemented in the working tree: S-011 fixed; S-010 partly fixed with its undecided session-revocation portion left open. Available Node and web-ui checks pass; Python, Go and Java verification limits are recorded below.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 1 | 1 | 0 | 0 |
|
||||||
|
| High | 3 | 2 | 0 | 1 |
|
||||||
|
| Medium | 13 | 12 | 0 | 1 |
|
||||||
|
| Low | 5 | 0 | 0 | 5 |
|
||||||
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
|
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical** · Fixed
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
|
||||||
|
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
|
||||||
|
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
|
||||||
|
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `PUT /access` now depends on a new `require_admin` dependency that needs a session whose role can manage users (401 without a session or AuthGuard, 403 for other roles), so an anonymous caller can no longer clear the login flag. `GET /access` stays public for the login screen, and the internal route keeps its shared-secret check; the tests now assert 401 and 403 and that an admin session can still toggle. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`.
|
||||||
|
|
||||||
|
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High** · Fixed
|
||||||
|
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
|
||||||
|
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
|
||||||
|
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
|
||||||
|
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
|
||||||
|
- **Status:** Fixed 2026-10-19 — in Node, `middleware()` now calls `tokenFromRequest` inside its `try`, and a malformed cookie escape yields `''`, so the request gets a 401 instead of an unhandled rejection. In Java, `extractCookieToken` escapes a literal `+` before `URLDecoder` so it is kept, and a malformed escape returns `""` instead of throwing. Tests were added in both packages; the Java tests were not compiled or run because no JDK is installed here, so they were checked by reading only. Files: `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
|
### S-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High** · Open
|
||||||
|
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
|
||||||
|
- **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control.
|
||||||
|
- **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware).
|
||||||
|
- **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation.
|
||||||
|
- **Status:** Open 2026-10-19 — partly fixed (decision 12): each websocket connection is issued a random `clientId` at upgrade time and receives it in its `hello` frame. A message naming any other identity gets a `client-id-mismatch` error frame and is dropped, so self-chosen and duplicate IDs are no longer possible. Behaviour change: a client must take its ID from `hello`, and a reconnect gets a new identity, so control claims and remote-control flags do not carry over. Still open: `/ws` still accepts unauthenticated connections, so an anonymous connection can still obtain an identity and claim control of any peer that enabled remote control. Requiring authentication on each consumer's `/ws` route is a consumer change and was not made here. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
|
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High** · Fixed
|
||||||
|
- **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit)
|
||||||
|
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
|
||||||
|
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
|
||||||
|
- **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `PUT /sync` now sits behind `Require`, so anonymous callers get 401 when login is required. `mediaId` and `playAt` must be null, a number or a string, and strings are trimmed and capped at 128 bytes, so other shapes are refused with 400 and the stored state holds only scalars. Behaviour change: clients that send anonymous `PUT /sync` with login enabled are now refused, and non-scalar `mediaId` or `playAt` values get 400. Any authenticated user can still write any session, including `"default"`, which is the session model rather than part of this finding. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`.
|
||||||
|
|
||||||
|
### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review).
|
||||||
|
- **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree.
|
||||||
|
- **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts.
|
||||||
|
- **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Python guarded routes now resolve through `_configured_client`, which fails closed with a 500 when AUTHGUARD_URL is unset unless the consumer passes `local_profile_without_authguard=True`, and the process-local login override is gone because the store is read on each call. In Go, `SetLoginRequired` now clears the two-second login cache instead of writing its own value, so a store that discards writes cannot leave a process with a local setting. Behaviour change: Python consumers that run without AuthGuard must pass `local_profile_without_authguard=True`, or their guarded routes return 500. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
|
### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`)
|
||||||
|
- **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern.
|
||||||
|
- **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable.
|
||||||
|
- **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Go handler, the Node and Python guards and the stores now reject an empty secret and compare in constant time (`subtle.ConstantTimeCompare`, `crypto.timingSafeEqual`, `hmac.compare_digest`). The Node and Python stores accept only http or https URLs with a host, the Go handler checks the same before storing, and the README examples call `internalSecretMatches` and `internal_secret_matches`. Files: `backend/coreconfig/coreconfig.go`, `backend/coreconfig/coreconfig_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/coreconfig.js`, `packages/node-backend/test/coreconfig.test.js`, `packages/python-backend/src/shared_backend/coreconfig.py`, `packages/python-backend/tests/test_coreconfig.py`, `packages/node-backend/README.md`, `packages/python-backend/README.md`.
|
||||||
|
|
||||||
|
### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`)
|
||||||
|
- **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site.
|
||||||
|
- **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes.
|
||||||
|
- **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `decodeProxyJSON` refuses any body that is not `application/json` and any request marked `Sec-Fetch-Site: cross-site`, and the body-less state-changing handlers (logout, TOTP initiate, managed user delete) refuse cross-site requests with a 403. Origin is still not checked, and requests from browsers that omit `Sec-Fetch-Site` are accepted, so SameSite remains a second layer. Behaviour change: clients that send a non-JSON body, or a cross-site request, to these routes are now refused. Files: `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
|
### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin)
|
||||||
|
- **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user.
|
||||||
|
- **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges.
|
||||||
|
- **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Signup` answers 409 while login is not required, so an anonymous caller cannot become superadmin on a service with login off. The oldest-user promotion in `EnsureSchema` now runs only in the migration that adds the `role` column, so a restart no longer promotes someone when no superadmin exists. Residual: with login required and an empty AuthGuard the first signup still becomes superadmin, as designed; a one-time setup token would be a product decision. Files: `backend/auth/proxy.go`, `backend/auth/store.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
|
### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review)
|
||||||
|
- **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user.
|
||||||
|
- **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter.
|
||||||
|
- **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts.
|
||||||
|
- **Status:** Fixed 2026-10-19 — login has a per-account limit (10 per 15 minutes) and a per-client-address limit (200), and TOTP verify and disable share a per-user limit (5), all held in process memory: `backend/auth/ratelimit.go` for the Go proxy and, new in this pass, `shared_backend/ratelimit.py` and `authproxy.build_auth_router` for the Python router (same numbers, `429` beyond them). The client address honours `X-Forwarded-For` only from peers listed in `TRUSTED_PROXIES` (decision 5): `backend/auth/clientip.go`, and the new `shared_backend/clientip.py` (the router reads the variable, or a `trusted_proxies` argument; an invalid list raises `ValueError` at startup). The verified address is now forwarded to AuthGuard as `X-Forwarded-For` on login, signup/register and TOTP verify/disable: Go `authclient.WithClientIP` (set by `auth.Service`), Python `authclient.forwarded_client_ip` (set by the router), Node an optional `{ clientIp }` on `register`, `login`, `totpVerify`, `totpDisable` and the reset calls. Only IP-address values are sent, never a raw request header. AuthGuard's own limiters (`Central/AuthGuard/internal/httpapi`, read for this pass) key on its `clientIP`, which reads the header only from peers inside AuthGuard's own `TRUSTED_PROXIES`, so the forwarding takes effect once an operator lists the consuming service's address there and is ignored until then. Residual: counters are per replica, so N replicas of one service allow N times the attempts (AuthGuard's central limiter still applies). Behaviour change: Python services now answer 429 on login and TOTP routes after the limits, and `build_auth_router` gains the `trusted_proxies` argument and reads `TRUSTED_PROXIES`. Files: `backend/auth/ratelimit.go`, `backend/auth/proxy.go`, `backend/auth/clientip.go`, `backend/authclient/client.go`, `backend/auth/proxy_handlers_test.go`, `backend/authclient/client_test.go`, `packages/python-backend/src/shared_backend/{authproxy,authclient,clientip,ratelimit}.py`, `packages/python-backend/tests/{test_authproxy,test_authclient,test_attempt_limits}.py`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`.
|
||||||
|
|
||||||
|
### S-010 · Self-service profile update changes the password without re-authentication · **Medium** · Open
|
||||||
|
- **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie)
|
||||||
|
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
|
||||||
|
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
||||||
|
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
||||||
|
- **Status:** Partly fixed 2026-10-20 — the decided rule is implemented: Go and Python self-service profile updates require `currentPassword` for a password change and a TOTP code when enabled; both reauthenticate through AuthGuard, omit proof fields from the managed-user update, and attempt to clear the temporary session. The shared web-ui prompts for and sends those values. No self-service `UpdateMe` route exists in the shared Node or Java clients. Still open: revoking other sessions after a password change is controlled by AuthGuard and has no owner decision. Files: `backend/auth/proxy.go`, `backend/auth/proxy_handlers_test.go`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `packages/web-ui/src/lib/components/ProfileDialog.svelte`, `packages/web-ui/tests/ProfileDialog.test.ts`.
|
||||||
|
|
||||||
|
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open
|
||||||
|
- **Location:** `backend/auth/totp.go` and `packages/{node-backend/src/totp.js,python-backend/src/shared_backend/totp.py,java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}` return the matched time step; Go, Node and Python auth stores persist it.
|
||||||
|
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
|
||||||
|
- **Impact:** A phished or shoulder-surfed code can be reused.
|
||||||
|
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
|
||||||
|
- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Go, Node, Python and web-ui checks passed; Java tests could not run because no JDK or Maven is available.
|
||||||
|
|
||||||
|
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
||||||
|
- **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available.
|
||||||
|
- **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role.
|
||||||
|
- **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `AuthClient.validate` parses the AuthGuard response with Jackson and reads only the top-level `valid`, `user_id`, `username` and `role` fields, so nested fields with the same names are ignored, and tests cover nested and reordered fields. Not compiled or run: no JDK or Maven is available here, so this was checked by reading only. Files: `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
|
### S-013 · Password hashing is below the intended settings in two runtimes · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes)
|
||||||
|
- **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent.
|
||||||
|
- **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded.
|
||||||
|
- **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message.
|
||||||
|
- **Status:** Fixed 2026-10-19 — every hash now carries a scheme prefix, and verification dispatches on it. Node writes `pbkdf2-sha256$<iterations>$<salt>$<hash>` at 600,000 iterations. Go and Python write `bcrypt$` followed by an unchanged bcrypt string at cost 12 (`BcryptCost`). Legacy Node `salt:hex` hashes (100,000 iterations) and unprefixed bcrypt hashes still verify, and any other format fails closed. Rehash on login: `verifyAndUpgradePasswordAsync` (Node), `verify_and_upgrade_password_async` (Python) and `VerifyAndUpgradePassword` (Go) return a current-scheme hash after a matching password, for the caller to store. Go platform-user writes now use `HashPassword`. Caveats: no login route in this repository checks local hashes (AuthGuard checks logins), so the rewrite happens only in a consumer that calls the helper; Node still cannot verify bcrypt. Behaviour change: Python and Go code from before this change cannot verify the new `bcrypt$` hashes, so services that share a database must move together. The 72-byte limit is enforced in Go (`validateProxyPassword` refuses more than 72 bytes, and bcrypt itself refuses them) and, since this pass, in Python (`MAX_PASSWORD_BYTES`: `hash_password` raises `ValueError` and the router's `_validate_password` answers 400, whatever bcrypt version is installed); Node's PBKDF2 has no such limit. Files: `backend/auth/password.go`, `backend/auth/password_test.go`, `backend/auth/store_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/node-backend/test/auth.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/src/shared_backend/__init__.py`, `packages/python-backend/tests/test_core.py`, `packages/python-backend/tests/test_store.py`.
|
||||||
|
|
||||||
|
### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`)
|
||||||
|
- **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers.
|
||||||
|
- **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced.
|
||||||
|
- **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `websocketAcceptOptions` no longer maps `*` to `InsecureSkipVerify`; origin verification is always on, and `*` adds no extra origin. Behaviour change: a deployment that relied on `CORS_ORIGIN=*` to accept sockets from any page must now list each origin explicitly. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
|
### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session)
|
||||||
|
- **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent.
|
||||||
|
- **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see.
|
||||||
|
- **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the sync hub no longer reads `X-Forwarded-For`, and it no longer sends a peer's IP address or user agent in the client list. The Go proxy's client address honours `X-Forwarded-For` only when the TCP peer is inside `TRUSTED_PROXIES` (decision 5), and otherwise uses the TCP peer. Behaviour change: clients that displayed the `ipAddress` or `userAgent` of other peers will no longer receive those fields. A service behind a reverse proxy gets per-client login limits only once it sets `TRUSTED_PROXIES`; until then its behaviour is unchanged. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/auth/clientip.go`, `backend/auth/clientip_test.go`, `backend/auth/proxy.go`.
|
||||||
|
|
||||||
|
### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review)
|
||||||
|
- **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash.
|
||||||
|
- **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake.
|
||||||
|
- **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `SetTOTPSecret` refuses while TOTP is enabled (`ErrTOTPAlreadyEnabled`), credential writes refuse an empty password hash and a username containing `@`, and identifier lookup tries usernames before emails in a fixed order. New in this pass: usernames are unique ignoring case through an index on `lower(username)` (`auth_users_username_lower_idx`), created by `EnsureSchema` (Go), `AuthStore.ensureSchema` (Node) and `AuthStore.ensure_schema` (Python) only while no pair such as `Admin` and `admin` exists. Choice made without an owner decision: a database that already holds such a pair still starts, gets no index, and logs the clashing names on each start (a warning in Node and Python) until an operator renames or removes one account of each pair; no account is merged or renamed automatically. The Node and Python stores now carry the same guards as Go (empty hash, `@` in a username, no TOTP secret replacement while enabled, username-then-email lookup). Behaviour change: registering a username that differs from an existing one only by case now fails as an existing user; `setTotpSecret`/`set_totp_secret` throw (`AUTH_TOTP_ALREADY_ENABLED`, `TotpAlreadyEnabledError`) while TOTP is enabled; a credential write with an empty hash or an `@` username throws (`AUTH_EMPTY_PASSWORD_HASH`/`AUTH_INVALID_USERNAME`, `EmptyPasswordHashError`/`InvalidUsernameError`). Files: `backend/auth/store.go`, `backend/auth/store_test.go`, `backend/auth/store_integration_test.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/test/authstore.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/test_store.py`.
|
||||||
|
|
||||||
|
### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium** · Fixed
|
||||||
|
- **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly)
|
||||||
|
- **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them.
|
||||||
|
- **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification).
|
||||||
|
- **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators).
|
||||||
|
- **Status:** Fixed 2026-10-19 — stored media paths go through `upstreamMediaPath`, which applies `SafeRelative`, refuses `?` and `#`, and escapes each segment before the CarrierNode call. The push and delete helpers for thumbnails, outputs, inputs and copies reject `.`, `..` and path separators through `validName`. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`, `backend/carriernodeclient/carriernodeclient.go`, `backend/carriernodeclient/thumbnails_test.go`.
|
||||||
|
|
||||||
|
### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low**
|
||||||
|
- **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard)
|
||||||
|
- **Description:** `IsAdmin` admits moderators while `NormalizeRole` and `CanManageUsers` do not. The assignment check exists but is not used, and roles from requests are forwarded without a local check.
|
||||||
|
- **Impact:** Moderators may receive access that the other definitions do not grant, and an escalation becomes possible if AuthGuard or the calling service does not enforce role rules (needs verification).
|
||||||
|
- **Recommendation:** Use one typed role set. Call `CanAssignRole` in the managed-user handlers as defence in depth, and restrict or document what moderators can do.
|
||||||
|
|
||||||
|
### S-019 · Reset codes are weak and unlimited, and TOTP secrets are stored in plaintext · **Low**
|
||||||
|
- **Location:** `backend/auth/reset.go:37` (four random bytes, so 32 bits), `backend/auth/reset.go:48` (code printed to stdout), `packages/node-backend/src/auth.js:106` (`randomBytes(4)`), `packages/python-backend/src/shared_backend/auth.py:83` and `:101` (`token_hex(4)` with `compare_digest`), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java` (per review), `backend/auth/store.go:84` (`totp_secret TEXT`), `packages/node-backend/src/auth.js:30` (`totp_secret TEXT`)
|
||||||
|
- **Description:** Administrator reset codes are 32-bit values. They can be guessed with unlimited attempts during their five-minute life, and calling `request` again rotates them. The code is printed to stdout, where log shipping may capture it. TOTP seeds are stored in plaintext in `auth_users`.
|
||||||
|
- **Impact:** A reset code can be brute-forced within its lifetime, and second-factor seeds are exposed if the database leaks.
|
||||||
|
- **Recommendation:** Add an attempt counter with lockout, and require an authenticated caller to request a code. Do not print codes to stdout in production. Encrypt TOTP secrets at rest with an application key kept outside the database.
|
||||||
|
|
||||||
|
### S-020 · Insecure-by-configuration options: secure cookies off by default, and database certificate verification can be disabled · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:244` (`secure_cookie` defaults to `False`), `packages/python-backend/src/shared_backend/authproxy.py:276` (`Secure` applied to cleared cookies), `packages/python-backend/src/shared_backend/authproxy.py:279-281` (AuthGuard `Set-Cookie` values forwarded unchanged), `packages/node-backend/src/config.js:48-51` (`DATABASE_SSL_ALLOW_INVALID` sets `rejectUnauthorized: false`)
|
||||||
|
- **Description:** The Python proxy does not set or validate `Secure`, `HttpOnly` or `SameSite` on forwarded session cookies, and `Secure` defaults to off. The Node configuration lets an environment flag turn off database certificate verification. Both are opt-in, but the defaults are the unsafe choice.
|
||||||
|
- **Impact:** Session cookies can travel over cleartext behind an HTTPS misconfiguration, and database connections can be made without certificate checks.
|
||||||
|
- **Recommendation:** Default `secure_cookie` to true, or derive it from the request scheme. Rewrite forwarded cookie attributes, and log a warning when database TLS verification is disabled.
|
||||||
|
|
||||||
|
### S-021 · CI workflows and repository hygiene need hardening, and history contains an example file with embedded database credentials · **Low**
|
||||||
|
- **Location:** `.github/workflows/lint.yml:37`, `:39`, `:59`, `:61` and `.github/workflows/tests.yml` (actions referenced by mutable tags such as `actions/checkout@v4`), `.gitea/workflows/publish-npm.yml:71`, `.gitea/workflows/publish-go.yml:61`, `.gitea/workflows/publish-python.yml:43` (registry token passed as a `curl --user` argument, so it is visible in process listings on the runner), `.gitignore` (no rules for `.env*`, `*.pem`, `*.key` or `.npmrc`), git history: commit `acde180` added `media-backend/.env.example`, which the working tree no longer contains; its `DATABASE_URL` line contains embedded credentials (value redacted, needs verification of whether it was ever valid)
|
||||||
|
- **Description:** Action references are mutable tags rather than commit SHAs. Workflow permissions are correctly `contents: read`. Registry credentials appear on command lines during upload, although the npm workflow correctly writes its token to a file. The ignore rules do not block common secret files, so an accidental commit would not be stopped. The removed example file shows that a connection string with credentials was committed once.
|
||||||
|
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
|
||||||
|
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
|
||||||
|
|
||||||
|
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low** · Open
|
||||||
|
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
|
||||||
|
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
|
||||||
|
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
|
||||||
|
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
|
||||||
|
- **Status:** Open 2026-10-19 — the access part is fixed: `/media/stream` (GET and HEAD) and `/media/thumb` now sit behind `RequireIfLoginRequired`, so anonymous requests get 401 while login is required and are served while it is off (applied from the vendored ContentScanner change). Hidden media (`active = FALSE`) returns 404 to non-moderators on the stream, thumb and original-image lookups, and a database error in that check counts as hidden (ported from the ModerationHub change); the caller rule has a unit test, the SQL filter does not, because the test suite has no database. Other media routes (state, tags, playlists) are not covered by this rule. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`. Still open: the `X-Content-Type-Options: nosniff` and restrictive CSP on proxied and served media (`backend/carriernodeclient/carriernodeclient.go`), the active-type mapping in `ServeFile` (`backend/mediacore/mediacore.go`, `.html` and `.svg`), and the `*sharedauth.User` JSON-tag question. Those need a header and content-type change in CarrierNode and the media server, and a decision on whether active types are allowed under media paths.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
|
||||||
|
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
|
||||||
|
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
|
||||||
|
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
|
||||||
|
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites plus Go `go test ./...`, `go vet ./...` and `gofmt -l` passed; Java tests were unavailable because no JDK or Maven is installed. No server was started.
|
||||||
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
|
||||||
@@ -5,12 +5,12 @@ services, not application-specific SQL or HTTP handlers.
|
|||||||
|
|
||||||
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
||||||
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
||||||
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
|
- `auth` — versioned bcrypt password hashes (`HashPassword` writes a `bcrypt$` prefix; `VerifyAndUpgradePassword` rewrites older hashes on login), trusted-proxy client addresses (`ParseTrustedProxies` reads `TRUSTED_PROXIES`, a comma-separated CIDR list; `X-Forwarded-For` is honoured only from those peers), secure token generation/hashing, account/session schema (usernames are unique ignoring case once no clashing pair exists), account/session persistence, and attempt limits on the login and TOTP routes (per account and per client address, held in process memory).
|
||||||
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database.
|
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. `WithClientIP(ctx, ip)` makes the credential calls send the end user's address as `X-Forwarded-For`; AuthServer reads it only from peers in its own `TRUSTED_PROXIES`.
|
||||||
- `migrate` — embedded filesystem adapter for Goose migrations.
|
- `migrate` — embedded filesystem adapter for Goose migrations.
|
||||||
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
|
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
|
||||||
|
|
||||||
Run `go test ./...` and `go vet ./...` from this directory. The module path is
|
Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, media, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is
|
||||||
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
|
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
|
||||||
hosted under a different repository path.
|
hosted under a different repository path.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MountAccountRoutes mounts the signed-in account routes onto r: the TOTP enrollment and
|
||||||
|
// verification routes, which require a session, and GET /profile, which reports the session's
|
||||||
|
// user or null. A project that signs users in through AuthGuard mounts these alongside its own
|
||||||
|
// routes.
|
||||||
|
func (s *Service) MountAccountRoutes(r chi.Router) {
|
||||||
|
r.With(s.Require).Get("/security/totp/status", s.TOTPStatus)
|
||||||
|
r.With(s.Require).Get("/security/totp/initiate", s.TOTPInitiate)
|
||||||
|
r.With(s.Require).Post("/security/totp/verify", s.TOTPVerify)
|
||||||
|
r.With(s.Require).Post("/security/totp/disable", s.TOTPDisable)
|
||||||
|
r.With(s.Optional).Get("/profile", profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
func profile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeAccountJSON(w, http.StatusOK, map[string]any{"user": nil})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeAccountJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAccountJSON(w http.ResponseWriter, status int, value any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(value)
|
||||||
|
}
|
||||||
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user