Compare commits
91
Commits
20e9461d46
...
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 | ||
|
|
43b951210e | ||
|
|
be0d4a87f5 | ||
|
|
efda65ae5f | ||
|
|
23cdd88e11 | ||
|
|
775a5520b6 | ||
|
|
a4f897572c | ||
|
|
d9e2d64535 | ||
|
|
668e9dd310 | ||
|
|
c0a5e29d27 | ||
|
|
4a391392bb | ||
|
|
74afed9a13 | ||
|
|
55b224bc48 | ||
|
|
346f6f839f | ||
|
|
407966fc94 | ||
|
|
ec82a8a8b9 | ||
|
|
b3d27ff37e | ||
|
|
08a6d7bd1d | ||
|
|
c097383d3a | ||
|
|
6e70b7e8c1 | ||
|
|
dc04ac4360 | ||
|
|
eb67f251d8 | ||
|
|
07e25a3cf3 | ||
|
|
f723afa369 | ||
|
|
a018f3da4c | ||
|
|
8d7c2f69ff | ||
|
|
6e13364ebd | ||
|
|
aae8d3807d | ||
|
|
803c3ab3ce | ||
|
|
f34887abf3 | ||
|
|
da15c3a7b7 | ||
|
|
899223270a | ||
|
|
5b18c38fc0 | ||
|
|
b1412a9016 | ||
|
|
1d99f0272d | ||
|
|
b9dd2ffde6 | ||
|
|
8327214942 | ||
|
|
2593fd67dc | ||
|
|
f8c05d9e90 | ||
|
|
1b05b7ea54 | ||
|
|
aea883cb77 | ||
|
|
a5dfd3dc5a | ||
|
|
cfa06cd466 | ||
|
|
8987d765a3 | ||
|
|
439ef02496 | ||
|
|
a2a96f6a46 | ||
|
|
df94fc6d8b | ||
|
|
fc4400b118 | ||
|
|
379022e446 | ||
|
|
7c4a903f59 |
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'
|
||||
workflow_dispatch: {}
|
||||
|
||||
env:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
@@ -38,13 +37,14 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
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
|
||||
|
||||
- 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'
|
||||
workflow_dispatch: {}
|
||||
|
||||
env:
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -29,6 +28,21 @@ jobs:
|
||||
working-directory: backend
|
||||
permissions:
|
||||
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:
|
||||
- name: Checkout
|
||||
@@ -42,7 +56,14 @@ jobs:
|
||||
cache: true
|
||||
|
||||
- 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:
|
||||
name: Dashboard checks
|
||||
@@ -67,8 +88,12 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
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
|
||||
|
||||
- name: Check dashboard
|
||||
run: npm run check
|
||||
|
||||
- name: Unit tests
|
||||
run: npm test
|
||||
@@ -26,3 +26,5 @@ frontend/dist/
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
*.exe
|
||||
@@ -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 {
|
||||
id 'com.android.application'
|
||||
id 'org.jetbrains.kotlin.android'
|
||||
id 'org.jetbrains.kotlin.plugin.compose'
|
||||
// KSP not available for Kotlin 2.2.21 yet; switch to kapt for Room annotation processing
|
||||
id 'org.jetbrains.kotlin.kapt'
|
||||
id 'com.google.devtools.ksp'
|
||||
id 'org.jlleitschuh.gradle.ktlint'
|
||||
id 'io.gitlab.arturbosch.detekt'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = 'com.collabtable.app'
|
||||
compileSdk = 34
|
||||
compileSdk {
|
||||
version = release(37) {
|
||||
minorApiLevel = 2
|
||||
}
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.collabtable.app"
|
||||
minSdk = 26
|
||||
targetSdk = 34
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
targetSdk = 37
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
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 {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
if (releaseKeystoreFile != null) {
|
||||
signingConfig signingConfigs.release
|
||||
}
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = '21'
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
packaging {
|
||||
resources {
|
||||
@@ -48,6 +68,12 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_21)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Core Android
|
||||
implementation 'androidx.core:core-ktx:1.12.0'
|
||||
@@ -68,16 +94,15 @@ dependencies {
|
||||
// ViewModel
|
||||
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-ktx:2.7.0'
|
||||
kapt 'androidx.room:room-compiler:2.7.0'
|
||||
ksp 'androidx.room:room-compiler:2.7.0'
|
||||
|
||||
// Retrofit
|
||||
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
|
||||
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
|
||||
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
|
||||
kapt 'com.squareup.retrofit2:retrofit:2.9.0'
|
||||
|
||||
// Coroutines
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
<application
|
||||
android:name=".CollabTableApplication"
|
||||
android:allowBackup="true"
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.collabtable.app.data.api
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import com.collabtable.app.BuildConfig
|
||||
import com.collabtable.app.data.preferences.PreferencesManager
|
||||
import com.collabtable.app.utils.Logger
|
||||
import okhttp3.Interceptor
|
||||
@@ -17,9 +18,13 @@ object ApiClient {
|
||||
private var retrofit: Retrofit? = 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 =
|
||||
HttpLoggingInterceptor().apply {
|
||||
level = HttpLoggingInterceptor.Level.BODY
|
||||
level =
|
||||
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
|
||||
redactHeader("Authorization")
|
||||
}
|
||||
|
||||
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) {
|
||||
this.context = context.applicationContext
|
||||
val prefs = PreferencesManager.getInstance(context)
|
||||
@@ -124,6 +141,7 @@ object ApiClient {
|
||||
Logger.i("HTTP", "API base URL initialized to $baseUrl")
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
warnIfCleartext(baseUrl)
|
||||
retrofit = buildRetrofit()
|
||||
}
|
||||
|
||||
@@ -133,6 +151,7 @@ object ApiClient {
|
||||
Logger.i("HTTP", "API base URL set to $baseUrl")
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
warnIfCleartext(baseUrl)
|
||||
retrofit = buildRetrofit()
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import retrofit2.http.Query
|
||||
|
||||
data class SyncRequest(
|
||||
val lastSyncTimestamp: Long,
|
||||
val lastSyncToken: Long,
|
||||
val lists: List<CollabList>,
|
||||
val fields: List<Field>,
|
||||
val items: List<Item>,
|
||||
@@ -24,6 +25,9 @@ data class SyncResponse(
|
||||
val items: List<Item>,
|
||||
val itemValues: List<ItemValue>,
|
||||
val serverTimestamp: Long,
|
||||
val serverChangeToken: Long,
|
||||
val nextSyncToken: Long,
|
||||
val hasMore: Boolean,
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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) {
|
||||
prefs
|
||||
.edit()
|
||||
@@ -101,30 +107,29 @@ class SyncRepository(
|
||||
return@withContext Result.success(Unit)
|
||||
}
|
||||
val lastServerTs = getLastServerSyncTs()
|
||||
val lastServerToken = getLastServerSyncToken()
|
||||
val lastLocalTs = getLastLocalSyncTs()
|
||||
// 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
|
||||
// to this snapshot once the sync completes successfully.
|
||||
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) {
|
||||
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (effectiveLastServerToken == 0L && (lastServerTs > 0L || lastServerToken > 0L)) {
|
||||
val reason = if (forceFullDown) "startup forced" else "local empty"
|
||||
Logger.w("Sync", "$reason full down-sync requested")
|
||||
}
|
||||
@@ -162,125 +167,137 @@ class SyncRepository(
|
||||
)
|
||||
}
|
||||
|
||||
// Send to server and get updates
|
||||
val syncRequest =
|
||||
SyncRequest(
|
||||
lastSyncTimestamp = effectiveLastServerTs,
|
||||
lists = localLists,
|
||||
fields = localFields,
|
||||
items = localItems,
|
||||
itemValues = localValues,
|
||||
)
|
||||
|
||||
// HTTP-only sync
|
||||
val response =
|
||||
try {
|
||||
api.sync(syncRequest)
|
||||
} catch (e: UnknownHostException) {
|
||||
// Host could not be resolved; apply exponential backoff and surface a warning once.
|
||||
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}")
|
||||
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) {
|
||||
// Upload local changes once, then follow the server's bounded pages without
|
||||
// replaying the same writes on every request.
|
||||
var cursor = effectiveLastServerToken
|
||||
var pageProgress = SyncPageProgress(cursor)
|
||||
var serverTimestamp = lastServerTs
|
||||
while (true) {
|
||||
val response =
|
||||
try {
|
||||
api.sync(
|
||||
SyncRequest(
|
||||
lastSyncTimestamp = lastServerTs,
|
||||
lastSyncToken = pageProgress.cursor,
|
||||
lists = if (pageProgress.firstPage) localLists else emptyList(),
|
||||
fields = if (pageProgress.firstPage) localFields else emptyList(),
|
||||
items = if (pageProgress.firstPage) localItems else emptyList(),
|
||||
itemValues = if (pageProgress.firstPage) localValues else emptyList(),
|
||||
),
|
||||
)
|
||||
} catch (e: UnknownHostException) {
|
||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||
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"))
|
||||
}
|
||||
throw e
|
||||
}
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code() == 401) {
|
||||
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
|
||||
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
|
||||
} 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)
|
||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
||||
}
|
||||
|
||||
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
|
||||
throw e
|
||||
}
|
||||
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 (!response.isSuccessful) {
|
||||
if (response.code() == 401) {
|
||||
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()) {
|
||||
database.itemValueDao().insertValues(filteredValues)
|
||||
val syncResponse = response.body() ?: return@withContext Result.failure(Exception("Sync response was empty"))
|
||||
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
|
||||
setLastServerSyncTs(syncResponse.serverTimestamp)
|
||||
// Save the server-owned change cursor only after every page has been applied.
|
||||
setLastServerSyncToken(cursor)
|
||||
setLastServerSyncTs(serverTimestamp)
|
||||
// Advance local watermark to the snapshot taken before reading local changes.
|
||||
// This avoids missing updates that occurred while the sync was in-flight.
|
||||
setLastLocalSyncTs(localSnapshotTs)
|
||||
@@ -298,6 +315,7 @@ class SyncRepository(
|
||||
// If WS indicated unauthorized, align behavior with HTTP path
|
||||
if (e.message?.contains("Unauthorized") == true) {
|
||||
setLastServerSyncTs(0)
|
||||
setLastServerSyncToken(0)
|
||||
setLastLocalSyncTs(0)
|
||||
}
|
||||
// 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.
|
||||
plugins {
|
||||
id 'com.android.application' version '8.8.0' apply false
|
||||
id 'com.android.library' version '8.8.0' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '2.2.21' apply false
|
||||
id 'org.jetbrains.kotlin.plugin.compose' version '2.2.21' apply false
|
||||
id 'com.android.application' version '9.5.0' apply false
|
||||
id 'com.android.library' version '9.5.0' apply false
|
||||
id 'org.jetbrains.kotlin.plugin.compose' version '2.3.20' 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 'io.gitlab.arturbosch.detekt' version '1.23.8' apply false
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
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
|
||||
validateDistributionUrl=true
|
||||
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.
|
||||
@@ -32,19 +32,34 @@ shared/ Design system and backend helpers shared with sibling proje
|
||||
|
||||
CollabTable's browser dashboard authenticates through AuthGuard, a centralized identity service shared across projects (`AUTHGUARD_URL`): create a username, email, and password on first launch, then sign in with the username or email. AuthGuard hashes passwords and issues the `auth_session` cookie the browser holds; CollabTable itself stores no account credentials, only a small local flag recording that its one-time setup screen has run. Unlike the single-admin-tool projects in this workspace, CollabTable is a genuinely multi-user app that already supported full admin user management (list/create/edit/delete accounts, assign roles) before this integration — that maps directly onto AuthGuard's own `/api/admin/users` endpoints, which CollabTable proxies to rather than re-implementing the same authorization rules locally.
|
||||
|
||||
`AUTHGUARD_URL` is optional: leaving it unset does not fall back to any local account store — it disables authentication entirely, treating every request as authenticated with nothing gated. Only run without it for local development or a deployment you are certain does not need access control. 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.
|
||||
AuthGuard integration has three states:
|
||||
- `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.
|
||||
- `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.
|
||||
|
||||
`AUTHGUARD_URL` and `CARRIERNODE_URL` are also only the bootstrap fallback: once CollabTable is registered in ProjectConfigurator's Projects workspace, ProjectConfigurator pushes both values here automatically (`PUT /api/core-services/internal`, `X-Internal-Auth`-gated with `SECRET`) and keeps them current with no restart — see `Core/ProjectConfigurator/README.md`'s "Pushing core service info to other projects". This means `AUTHGUARD_URL` no longer needs to be set at all for a registered deployment: it stays "pending" until the first push. A push never overrides `AUTH_DISABLED=true`; it only ever retargets an already-enabled AuthGuard connection. CarrierNode isn't used by any feature here yet, but the client is wired and ready.
|
||||
|
||||
The device-sync API token (generated from the dashboard's Settings page, used by the Android app's `Authorization: Bearer` header for `/api/lists`, `/api/fields`, `/api/items`, `/api/sync`, and notification polling) is unrelated to AuthGuard and unaffected by whether it's configured: it's a long-lived per-account credential for a user's own devices, not a browser session, and stays entirely local to CollabTable's own Postgres.
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
|----------|----------|---------|--------------|
|
||||
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
||||
| `AUTHGUARD_URL` | No | unset (auth disabled) | Base URL of the AuthGuard identity service. Leaving it unset disables authentication entirely rather than falling back to local auth. |
|
||||
| `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 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. |
|
||||
| `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 |
|
||||
| `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_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 |
|
||||
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
||||
|
||||
@@ -63,6 +78,7 @@ docker run -d \
|
||||
-p 8080:8080 \
|
||||
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
|
||||
-e AUTHGUARD_URL="https://auth.example.com" \
|
||||
-e SECRET="<long-random-shared-secret>" \
|
||||
collabtable:local
|
||||
```
|
||||
|
||||
@@ -80,7 +96,8 @@ Open **http://\<host\>:8080**, complete setup (this registers the first account
|
||||
cd backend
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/collabtable" go run .
|
||||
# Add AUTHGUARD_URL="http://localhost:8081" to authenticate against a local
|
||||
# AuthGuard instance instead of running with authentication disabled.
|
||||
# AuthGuard instance, or AUTH_DISABLED=true to run with authentication
|
||||
# disabled entirely.
|
||||
```
|
||||
|
||||
### Frontend
|
||||
@@ -109,8 +126,12 @@ Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emul
|
||||
```bash
|
||||
cd backend
|
||||
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
|
||||
npm test
|
||||
npm run check
|
||||
npm run lint
|
||||
```
|
||||
@@ -125,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`.
|
||||
- **`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:**
|
||||
|
||||
|
||||
@@ -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.
|
||||
+48
-5
@@ -7,16 +7,49 @@ APP_VERSION=dev
|
||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||
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)
|
||||
#################################################################
|
||||
# Base URL of the AuthGuard centralized identity service this app authenticates
|
||||
# through instead of a local user table.
|
||||
# through instead of a local user table. AuthGuard integration has three states:
|
||||
# - 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.
|
||||
# - AUTH_DISABLED=true: authentication is fully off (no login screen,
|
||||
# everything open).
|
||||
# AUTHGUARD_URL=https://auth.example.com
|
||||
# Leaving AUTHGUARD_URL unset does NOT fall back to any local account store --
|
||||
# it disables authentication entirely (no login screen, everything open).
|
||||
# Only run without it for local development or a deployment you are certain
|
||||
# does not need access control.
|
||||
# AUTH_DISABLED=true
|
||||
# Only set AUTH_DISABLED=true for local development or a deployment you are
|
||||
# certain does not need access control. Leaving AUTHGUARD_URL unset does NOT
|
||||
# do this -- it just leaves the service "pending" until ProjectConfigurator's
|
||||
# push arrives.
|
||||
|
||||
# Base URL of a CarrierNode instance, for the generic per-project mount API
|
||||
# (not used by any feature here yet).
|
||||
# CARRIERNODE_URL=https://carrier.example.com
|
||||
|
||||
# Shared secret CarrierNode and ProjectConfigurator were also configured with,
|
||||
# sent/checked as X-Internal-Auth. AUTHGUARD_URL and CARRIERNODE_URL above are
|
||||
# only the bootstrap fallback: once this project is registered in
|
||||
# ProjectConfigurator's Projects workspace, it pushes both values here
|
||||
# automatically (PUT /api/core-services/internal) and keeps them current --
|
||||
# see Core/ProjectConfigurator/README.md's "Pushing core service info to
|
||||
# other projects". That push is itself authenticated with this secret, so it
|
||||
# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A
|
||||
# push never overrides AUTH_DISABLED=true; it only ever retargets an
|
||||
# already-enabled AuthGuard connection.
|
||||
|
||||
#################################################################
|
||||
# PostgreSQL configuration
|
||||
@@ -40,3 +73,13 @@ SYNC_MAX_FUTURE_SKEW_MS=0
|
||||
|
||||
# Notification retention period in milliseconds (default: 7 days)
|
||||
NOTIF_RETENTION_MS=604800000
|
||||
|
||||
# Required shared-service authentication secret.
|
||||
SECRET=change-me-to-a-long-random-value
|
||||
# Set true only for local development or a standalone deployment.
|
||||
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=
|
||||
+96
-9
@@ -24,6 +24,7 @@ docker run -d --name collabtable-server --restart unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||
-e AUTHGUARD_URL=https://auth.example.com \
|
||||
-e SECRET=<long-random-shared-secret> \
|
||||
-e COOKIE_SECURE=false \
|
||||
collabtable-server
|
||||
```
|
||||
@@ -41,6 +42,10 @@ go test ./...
|
||||
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:
|
||||
|
||||
```bash
|
||||
@@ -55,6 +60,26 @@ go -C backend build -o collabtable-server .
|
||||
|
||||
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
|
||||
|
||||
All Android synchronization routes are prefixed with `/api/` and require:
|
||||
@@ -79,10 +104,14 @@ notification events.
|
||||
Browser authentication proxies to AuthGuard (`AUTHGUARD_URL`), which sets and reads its own
|
||||
`auth_session` HTTP-only cookie; CollabTable itself mints no session token. Any number of
|
||||
accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/auth/users`.
|
||||
`AUTHGUARD_URL` is optional: leaving it unset disables authentication entirely (no login
|
||||
screen, nothing gated) rather than falling back to any local account store -- only use that for
|
||||
local development or a deployment you are certain does not need access control. API tokens are
|
||||
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
|
||||
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
|
||||
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
||||
(the browser-session gate is off). List access still requires membership. In this mode requests
|
||||
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
|
||||
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
|
||||
|
||||
@@ -99,6 +128,14 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
- `POST /api/sync`
|
||||
- `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
|
||||
|
||||
- `GET /health` is public.
|
||||
@@ -110,12 +147,27 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
|
||||
- `PORT` — HTTP port, default `8080`
|
||||
- `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
|
||||
- `AUTHGUARD_URL` — base URL of the AuthGuard identity service CollabTable authenticates
|
||||
against, default unset (auth disabled). Leaving it unset does not fall back to any local
|
||||
account store -- it disables authentication entirely, treating every request as
|
||||
authenticated with nothing gated.
|
||||
- `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service
|
||||
CollabTable authenticates against, default unset (pending). 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` — set `true` to disable browser-session gates, default `false`. List access is
|
||||
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
|
||||
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_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||
@@ -124,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
|
||||
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
|
||||
|
||||
MIT
|
||||
+160
-978
File diff suppressed because it is too large.
Load diff
+46
-167
@@ -1,194 +1,73 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
)
|
||||
|
||||
// unreachableAuthGuardClient returns an authclient.Client pointed at a real
|
||||
// address that is guaranteed to refuse the connection: an httptest.Server
|
||||
// that has already been closed. This exercises a genuine transport-level
|
||||
// failure (connection refused), the same failure mode as "AUTHGUARD_URL is
|
||||
// configured but AuthGuard is down/unreachable", rather than simulating it by
|
||||
// hand.
|
||||
func unreachableAuthGuardClient(t *testing.T) *authclient.Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
url := srv.URL
|
||||
srv.Close()
|
||||
return authclient.New(url)
|
||||
}
|
||||
// The bulk of what auth_test.go used to cover (username/email normalization,
|
||||
// session-cookie parsing, AuthGuard-unreachable error surfacing, AuthGuard
|
||||
// error forwarding) is now sharedauth's own responsibility and covered by
|
||||
// that package's tests (shared/backend/auth). What's left to test here is
|
||||
// CollabTable's own tiny addition: the collabTableAuthStore adapter wired
|
||||
// into newAuthService (see auth.go).
|
||||
|
||||
func TestAuthNormalization(t *testing.T) {
|
||||
username, err := normalizeUsername(" admin ")
|
||||
if err != nil || username != "admin" {
|
||||
t.Fatalf("normalizeUsername() = %q, %v", username, err)
|
||||
}
|
||||
|
||||
email, err := normalizeEmail(" Admin@Example.COM ")
|
||||
if err != nil || email != "admin@example.com" {
|
||||
t.Fatalf("normalizeEmail() = %q, %v", email, err)
|
||||
}
|
||||
|
||||
if err := validatePassword("short"); err == nil {
|
||||
t.Fatal("validatePassword() accepted a short password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTokenReadsAuthGuardCookie(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
if got := a.sessionToken(req); got != "sometoken" {
|
||||
t.Fatalf("sessionToken() = %q, want %q", got, "sometoken")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTokenIgnoresLegacyCookieName(t *testing.T) {
|
||||
// The pre-migration collabtable_session cookie is no longer read as a
|
||||
// session credential; only AuthGuard's own auth_session cookie is.
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: legacySessionCookieName, Value: "stale-value"})
|
||||
|
||||
if got := a.sessionToken(req); got != "" {
|
||||
t.Fatalf("sessionToken() = %q, want empty for a legacy-only cookie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAuthGuardErrorForwardsAPIError(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeAuthGuardError(rec, &authclient.APIError{StatusCode: http.StatusConflict, Message: "username or email is already in use"}, "fallback")
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusConflict)
|
||||
}
|
||||
if body := rec.Body.String(); body == "" {
|
||||
t.Fatal("response body was empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAuthGuardErrorFallsBackForTransportFailures(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeAuthGuardError(rec, errors.New("dial tcp: connection refused"), "unable to reach AuthGuard")
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUserIDUsesPlaceholderWhenAuthDisabled(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
|
||||
|
||||
id, ok, err := a.currentUserID(req)
|
||||
func TestCollabTableAuthStoreLoginRequiredAlwaysTrue(t *testing.T) {
|
||||
store := collabTableAuthStore{}
|
||||
required, err := store.LoginRequired(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("currentUserID() error = %v, want nil in disabled mode", err)
|
||||
t.Fatalf("LoginRequired() error = %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("currentUserID() ok = false, want true in disabled mode (every request shares the placeholder identity)")
|
||||
}
|
||||
if id != localProfile.ID {
|
||||
t.Fatalf("currentUserID() id = %d, want %d (localProfile.ID)", id, localProfile.ID)
|
||||
if !required {
|
||||
t.Fatal("LoginRequired() = false, want true: CollabTable always requires a session when AuthGuard is configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSessionLetsRequestThroughWhenAuthDisabled(t *testing.T) {
|
||||
a := &AuthService{}
|
||||
nextCalled := false
|
||||
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
nextCalled = true
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/tech-stack", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if !nextCalled {
|
||||
t.Fatal("requireSession did not let the request through despite auth being disabled (AUTHGUARD_URL unset)")
|
||||
func TestCollabTableAuthStoreSetLoginRequiredIsNoOp(t *testing.T) {
|
||||
store := collabTableAuthStore{}
|
||||
if err := store.SetLoginRequired(context.Background(), false); err != nil {
|
||||
t.Fatalf("SetLoginRequired() error = %v, want nil (CollabTable has no such toggle)", err)
|
||||
}
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||
// Confirm it really didn't change anything observable.
|
||||
required, err := store.LoginRequired(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("LoginRequired() error = %v", err)
|
||||
}
|
||||
if !required {
|
||||
t.Fatal("SetLoginRequired(false) unexpectedly changed LoginRequired()'s answer")
|
||||
}
|
||||
}
|
||||
|
||||
// The following tests cover the specific failure mode of AUTHGUARD_URL being
|
||||
// configured but AuthGuard being unreachable (connection refused). This must
|
||||
// never be silently treated as "no session" (which would either let an
|
||||
// unauthenticated request through, for requireSession, or show a bare "please
|
||||
// log in" screen with no indication anything is wrong, for handleStatus) --
|
||||
// it must surface as a distinct, visible error. See currentUser/
|
||||
// currentProfile's doc comments and errAuthGuardUnavailable.
|
||||
|
||||
func TestCurrentUserSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
user, err := a.currentUser(req)
|
||||
if err == nil {
|
||||
t.Fatal("currentUser() returned no error for an unreachable AuthGuard; want a transport error")
|
||||
}
|
||||
if errors.Is(err, authclient.ErrInvalidSession) {
|
||||
t.Fatal("currentUser() classified a transport failure as ErrInvalidSession -- this would make requireSession treat 'AuthGuard is down' as 'not logged in' instead of a 500")
|
||||
}
|
||||
if user != nil {
|
||||
t.Fatalf("currentUser() returned a user (%+v) despite AuthGuard being unreachable", user)
|
||||
func TestNewAuthServiceBuildsAService(t *testing.T) {
|
||||
// newAuthService must not panic given a nil *DB and no AuthGuard URL
|
||||
// ("pending" mode) -- the store adapter's IsSetupClaimed/TryClaimSetup/
|
||||
// UnclaimSetup only get called once a real request comes in and AuthGuard
|
||||
// is enabled, so construction alone must be safe.
|
||||
if service := newAuthService(nil, "", false, false); service == nil {
|
||||
t.Fatal("newAuthService() returned nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentProfileSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
|
||||
profile, token, err := a.currentProfile(req)
|
||||
if err == nil {
|
||||
t.Fatal("currentProfile() returned no error for an unreachable AuthGuard; want a transport error")
|
||||
}
|
||||
if profile != nil {
|
||||
t.Fatalf("currentProfile() returned a profile (%+v) despite AuthGuard being unreachable", profile)
|
||||
}
|
||||
if token != "" {
|
||||
t.Fatalf("currentProfile() returned a token (%q) alongside an error", token)
|
||||
func TestNewAuthServiceBuildsADisabledService(t *testing.T) {
|
||||
// authDisabled=true must also not panic given a nil *DB and no AuthGuard
|
||||
// URL -- this is the explicit auth-disabled mode (sharedauth.Disabled()).
|
||||
if service := newAuthService(nil, "", false, true); service == nil {
|
||||
t.Fatal("newAuthService() returned nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUserIDSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
func TestExtractBearerRequiresBearerPrefix(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
req.Header.Set("Authorization", "Bearer sometoken")
|
||||
if got := extractBearer(req); got != "sometoken" {
|
||||
t.Fatalf("extractBearer() = %q, want %q", got, "sometoken")
|
||||
}
|
||||
|
||||
if _, ok, err := a.currentUserID(req); err == nil || ok {
|
||||
t.Fatalf("currentUserID() = (ok=%v, err=%v), want ok=false and a non-nil transport error", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSessionReturns500RatherThanLettingRequestThroughWhenAuthGuardUnreachable(t *testing.T) {
|
||||
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
|
||||
nextCalled := false
|
||||
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
nextCalled = true
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if nextCalled {
|
||||
t.Fatal("requireSession let the request through to the wrapped handler despite AuthGuard being unreachable")
|
||||
}
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d (must not be 401 'please log in' or 200)", rec.Code, http.StatusInternalServerError)
|
||||
}
|
||||
if body := rec.Body.String(); !strings.Contains(strings.ToLower(body), "authentication service") {
|
||||
t.Fatalf("response body = %q, want a message identifying the authentication service as the problem", body)
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/lists", nil)
|
||||
req.Header.Set("Authorization", "sometoken")
|
||||
if got := extractBearer(req); got != "" {
|
||||
t.Fatalf("extractBearer() = %q, want empty for a header missing the Bearer prefix", got)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 1)
|
||||
func (d *DB) queryLists(ctx context.Context, userID int64, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
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 {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
conditions = append(conditions, "updatedat >= $1")
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
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...)
|
||||
if err != nil {
|
||||
@@ -98,9 +100,11 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
||||
return lists, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryFields(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
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 {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
@@ -116,7 +120,7 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
||||
if len(conditions) > 0 {
|
||||
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...)
|
||||
if err != nil {
|
||||
@@ -134,9 +138,11 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
||||
return fields, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryItems(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
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 {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
@@ -152,7 +158,7 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
||||
if len(conditions) > 0 {
|
||||
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...)
|
||||
if err != nil {
|
||||
@@ -170,9 +176,11 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryValues(ctx context.Context, userID int64, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
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 {
|
||||
args = append(args, *since)
|
||||
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 {
|
||||
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...)
|
||||
if err != nil {
|
||||
@@ -220,6 +228,132 @@ func boolInt(value bool) int {
|
||||
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 {
|
||||
List
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
@@ -227,7 +361,11 @@ type listMutation struct {
|
||||
|
||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||
return
|
||||
@@ -237,23 +375,42 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var request listMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.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))
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
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 errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
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)
|
||||
if err != nil {
|
||||
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")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if !s.requireListMembership(w, r, id) {
|
||||
return
|
||||
}
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
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"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var list List
|
||||
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 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")
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
@@ -308,16 +485,38 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodDelete:
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||
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"})
|
||||
}
|
||||
}
|
||||
@@ -328,7 +527,15 @@ type fieldMutation struct {
|
||||
}
|
||||
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||
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) {
|
||||
var request fieldMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
_, err := s.db.pool.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))
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
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), request.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
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 errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
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)
|
||||
if err != nil {
|
||||
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"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var field Field
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var listID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields 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 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")
|
||||
return
|
||||
}
|
||||
field, err := s.getField(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, field)
|
||||
case http.MethodDelete:
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
||||
_ = decodeJSON(w, r, &request) // DELETE bodies are optional.
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
var field Field
|
||||
cascade := false
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
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 {
|
||||
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
|
||||
}
|
||||
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 {
|
||||
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))
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
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")
|
||||
return
|
||||
}
|
||||
@@ -478,7 +717,14 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||
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) {
|
||||
var request itemMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.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))
|
||||
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), 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 errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
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)
|
||||
if err != nil {
|
||||
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]
|
||||
}
|
||||
}
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
return
|
||||
@@ -538,37 +820,65 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
||||
ItemValue
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
if err := decodeJSON(w, r, &request); err != nil {
|
||||
writeDecodeError(w, err, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
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
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
&value.ID,
|
||||
&value.ItemID,
|
||||
&value.FieldID,
|
||||
&value.Value,
|
||||
&value.UpdatedAt,
|
||||
)
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var fieldListID, itemListID string
|
||||
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 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")
|
||||
return
|
||||
}
|
||||
@@ -584,41 +894,91 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||
_ = decodeJSON(r, &request)
|
||||
_ = decodeJSON(w, r, &request)
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var item Item
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
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")
|
||||
return
|
||||
}
|
||||
item, err := s.getItem(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
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 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")
|
||||
return
|
||||
}
|
||||
item, itemErr := s.getItem(r.Context(), id)
|
||||
if itemErr == nil {
|
||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
+135
-41
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
// be used by the Go server without a separate migration step.
|
||||
func (d *DB) initSchema(ctx context.Context) error {
|
||||
@@ -44,7 +50,8 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
name TEXT NOT NULL,
|
||||
createdat 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 (
|
||||
@@ -58,6 +65,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
@@ -67,6 +75,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
@@ -76,6 +85,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
fieldid TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedat BIGINT NOT NULL,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (itemid) REFERENCES items(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_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_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 (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -152,16 +214,16 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
CHECK (id = 1)
|
||||
);
|
||||
|
||||
-- authguard_totp_cache is a best-effort, locally-cached mirror of "does
|
||||
-- this AuthGuard account have TOTP enabled", keyed by AuthGuard's own
|
||||
-- numeric user id. AuthGuard's HTTP API (deliberately not modified by
|
||||
-- this migration) has no endpoint to query current TOTP status, only to
|
||||
-- enable/verify/disable it, so CollabTable keeps this cache updated
|
||||
-- itself at every point it can observe the true state (successful TOTP
|
||||
-- verify/disable calls, and a successful login attempted without a TOTP
|
||||
-- token, which AuthGuard would have rejected had TOTP been enabled). See
|
||||
-- handleTOTPStatus's doc comment in auth.go for the full reasoning and
|
||||
-- its known staleness caveat.
|
||||
-- authguard_totp_cache is RETIRED as of the migration onto
|
||||
-- shared/backend/auth (sharedauth.Service): it used to be a
|
||||
-- best-effort, locally-cached mirror of "does this AuthGuard account
|
||||
-- have TOTP enabled", keyed by AuthGuard's own numeric user id, needed
|
||||
-- because AuthGuard's HTTP API had no endpoint to query current TOTP
|
||||
-- status, only to enable/verify/disable it. sharedauth.Service's
|
||||
-- Me/Status/TOTPStatus now read TOTP-enabled status live from
|
||||
-- AuthGuard's GET /api/me on every request instead, so no Go code
|
||||
-- reads or writes this table anymore. Left in place rather than
|
||||
-- dropped, same as auth_users/auth_sessions above.
|
||||
CREATE TABLE IF NOT EXISTS authguard_totp_cache (
|
||||
authguard_user_id BIGINT PRIMARY KEY,
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
@@ -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);
|
||||
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 {
|
||||
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
|
||||
}
|
||||
|
||||
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) {
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
@@ -203,7 +315,7 @@ func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||
return
|
||||
case <-ticker.C:
|
||||
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:
|
||||
cutoff := time.Now().UnixMilli() - retention
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,34 +388,16 @@ func (d *DB) UnclaimSetup(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled
|
||||
// state for an AuthGuard account, or false if this instance has never
|
||||
// observed that account's TOTP state. See handleTOTPStatus's doc comment in
|
||||
// auth.go.
|
||||
func (d *DB) GetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64) (bool, error) {
|
||||
var enabled bool
|
||||
err := d.pool.QueryRow(ctx, `SELECT totp_enabled FROM authguard_totp_cache WHERE authguard_user_id = $1`, authGuardUserID).Scan(&enabled)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("get cached totp state: %w", err)
|
||||
}
|
||||
return enabled, nil
|
||||
}
|
||||
|
||||
// SetCachedTOTPEnabled upserts the best-effort locally-cached TOTP-enabled
|
||||
// state for an AuthGuard account.
|
||||
func (d *DB) SetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64, enabled bool) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
INSERT INTO authguard_totp_cache (authguard_user_id, totp_enabled, updated_at) VALUES ($1, $2, now())
|
||||
ON CONFLICT (authguard_user_id) DO UPDATE SET totp_enabled = $2, updated_at = now()
|
||||
`, authGuardUserID, enabled)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set cached totp state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Note: this instance used to also keep a local best-effort cache of each
|
||||
// AuthGuard account's TOTP-enabled state (GetCachedTOTPEnabled/
|
||||
// SetCachedTOTPEnabled, backed by the authguard_totp_cache table above) --
|
||||
// that existed only because the pre-migration code believed AuthGuard could
|
||||
// not report TOTP status live. It can (GET /api/me), so sharedauth.Service's
|
||||
// Me/Status/TOTPStatus now read it live from AuthGuard directly and this
|
||||
// cache's Go code was deleted along with the migration onto that shared
|
||||
// package. The authguard_totp_cache table itself (and any rows already in
|
||||
// it) is left in place rather than dropped, same as auth_users/auth_sessions
|
||||
// above.
|
||||
|
||||
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// envInt64 returns the parsed environment value or fallback when the variable
|
||||
// is unset, empty, or not a valid base-10 int64.
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
parsed, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEnvInt64(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value string
|
||||
fallback int64
|
||||
want int64
|
||||
}{
|
||||
{name: "valid", value: "1234567890123", fallback: 7, want: 1234567890123},
|
||||
{name: "trimmed", value: " 42 ", fallback: 7, want: 42},
|
||||
{name: "empty", value: "", fallback: 7, want: 7},
|
||||
{name: "invalid", value: "not-a-number", fallback: 7, want: 7},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Setenv("COLLABTABLE_TEST_ENV_INT64", test.value)
|
||||
if got := envInt64("COLLABTABLE_TEST_ENV_INT64", test.fallback); got != test.want {
|
||||
t.Fatalf("envInt64() = %d, want %d", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvInt64UsesFallbackWhenUnset(t *testing.T) {
|
||||
t.Setenv("COLLABTABLE_TEST_ENV_INT64", "")
|
||||
if got := envInt64("COLLABTABLE_TEST_ENV_INT64_UNSET", 99); got != 99 {
|
||||
t.Fatalf("envInt64() = %d, want 99", got)
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -9,13 +9,16 @@ require (
|
||||
|
||||
replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../shared/backend
|
||||
|
||||
require golang.org/x/crypto v0.54.0 // indirect
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
||||
golang.org/x/crypto v0.55.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // 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
|
||||
)
|
||||
+6
-4
@@ -1,6 +1,8 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -18,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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
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.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
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/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
+16
-6
@@ -86,6 +86,7 @@ type ItemValue struct {
|
||||
|
||||
type SyncRequest struct {
|
||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||
LastSyncToken *int64 `json:"lastSyncToken"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
@@ -94,12 +95,21 @@ type SyncRequest struct {
|
||||
}
|
||||
|
||||
type SyncResponse struct {
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
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 {
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||
)
|
||||
|
||||
type queryExecutor interface {
|
||||
@@ -41,6 +43,31 @@ func enqueueNotification(
|
||||
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 {
|
||||
if value == "" {
|
||||
return nil
|
||||
@@ -48,14 +75,12 @@ func nullableString(value string) any {
|
||||
return value
|
||||
}
|
||||
|
||||
// ignoreNotificationError logs a failed notification. Use it only for
|
||||
// notifications written by enqueueNotificationInTx or outside a transaction.
|
||||
func ignoreNotificationError(err error) {
|
||||
if err != nil {
|
||||
// Notifications are an acceleration path for clients that poll. A failed
|
||||
// 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 (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegisterRoutes(t *testing.T) {
|
||||
server := &Server{auth: &AuthService{}}
|
||||
server.registerRoutes(http.NewServeMux(), webFS)
|
||||
// Auth is disabled and there is no database, so these checks only touch
|
||||
// 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.
+270
-79
@@ -1,12 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
@@ -16,7 +19,10 @@ import (
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
|
||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||
)
|
||||
|
||||
// The SvelteKit build is copied here by the Docker builder before go build.
|
||||
@@ -27,17 +33,48 @@ import (
|
||||
var webFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
db *DB
|
||||
auth *AuthService
|
||||
startTime time.Time
|
||||
db *DB
|
||||
auth *sharedauth.Service
|
||||
startTime time.Time
|
||||
internalServiceSecret string
|
||||
coreConfig *coreconfig.Store
|
||||
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() {
|
||||
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")
|
||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
if connectionString == "" {
|
||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
||||
os.Exit(1)
|
||||
logErrorln(logshipper.LevelCritical, "DATABASE_URL environment variable is required")
|
||||
exitAfterFlush(1)
|
||||
}
|
||||
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())
|
||||
@@ -45,68 +82,101 @@ func main() {
|
||||
|
||||
database, err := connectWithRetry(ctx, connectionString)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
logErrorf(logshipper.LevelCritical, "database initialization failed: %v\n", err)
|
||||
exitAfterFlush(1)
|
||||
}
|
||||
defer database.close()
|
||||
go database.pruneExpiredSessions(ctx)
|
||||
go database.cleanupNotifications(ctx)
|
||||
|
||||
// AuthGuard is optional (see auth.go's top-of-file "Auth-disabled mode"
|
||||
// section): a nil client means every request is treated as already
|
||||
// authenticated, with nothing gated -- an explicit choice for local
|
||||
// development or a standalone deployment, not a degraded fallback.
|
||||
// AuthGuard integration has three states now (see auth.go's top-of-file
|
||||
// doc comment and sharedauth's own "Auth-disabled mode" section): an
|
||||
// AUTHGUARD_URL set is used immediately; unset with AUTH_DISABLED
|
||||
// unset/false is "pending" (fully gated, failing closed until
|
||||
// ProjectConfigurator's push arrives); AUTH_DISABLED=true is an explicit
|
||||
// opt-out where every request is treated as already authenticated, with
|
||||
// nothing gated -- for local development or a standalone deployment, not
|
||||
// a degraded fallback.
|
||||
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
|
||||
var authGuard *authclient.Client
|
||||
if authGuardURL != "" {
|
||||
authGuard = authclient.New(authGuardURL)
|
||||
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
|
||||
} else {
|
||||
fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated")
|
||||
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
||||
switch {
|
||||
case authDisabled:
|
||||
logPrintln(logshipper.LevelWarn, "auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
||||
case authGuardURL != "":
|
||||
logPrintf(logshipper.LevelInfo, "auth: AuthGuard at %s\n", authGuardURL)
|
||||
default:
|
||||
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(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
server := &Server{db: database, auth: auth, startTime: time.Now()}
|
||||
// coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project
|
||||
// is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and
|
||||
// CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives.
|
||||
// See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects".
|
||||
// auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds
|
||||
// internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it
|
||||
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
||||
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
||||
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
||||
omniShipper.Follow(coreConfig)
|
||||
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
||||
if info.AuthGuardURL != "" {
|
||||
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
||||
}
|
||||
})
|
||||
server := &Server{
|
||||
db: database,
|
||||
auth: auth,
|
||||
startTime: time.Now(),
|
||||
internalServiceSecret: internalServiceSecret,
|
||||
coreConfig: coreConfig,
|
||||
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||
trustedProxies: trustedProxies,
|
||||
}
|
||||
|
||||
webRoot, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
||||
os.Exit(1)
|
||||
logErrorf(logshipper.LevelCritical, "embedded web assets missing: %v\n", err)
|
||||
exitAfterFlush(1)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
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{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(mux),
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
||||
logPrintf(logshipper.LevelInfo, "CollabTable Go server listening on :%s\n", port)
|
||||
logPrintf(logshipper.LevelInfo, "Database: PostgreSQL (pgx)\n")
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
||||
os.Exit(1)
|
||||
logErrorf(logshipper.LevelCritical, "server error: %v\n", err)
|
||||
exitAfterFlush(1)
|
||||
}
|
||||
}
|
||||
|
||||
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
|
||||
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
|
||||
if interval < 250*time.Millisecond {
|
||||
interval = 250 * time.Millisecond
|
||||
}
|
||||
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
|
||||
retryOptions := sharedpostgres.StartupRetryOptionsFromEnv()
|
||||
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
database, err := connectDB(ctx, connectionString)
|
||||
if err == nil {
|
||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||
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
|
||||
} else {
|
||||
@@ -115,44 +185,53 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if maxAttempts > 0 && attempt >= maxAttempts {
|
||||
logErrorf(logshipper.LevelWarn, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("[DB] Retrying in %s...\n", interval)
|
||||
logPrintf(logshipper.LevelWarn, "[DB] Retrying in %s...\n", retryOptions.Interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(interval):
|
||||
case <-time.After(retryOptions.Interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
mux.HandleFunc("GET /health", s.handleHealth)
|
||||
mux.HandleFunc("GET /api/info", s.handleInfo)
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout)))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(http.HandlerFunc(s.auth.handleUpdateCredentials)))
|
||||
mux.Handle("GET /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPStatus)))
|
||||
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPSetup)))
|
||||
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPEnable)))
|
||||
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPDisable)))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenStatus)))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenRegenerate)))
|
||||
// X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly
|
||||
// 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.HandleFunc("GET /api/auth/status", s.auth.Status)
|
||||
mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup)))
|
||||
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("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)))
|
||||
// Managed-user routes check the caller's role here, not only in AuthGuard.
|
||||
mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers)))
|
||||
mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser)))
|
||||
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
|
||||
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser)))
|
||||
mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))))
|
||||
mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))))
|
||||
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("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
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
api := func(handler http.Handler) http.Handler {
|
||||
return s.auth.requireAPIToken(handler)
|
||||
return requireAPIToken(s.db)(handler)
|
||||
}
|
||||
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
@@ -177,8 +256,8 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
|
||||
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
|
||||
// are protected by the browser session.
|
||||
mux.Handle("GET /api/tech-stack", s.auth.requireSession(http.HandlerFunc(s.handleTechStack)))
|
||||
mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData)))
|
||||
mux.Handle("GET /api/tech-stack", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTechStack)))
|
||||
mux.Handle("GET /web/data", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleWebData)))
|
||||
mux.Handle("/", spaFileServer(webRoot))
|
||||
}
|
||||
|
||||
@@ -199,8 +278,7 @@ func (s *Server) handleInfo(w http.ResponseWriter, _ *http.Request) {
|
||||
"ok": true,
|
||||
"name": "CollabTable",
|
||||
"tabs": []map[string]string{
|
||||
{"label": "Overview", "token": "/"},
|
||||
{"label": "About", "token": "/about"},
|
||||
{"key": "overview", "label": "Overview", "token": "/"},
|
||||
},
|
||||
"mountTypes": []string{},
|
||||
})
|
||||
@@ -213,24 +291,24 @@ func envOrDefault(name, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
var parsed int64
|
||||
if _, err := fmt.Sscan(value, &parsed); err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
|
||||
return decodeJSONLimit(w, r, target, jsonBodyLimit)
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
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) {
|
||||
@@ -246,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) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
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 {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
if permitted {
|
||||
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)
|
||||
return
|
||||
}
|
||||
@@ -264,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 {
|
||||
fileServer := http.FileServer(http.FS(root))
|
||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -273,10 +452,15 @@ func spaFileServer(root fs.FS) http.Handler {
|
||||
return
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
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), "/")
|
||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||
serveIndex(w, r)
|
||||
@@ -286,6 +470,13 @@ func spaFileServer(root fs.FS) http.Handler {
|
||||
serveIndex(w, r)
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"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 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
if value < 0 {
|
||||
@@ -42,208 +50,415 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
||||
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) {
|
||||
// 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
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
||||
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
deviceID := requestDeviceID(r, request.DeviceID)
|
||||
batch := syncBatch{now: now, userID: requestUserID(r), initialSync: *request.LastSyncToken == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||
orphans := make([]OrphanValue, 0)
|
||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||
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 {
|
||||
for _, list := range request.Lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
||||
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
|
||||
}
|
||||
}
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, field := range request.Fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
||||
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
|
||||
var err error
|
||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||
return err
|
||||
})
|
||||
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")
|
||||
return
|
||||
}
|
||||
|
||||
var since *int64
|
||||
if lastSync != 0 {
|
||||
since = &lastSync
|
||||
}
|
||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
||||
response, err := s.db.changesSince(r.Context(), requestUserID(r), *request.LastSyncToken)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
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(),
|
||||
})
|
||||
response.OrphanItemValues = orphans
|
||||
response.ServerTimestamp = time.Now().UnixMilli()
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
@@ -25,3 +25,24 @@ func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
|
||||
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
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
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 {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
||||
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
||||
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
||||
values, err := s.db.queryValues(r.Context(), userID, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
@@ -71,10 +79,7 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
||||
}
|
||||
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
w.Header().Set("Expires", "0")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
payload := map[string]any{
|
||||
"lists": webLists,
|
||||
"fields": fields,
|
||||
"items": items,
|
||||
@@ -85,8 +90,41 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||
"items": len(items),
|
||||
"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) {
|
||||
@@ -100,10 +138,14 @@ func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request)
|
||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||
FROM notifications
|
||||
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 != "" {
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
|
||||
args = append(args, deviceID)
|
||||
}
|
||||
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/node-backend/package.json /shared/packages/node-backend/
|
||||
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 \
|
||||
for attempt in 1 2 3 4 5; do \
|
||||
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/node-backend /shared/packages/node-backend
|
||||
COPY shared/packages/web-ui /shared/packages/web-ui
|
||||
RUN npm run build --prefix /shared
|
||||
COPY frontend/ ./
|
||||
RUN rm -rf /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
|
||||
USER 65534:65534
|
||||
EXPOSE 8080
|
||||
VOLUME ["/data"]
|
||||
ENV PORT=8080
|
||||
ENTRYPOINT ["/server"]
|
||||
@@ -1,5 +1,7 @@
|
||||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"extends": "$app/tsconfig",
|
||||
"include": ["src", "test", "*"],
|
||||
"exclude": ["src/service-worker"],
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": false,
|
||||
|
||||
Generated
+181
-251
@@ -8,6 +8,7 @@
|
||||
"name": "collabtable-server-frontend",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||
"@lucide/svelte": "latest",
|
||||
"@tanstack/svelte-query": "latest",
|
||||
@@ -18,8 +19,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "latest",
|
||||
"@sveltejs/adapter-static": "latest",
|
||||
"@sveltejs/kit": "latest",
|
||||
"@sveltejs/adapter-static": "^4.0.1",
|
||||
"@sveltejs/kit": "^3.1.1",
|
||||
"@sveltejs/vite-plugin-svelte": "latest",
|
||||
"@tailwindcss/vite": "latest",
|
||||
"eslint": "latest",
|
||||
@@ -27,13 +28,18 @@
|
||||
"eslint-plugin-svelte": "latest",
|
||||
"prettier": "latest",
|
||||
"prettier-plugin-svelte": "latest",
|
||||
"svelte": "latest",
|
||||
"svelte": "^5.57.3",
|
||||
"svelte-check": "latest",
|
||||
"tailwindcss": "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": {
|
||||
"name": "@gabriel20xx/web-ui",
|
||||
"version": "0.1.1",
|
||||
@@ -52,37 +58,6 @@
|
||||
"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": {
|
||||
"version": "4.10.1",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
||||
@@ -236,6 +211,10 @@
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@gabriel20xx/design-tokens": {
|
||||
"resolved": "../shared/packages/design-tokens",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gabriel20xx/web-ui": {
|
||||
"resolved": "../shared/packages/web-ui",
|
||||
"link": true
|
||||
@@ -346,9 +325,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
"version": "1.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
|
||||
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@jridgewell/trace-mapping": {
|
||||
@@ -370,35 +349,14 @@
|
||||
"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": {
|
||||
"version": "0.142.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz",
|
||||
"integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
|
||||
"version": "0.155.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
|
||||
"integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/Boshen"
|
||||
"url": "https://github.com/sponsors/oxc-project"
|
||||
}
|
||||
},
|
||||
"node_modules/@polka/url": {
|
||||
@@ -408,10 +366,26 @@
|
||||
"devOptional": true,
|
||||
"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": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.1.tgz",
|
||||
"integrity": "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz",
|
||||
"integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -425,9 +399,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.1.tgz",
|
||||
"integrity": "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz",
|
||||
"integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -441,9 +415,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-x64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.1.tgz",
|
||||
"integrity": "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz",
|
||||
"integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -457,9 +431,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.1.tgz",
|
||||
"integrity": "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz",
|
||||
"integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -473,9 +447,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.1.tgz",
|
||||
"integrity": "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz",
|
||||
"integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -489,9 +463,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz",
|
||||
"integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -508,9 +482,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.1.tgz",
|
||||
"integrity": "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz",
|
||||
"integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -527,9 +501,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz",
|
||||
"integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -546,9 +520,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz",
|
||||
"integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -565,9 +539,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz",
|
||||
"integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -584,9 +558,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.1.tgz",
|
||||
"integrity": "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz",
|
||||
"integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -603,9 +577,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.1.tgz",
|
||||
"integrity": "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz",
|
||||
"integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -618,25 +592,10 @@
|
||||
"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": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.1.tgz",
|
||||
"integrity": "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz",
|
||||
"integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -650,9 +609,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.1.tgz",
|
||||
"integrity": "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz",
|
||||
"integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -680,56 +639,53 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@sveltejs/acorn-typescript": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
|
||||
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
|
||||
"version": "1.0.13",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
|
||||
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"acorn": "^8.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@sveltejs/adapter-static": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-3.0.10.tgz",
|
||||
"integrity": "sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==",
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-4.0.1.tgz",
|
||||
"integrity": "sha512-svOU1OcBiJ9Kn1cdxHDmJIsBy1/iQe9STPvUFkO2/iinxPFS7r8fc9TiCaWWUgbrE+7ox6Bt4MURv3RPi7sunQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@sveltejs/kit": "^2.0.0"
|
||||
"@sveltejs/kit": "^3.0.0-next.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@sveltejs/kit": {
|
||||
"version": "2.70.2",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.2.tgz",
|
||||
"integrity": "sha512-RzRoRpuR2KXqc5yMO0akQHDZeT4AslOlznGITURsqHaVbtyYP4Wn3eE3gxj9JcDyNYO0crkxhdwFHc+2vkVm6w==",
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-3.2.0.tgz",
|
||||
"integrity": "sha512-zhb8GTeFd/6BwfqaY4wKIF7eFACYOgn/KNppV6UHFBHk174B4d7xTtN7x0PxaPPlwnCTgbnpaYF6r9lirz0Biw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"@sveltejs/acorn-typescript": "^1.0.9",
|
||||
"@types/cookie": "^0.6.0",
|
||||
"acorn": "^8.16.0",
|
||||
"cookie": "^0.6.0",
|
||||
"devalue": "^5.8.1",
|
||||
"@jridgewell/trace-mapping": "^0.3.31",
|
||||
"@rolldown/pluginutils": "^1.0.1",
|
||||
"@standard-schema/spec": "^1.1.0",
|
||||
"cookie": "^2.0.1",
|
||||
"devalue": "^5.9.4",
|
||||
"esm-env": "^1.2.2",
|
||||
"kleur": "^4.1.5",
|
||||
"magic-string": "^0.30.5",
|
||||
"mrmime": "^2.0.0",
|
||||
"set-cookie-parser": "^3.0.0",
|
||||
"sirv": "^3.0.0"
|
||||
"magic-string": "^1.2.3",
|
||||
"mrmime": "^2.0.1",
|
||||
"sirv": "^3.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"svelte-kit": "svelte-kit.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.13"
|
||||
"node": ">=22.17"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@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",
|
||||
"svelte": "^4.0.0 || ^5.0.0-next.0",
|
||||
"typescript": "^5.3.3 || ^6.0.0",
|
||||
"vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0"
|
||||
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||
"svelte": "^5.57.1",
|
||||
"typescript": "^6.0.0",
|
||||
"vite": "^8.0.12"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@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": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz",
|
||||
@@ -1156,23 +1122,6 @@
|
||||
"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": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
|
||||
@@ -1193,12 +1142,6 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
||||
@@ -1291,9 +1234,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -1341,13 +1284,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz",
|
||||
"integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz",
|
||||
"integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
"node": ">=22"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
@@ -1433,9 +1380,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/devalue": {
|
||||
"version": "5.9.0",
|
||||
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz",
|
||||
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==",
|
||||
"version": "5.9.4",
|
||||
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
|
||||
"integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/enhanced-resolve": {
|
||||
@@ -1644,9 +1591,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/esrap": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
|
||||
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
|
||||
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||
@@ -1936,16 +1883,6 @@
|
||||
"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": {
|
||||
"version": "0.37.0",
|
||||
"resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz",
|
||||
@@ -2334,9 +2271,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"version": "3.3.20",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
|
||||
"devOptional": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2451,9 +2388,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
|
||||
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
||||
"version": "4.0.7",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -2464,9 +2401,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.25",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
||||
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
||||
"version": "8.5.32",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
|
||||
"integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
|
||||
"devOptional": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2484,9 +2421,9 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.16",
|
||||
"nanoid": "^3.3.20",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
"source-map-js": "^1.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || >=14"
|
||||
@@ -2665,13 +2602,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz",
|
||||
"integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==",
|
||||
"version": "1.2.15",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz",
|
||||
"integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@oxc-project/types": "=0.142.0",
|
||||
"@oxc-project/types": "=0.155.0",
|
||||
"@rolldown/pluginutils": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
@@ -2681,21 +2618,21 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@rolldown/binding-android-arm64": "1.2.1",
|
||||
"@rolldown/binding-darwin-arm64": "1.2.1",
|
||||
"@rolldown/binding-darwin-x64": "1.2.1",
|
||||
"@rolldown/binding-freebsd-x64": "1.2.1",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.1",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.2.1",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.2.1",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.1",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.2.1",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.2.1",
|
||||
"@rolldown/binding-linux-x64-musl": "1.2.1",
|
||||
"@rolldown/binding-openharmony-arm64": "1.2.1",
|
||||
"@rolldown/binding-wasm32-wasi": "1.2.1",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.2.1",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.2.1"
|
||||
"@rolldown/binding-android-arm-eabi": "1.2.15",
|
||||
"@rolldown/binding-android-arm64": "1.2.15",
|
||||
"@rolldown/binding-darwin-arm64": "1.2.15",
|
||||
"@rolldown/binding-darwin-x64": "1.2.15",
|
||||
"@rolldown/binding-freebsd-x64": "1.2.15",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.15",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.2.15",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.2.15",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.15",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.2.15",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.2.15",
|
||||
"@rolldown/binding-linux-x64-musl": "1.2.15",
|
||||
"@rolldown/binding-openharmony-arm64": "1.2.15",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.2.15",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.2.15"
|
||||
}
|
||||
},
|
||||
"node_modules/runed": {
|
||||
@@ -2748,13 +2685,6 @@
|
||||
"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": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
@@ -2794,9 +2724,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
|
||||
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
|
||||
"devOptional": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
@@ -2813,23 +2743,22 @@
|
||||
}
|
||||
},
|
||||
"node_modules/svelte": {
|
||||
"version": "5.56.8",
|
||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
|
||||
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
|
||||
"version": "5.57.3",
|
||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
|
||||
"integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/remapping": "^2.3.4",
|
||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
||||
"@sveltejs/acorn-typescript": "^1.0.10",
|
||||
"@types/estree": "^1.0.5",
|
||||
"@types/trusted-types": "^2.0.7",
|
||||
"acorn": "^8.12.1",
|
||||
"@jridgewell/remapping": "^2.3.5",
|
||||
"@jridgewell/sourcemap-codec": "^1.6.0",
|
||||
"@sveltejs/acorn-typescript": "^1.0.13",
|
||||
"@types/estree": "^1.0.9",
|
||||
"acorn": "^8.18.0",
|
||||
"aria-query": "5.3.1",
|
||||
"axobject-query": "^4.1.0",
|
||||
"clsx": "^2.1.1",
|
||||
"devalue": "^5.8.1",
|
||||
"devalue": "^5.9.2",
|
||||
"esm-env": "^1.2.1",
|
||||
"esrap": "^2.2.12",
|
||||
"esrap": "^2.3.6",
|
||||
"is-reference": "^3.0.3",
|
||||
"locate-character": "^3.0.0",
|
||||
"magic-string": "^0.30.11",
|
||||
@@ -3031,7 +2960,8 @@
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
"license": "0BSD",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/tw-animate-css": {
|
||||
"version": "1.4.0",
|
||||
@@ -3089,16 +3019,16 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
|
||||
"integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
|
||||
"version": "8.3.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz",
|
||||
"integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lightningcss": "^1.33.0",
|
||||
"picomatch": "^4.0.5",
|
||||
"postcss": "^8.5.23",
|
||||
"rolldown": "~1.2.0",
|
||||
"picomatch": "^4.0.7",
|
||||
"postcss": "^8.5.28",
|
||||
"rolldown": "~1.2.11",
|
||||
"tinyglobby": "^0.2.17"
|
||||
},
|
||||
"bin": {
|
||||
@@ -3115,7 +3045,7 @@
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@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",
|
||||
"jiti": ">=1.21.0",
|
||||
"less": "^4.0.0",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --write .",
|
||||
@@ -14,8 +15,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "latest",
|
||||
"@sveltejs/adapter-static": "latest",
|
||||
"@sveltejs/kit": "latest",
|
||||
"@sveltejs/adapter-static": "^4.0.1",
|
||||
"@sveltejs/kit": "^3.1.1",
|
||||
"@sveltejs/vite-plugin-svelte": "latest",
|
||||
"@tailwindcss/vite": "latest",
|
||||
"eslint": "latest",
|
||||
@@ -23,14 +24,15 @@
|
||||
"eslint-plugin-svelte": "latest",
|
||||
"prettier": "latest",
|
||||
"prettier-plugin-svelte": "latest",
|
||||
"svelte": "latest",
|
||||
"svelte": "^5.57.3",
|
||||
"svelte-check": "latest",
|
||||
"tailwindcss": "latest",
|
||||
"tw-animate-css": "latest",
|
||||
"vite": "latest"
|
||||
"vite": "^8.3.3"
|
||||
},
|
||||
"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",
|
||||
"@tanstack/svelte-query": "latest",
|
||||
"bits-ui": "latest",
|
||||
|
||||
+59
-28
@@ -8,51 +8,76 @@
|
||||
*/
|
||||
:root,
|
||||
[data-theme='dark'] {
|
||||
--color-bg: #0d1117;
|
||||
--color-surface: #161b22;
|
||||
--color-surface-hover: #1c2333;
|
||||
--color-border: #30363d;
|
||||
--color-fg: #e6edf3;
|
||||
--color-muted-fg: #8b949e;
|
||||
--color-bg: var(--sc-bg);
|
||||
--color-surface: var(--sc-surface);
|
||||
--color-surface-hover: var(--sc-surface-hover);
|
||||
--color-border: var(--sc-border);
|
||||
--color-fg: var(--sc-fg);
|
||||
--color-muted-fg: var(--sc-muted-fg);
|
||||
--color-primary: #3b82f6;
|
||||
--color-primary-fg: #04122e;
|
||||
--color-secondary: #60a5fa;
|
||||
--color-secondary-fg: #04122e;
|
||||
--color-secondary: var(--sc-secondary);
|
||||
--color-secondary-fg: var(--sc-secondary-fg);
|
||||
--color-accent: #3b82f6;
|
||||
--color-accent-fg: #04122e;
|
||||
--color-danger: #ef4444;
|
||||
--color-danger-fg: #ffffff;
|
||||
--color-success: #22c55e;
|
||||
--color-success-fg: #04210f;
|
||||
--color-warning: #f59e0b;
|
||||
--color-warning-fg: #2a1a00;
|
||||
--color-danger: var(--sc-danger);
|
||||
--color-danger-fg: var(--sc-danger-fg);
|
||||
--color-success: var(--sc-success);
|
||||
--color-success-fg: var(--sc-success-fg);
|
||||
--color-warning: var(--sc-warning);
|
||||
--color-warning-fg: var(--sc-warning-fg);
|
||||
--color-ring: #60a5fa;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* Bridge onto the shared component library's own --sc-* tokens so parts of the app built from
|
||||
@gabriel20xx/web-ui components outside AppShell's .collabtable-shell scope (AuthPage, the
|
||||
Settings/Profile dialogs) carry this project's brand color too, instead of falling back to the
|
||||
shared library's generic default blue. `html` raises specificity above shared-styles.css's
|
||||
plain `:root`/`[data-theme]` rules so this wins regardless of stylesheet import order. */
|
||||
html:root,
|
||||
html[data-theme='dark'] {
|
||||
--sc-primary: var(--color-primary);
|
||||
--sc-primary-hover: var(--color-secondary);
|
||||
--sc-primary-fg: var(--color-primary-fg);
|
||||
--sc-accent: var(--color-accent);
|
||||
--sc-accent-fg: var(--color-accent-fg);
|
||||
--sc-ring: var(--color-ring);
|
||||
}
|
||||
|
||||
[data-theme='light'] {
|
||||
--color-bg: #f6f8fa;
|
||||
--color-surface: #ffffff;
|
||||
--color-surface-hover: #eaeef2;
|
||||
--color-border: #d0d7de;
|
||||
--color-fg: #1f2328;
|
||||
--color-muted-fg: #59636e;
|
||||
--color-bg: var(--sc-bg);
|
||||
--color-surface: var(--sc-surface);
|
||||
--color-surface-hover: var(--sc-surface-hover);
|
||||
--color-border: var(--sc-border);
|
||||
--color-fg: var(--sc-fg);
|
||||
--color-muted-fg: var(--sc-muted-fg);
|
||||
--color-primary: #2563eb;
|
||||
--color-primary-fg: #ffffff;
|
||||
--color-secondary: #1d4ed8;
|
||||
--color-secondary-fg: #ffffff;
|
||||
--color-secondary: var(--sc-secondary);
|
||||
--color-secondary-fg: var(--sc-secondary-fg);
|
||||
--color-accent: #2563eb;
|
||||
--color-accent-fg: #ffffff;
|
||||
--color-danger: #dc2626;
|
||||
--color-danger-fg: #ffffff;
|
||||
--color-success: #16a34a;
|
||||
--color-success-fg: #ffffff;
|
||||
--color-warning: #b45309;
|
||||
--color-warning-fg: #ffffff;
|
||||
--color-danger: var(--sc-danger);
|
||||
--color-danger-fg: var(--sc-danger-fg);
|
||||
--color-success: var(--sc-success);
|
||||
--color-success-fg: var(--sc-success-fg);
|
||||
--color-warning: var(--sc-warning);
|
||||
--color-warning-fg: var(--sc-warning-fg);
|
||||
--color-ring: #2563eb;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* See the dark-theme bridge above for why this exists and why `html` is needed. */
|
||||
html[data-theme='light'] {
|
||||
--sc-primary: var(--color-primary);
|
||||
--sc-primary-hover: var(--color-secondary);
|
||||
--sc-primary-fg: var(--color-primary-fg);
|
||||
--sc-accent: var(--color-accent);
|
||||
--sc-accent-fg: var(--color-accent-fg);
|
||||
--sc-ring: var(--color-ring);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-bg: var(--color-bg);
|
||||
--color-surface: var(--color-surface);
|
||||
@@ -100,3 +125,9 @@ body {
|
||||
[data-wide-layout='true'] .sc-main {
|
||||
width: calc(100% - 2rem);
|
||||
}
|
||||
|
||||
/* The shared paginator adds separation when it follows content directly. Inside the overview
|
||||
card, the card padding provides that spacing and keeps the top and bottom insets balanced. */
|
||||
.pagination-card .sc-pagination {
|
||||
margin-top: 0;
|
||||
}
|
||||
+62
-8
@@ -37,42 +37,96 @@ export async function fetchHealth() {
|
||||
return { up: res.ok };
|
||||
}
|
||||
|
||||
// flattenAuthStatus adapts sharedauth.Service's Status/Signup/Login response
|
||||
// shape (a nested `user: {id, email, username, role, canManageUsers,
|
||||
// mfaEnabled}`, since CollabTable's AuthGuard migration onto
|
||||
// shared/backend/auth) back into the flat shape this frontend already
|
||||
// expects (AppShell.svelte reads status.username/.email/.setupRequired/
|
||||
// .authenticated directly) - keeping the rest of the frontend from needing to
|
||||
// change shape, the same translation GameStream/OmniLogger's frontends made
|
||||
// for the same migration.
|
||||
function flattenAuthStatus(payload) {
|
||||
return {
|
||||
setupRequired: payload?.setupRequired ?? false,
|
||||
authenticated: payload?.authenticated ?? false,
|
||||
authRequired: payload?.authRequired ?? true,
|
||||
id: payload?.user?.id,
|
||||
username: payload?.user?.username,
|
||||
email: payload?.user?.email,
|
||||
role: payload?.user?.role,
|
||||
canManageUsers: payload?.user?.canManageUsers,
|
||||
totpEnabled: payload?.user?.mfaEnabled,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchAuthStatus() {
|
||||
return getJson('/api/auth/status');
|
||||
return flattenAuthStatus(await getJson('/api/auth/status'));
|
||||
}
|
||||
|
||||
export async function setupAccount(username, email, password) {
|
||||
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
|
||||
const { user } = await request('/api/auth/setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, email, password }),
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function login(identifier, password, totpToken = '') {
|
||||
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpToken }) });
|
||||
const { user } = await request('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ identifier, password, totpToken }),
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function fetchTotpStatus() {
|
||||
return request('/api/auth/totp/status');
|
||||
}
|
||||
|
||||
// setupTotp/enableTotp/disableTotp proxy to sharedauth.Service's
|
||||
// TOTPInitiate/TOTPVerify/TOTPDisable, whose response bodies nest their
|
||||
// payload under a `data` key (`{"data": {...}}`) instead of the pre-migration
|
||||
// flat shape - unwrapped here so TotpSettings.svelte (@gabriel20xx/web-ui),
|
||||
// which reads setup.secret/setup.otpauthUrl directly, needs no changes.
|
||||
export async function setupTotp() {
|
||||
return request('/api/auth/totp/setup', { method: 'POST' });
|
||||
const { data } = await request('/api/auth/totp/setup', { method: 'POST' });
|
||||
return { secret: data.secret, otpauthUrl: data.otpauthUrl, enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function enableTotp(token) {
|
||||
return request('/api/auth/totp/enable', { method: 'POST', body: JSON.stringify({ token }) });
|
||||
const { data } = await request('/api/auth/totp/enable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
return { enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function disableTotp(token) {
|
||||
return request('/api/auth/totp/disable', { method: 'POST', body: JSON.stringify({ token }) });
|
||||
const { data } = await request('/api/auth/totp/disable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
return { enabled: data.enabled };
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
return request('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
||||
// updateCredentials proxies to sharedauth.Service's UpdateMe
|
||||
// (POST /api/auth/credentials), which requires a valid, non-empty email on
|
||||
// every call (it has no concept of "leave this field unchanged" for email the
|
||||
// way CollabTable's pre-migration handler did) - newUsername/newEmail must
|
||||
// always be the account's current values when the caller isn't actually
|
||||
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
||||
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
||||
// on hand. When changing the password, the shared ProfileDialog also supplies
|
||||
// currentPassword and (when enabled) totpToken for sharedauth's reauthentication
|
||||
// check. newPassword remains optional when it is not being changed.
|
||||
export async function updateCredentials({ newUsername, newEmail, newPassword, currentPassword, totpToken }) {
|
||||
return request('/api/auth/credentials', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ newUsername, newEmail, 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>
|
||||
import ListCard from './ListCard.svelte';
|
||||
|
||||
let { lists, fields, items, onSelect } = $props();
|
||||
let { lists, fieldsByList, itemsByList, onSelect } = $props();
|
||||
</script>
|
||||
|
||||
{#if lists.length === 0}
|
||||
@@ -10,9 +10,14 @@
|
||||
<div class="text-fg">No lists match your filters</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="grid grid-cols-1 gap-3 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)}
|
||||
<ListCard {list} {fields} {items} onClick={onSelect} />
|
||||
<ListCard
|
||||
{list}
|
||||
fields={fieldsByList.get(list.id) ?? []}
|
||||
items={itemsByList.get(list.id) ?? []}
|
||||
onClick={onSelect}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,7 +1,7 @@
|
||||
<script>
|
||||
import ListRow from './ListRow.svelte';
|
||||
|
||||
let { lists, fields, items, onSelect } = $props();
|
||||
let { lists, fieldsByList, itemsByList, onSelect } = $props();
|
||||
</script>
|
||||
|
||||
<table class="w-full text-left text-sm">
|
||||
@@ -15,7 +15,12 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
{#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}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
default: 'h-10 px-4 py-2',
|
||||
sm: 'h-10 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-6',
|
||||
icon: 'h-9 w-9',
|
||||
icon: 'h-10 w-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
@@ -2,14 +2,7 @@
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import { cn } from '$lib/utils/cn.js';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
sideOffset = 6,
|
||||
align = 'end',
|
||||
children,
|
||||
...restProps
|
||||
} = $props();
|
||||
let { ref = $bindable(null), class: className, sideOffset = 6, align = 'end', children, ...restProps } = $props();
|
||||
</script>
|
||||
|
||||
<DropdownMenu.Portal>
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
<script>
|
||||
import { ChevronFirst, ChevronLast, ChevronLeft, ChevronRight } from '@lucide/svelte';
|
||||
import Button from './button.svelte';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './select';
|
||||
import { SimpleTooltip } from './tooltip';
|
||||
|
||||
const PAGE_SIZE_OPTIONS = [12, 24, 48, 96];
|
||||
|
||||
let { page, pageSize = 24, pageLength = 0, totalLength = 0, onPaging } = $props();
|
||||
|
||||
const hasPreviousPage = $derived(page > 1);
|
||||
const firstItemIndex = $derived((page - 1) * pageSize + 1);
|
||||
const lastItemIndex = $derived((page - 1) * pageSize + pageLength);
|
||||
const hasNextPage = $derived(page * pageSize < totalLength);
|
||||
|
||||
// Passed as `Select`'s `items` prop so the trigger shows the right label immediately, even
|
||||
// before the dropdown has ever been opened - bits-ui can't rely on `Select.Item` having
|
||||
// mounted to the DOM yet to read its label back off of it.
|
||||
const pageSizeItems = PAGE_SIZE_OPTIONS.map((size) => ({ value: String(size), label: String(size) }));
|
||||
</script>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-4 px-2 py-3 text-sm">
|
||||
<Select
|
||||
type="single"
|
||||
value={String(pageSize)}
|
||||
items={pageSizeItems}
|
||||
onValueChange={(value) => onPaging({ page: 1, pageSize: Number(value) })}
|
||||
>
|
||||
<SelectTrigger class="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{#each pageSizeItems as item (item.value)}
|
||||
<SelectItem value={item.value} label={item.label}>{item.label}</SelectItem>
|
||||
{/each}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="text-muted-fg">
|
||||
{firstItemIndex.toLocaleString()}–{lastItemIndex.toLocaleString()} of {totalLength.toLocaleString()}
|
||||
</p>
|
||||
<div class="flex items-center gap-1">
|
||||
<SimpleTooltip label="First page">
|
||||
{#snippet children({ props })}
|
||||
<Button
|
||||
{...props}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasPreviousPage}
|
||||
onclick={() => onPaging({ page: 1, pageSize })}
|
||||
>
|
||||
<ChevronFirst class="size-4" />
|
||||
</Button>
|
||||
{/snippet}
|
||||
</SimpleTooltip>
|
||||
<SimpleTooltip label="Previous page">
|
||||
{#snippet children({ props })}
|
||||
<Button
|
||||
{...props}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasPreviousPage}
|
||||
onclick={() => onPaging({ page: page - 1, pageSize })}
|
||||
>
|
||||
<ChevronLeft class="size-4" />
|
||||
</Button>
|
||||
{/snippet}
|
||||
</SimpleTooltip>
|
||||
<SimpleTooltip label="Next page">
|
||||
{#snippet children({ props })}
|
||||
<Button
|
||||
{...props}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasNextPage}
|
||||
onclick={() => onPaging({ page: page + 1, pageSize })}
|
||||
>
|
||||
<ChevronRight class="size-4" />
|
||||
</Button>
|
||||
{/snippet}
|
||||
</SimpleTooltip>
|
||||
<SimpleTooltip label="Last page">
|
||||
{#snippet children({ props })}
|
||||
<Button
|
||||
{...props}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={!hasNextPage}
|
||||
onclick={() => onPaging({ page: Math.max(1, Math.ceil(totalLength / pageSize)), pageSize })}
|
||||
>
|
||||
<ChevronLast class="size-4" />
|
||||
</Button>
|
||||
{/snippet}
|
||||
</SimpleTooltip>
|
||||
</div>
|
||||
</div>
|
||||
@@ -9,7 +9,7 @@
|
||||
<Select.Trigger
|
||||
bind:ref
|
||||
class={cn(
|
||||
'flex h-9 items-center justify-between gap-2 rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'flex h-10 items-center justify-between gap-2 rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...restProps}
|
||||
|
||||
@@ -20,10 +20,18 @@
|
||||
let credentialsOpen = $state(false);
|
||||
|
||||
async function saveProfile(input) {
|
||||
// The backend's UpdateMe (POST /api/auth/credentials) requires a valid,
|
||||
// non-empty email on every call - it has no concept of "leave this field
|
||||
// unchanged" for email - so both username and email are always sent
|
||||
// as-is; ProfileDialog's form always pre-fills and requires both fields,
|
||||
// so they're never empty here. Only password is genuinely optional
|
||||
// (blank means unchanged).
|
||||
await auth.updateCredentials({
|
||||
newUsername: input.username.trim() || undefined,
|
||||
newEmail: input.email.trim() || undefined,
|
||||
newUsername: input.username.trim(),
|
||||
newEmail: input.email.trim(),
|
||||
newPassword: input.password || undefined,
|
||||
currentPassword: input.currentPassword,
|
||||
totpToken: input.totpToken,
|
||||
});
|
||||
}
|
||||
</script>
|
||||
@@ -68,36 +76,15 @@
|
||||
/>
|
||||
|
||||
<style>
|
||||
/* The shared component library (header, page title box, dialogs, buttons, ...) otherwise
|
||||
renders in its own generic default palette instead of this app's own branding - remap its
|
||||
--sc-* tokens onto this app's own --color-* palette so every shared component follows suit.
|
||||
--sc-secondary is a subtle tinted-surface color for low-emphasis buttons, a different role
|
||||
than this app's own saturated --color-secondary, so it's derived instead of mapped directly. */
|
||||
/* Most --sc-* bridging (primary/accent/ring, and the shared background/surface/border/status
|
||||
tokens) now lives globally in app.css so it also reaches shared components rendered outside
|
||||
this scope (AuthPage, the Settings/Profile dialogs). --sc-secondary is a subtle tinted-surface
|
||||
color for low-emphasis buttons here, a different role than this app's own saturated
|
||||
--color-secondary, so it stays local rather than overriding --color-secondary's shared
|
||||
meaning workspace-wide. */
|
||||
:global(.collabtable-shell) {
|
||||
--sc-bg: var(--color-bg);
|
||||
--sc-surface: var(--color-surface);
|
||||
--sc-surface-raised: var(--color-surface);
|
||||
--sc-surface-hover: var(--color-surface-hover);
|
||||
--sc-border: var(--color-border);
|
||||
--sc-border-strong: var(--color-border);
|
||||
--sc-fg: var(--color-fg);
|
||||
--sc-muted-fg: var(--color-muted-fg);
|
||||
--sc-subtle-fg: var(--color-muted-fg);
|
||||
--sc-primary: var(--color-primary);
|
||||
--sc-primary-hover: var(--color-secondary);
|
||||
--sc-primary-fg: var(--color-primary-fg);
|
||||
--sc-secondary: color-mix(in srgb, var(--color-primary) 12%, var(--color-surface));
|
||||
--sc-secondary-hover: color-mix(in srgb, var(--color-primary) 20%, var(--color-surface));
|
||||
--sc-secondary-fg: var(--color-fg);
|
||||
--sc-accent: var(--color-accent);
|
||||
--sc-accent-fg: var(--color-accent-fg);
|
||||
--sc-danger: var(--color-danger);
|
||||
--sc-danger-hover: color-mix(in srgb, var(--color-danger) 90%, black);
|
||||
--sc-danger-fg: var(--color-danger-fg);
|
||||
--sc-success: var(--color-success);
|
||||
--sc-success-fg: var(--color-success-fg);
|
||||
--sc-warning: var(--color-warning);
|
||||
--sc-warning-fg: var(--color-warning-fg);
|
||||
--sc-ring: var(--color-ring);
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script>
|
||||
import { Moon, Sun, SunMoon } from '@lucide/svelte';
|
||||
import Button from '$lib/components/ui/button.svelte';
|
||||
import { SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui';
|
||||
import { PrimaryColorPicker, SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select';
|
||||
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
|
||||
import { layoutState } from '$lib/layout.svelte.js';
|
||||
@@ -49,6 +49,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-5">
|
||||
<PrimaryColorPicker projectKey="CollabTable" />
|
||||
<label for="settings-language" class="mb-2 block text-sm font-medium">Language</label>
|
||||
<Select type="single" value={currentLanguage()} items={languageItems} onValueChange={(value) => setLanguage(value)}>
|
||||
<SelectTrigger id="settings-language" class="w-full">
|
||||
@@ -67,7 +68,6 @@
|
||||
type="checkbox"
|
||||
checked={layoutState.wide}
|
||||
onchange={(event) => layoutState.setWide(event.currentTarget.checked)}
|
||||
class="size-4 rounded border-border accent-primary"
|
||||
/>
|
||||
</label>
|
||||
<div class="sc-form-actions">
|
||||
|
||||
@@ -6,8 +6,20 @@ export function listItemsFor(items, listId) {
|
||||
return items.filter((i) => i.listId === listId && !i.isDeleted);
|
||||
}
|
||||
|
||||
export function itemValuesFor(values, itemId) {
|
||||
return values.filter((v) => v.itemId === itemId);
|
||||
// groupByKey indexes rows by keyOf in one pass. Build it once per data change in a
|
||||
// $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) {
|
||||
|
||||
@@ -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 = [
|
||||
{ id: 'ar', label: 'العربية' },
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import { browser } from '$app/environment';
|
||||
import { browser } from '$app/env';
|
||||
|
||||
const STORAGE_KEY = 'collabtable-wide-layout';
|
||||
|
||||
function loadInitialWide() {
|
||||
if (!browser) return false;
|
||||
return localStorage.getItem(STORAGE_KEY) === 'true';
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEY) === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function applyWide(value) {
|
||||
if (value) {
|
||||
document.documentElement.setAttribute('data-wide-layout', 'true');
|
||||
} else {
|
||||
document.documentElement.removeAttribute('data-wide-layout');
|
||||
}
|
||||
}
|
||||
|
||||
let wide = $state(loadInitialWide());
|
||||
@@ -15,17 +27,18 @@ export const layoutState = {
|
||||
},
|
||||
setWide(next) {
|
||||
wide = next;
|
||||
if (browser) localStorage.setItem(STORAGE_KEY, String(next));
|
||||
if (!browser) return;
|
||||
|
||||
applyWide(next);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, String(next));
|
||||
} catch {
|
||||
// Ignore storage failures; the current page can still use the selected layout width.
|
||||
}
|
||||
},
|
||||
toggle() {
|
||||
layoutState.setWide(!wide);
|
||||
},
|
||||
};
|
||||
|
||||
if (browser) {
|
||||
$effect.root(() => {
|
||||
$effect(() => {
|
||||
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';
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
import { resolve } from '$app/paths';
|
||||
import { ArrowDown, ArrowUp, LayoutGrid, List, Search, X } from '@lucide/svelte';
|
||||
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 { createDashboardViewMode } from '$lib/preferences/viewMode.svelte.js';
|
||||
import Button from '$lib/components/ui/button.svelte';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select';
|
||||
import Paginator from '$lib/components/ui/paginator.svelte';
|
||||
import { Pagination } from '@gabriel20xx/web-ui';
|
||||
import ListsGrid from '$lib/components/lists/ListsGrid.svelte';
|
||||
import ListsTable from '$lib/components/lists/ListsTable.svelte';
|
||||
|
||||
@@ -42,6 +43,10 @@
|
||||
let searched = $derived(filterListsBySearch(overview.lists, searchState.query));
|
||||
let sorted = $derived(sortLists(searched, sortField, sortDir));
|
||||
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(() => {
|
||||
void searchState.query;
|
||||
@@ -55,7 +60,7 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex-1 space-y-4 py-4">
|
||||
<div class="flex-1 space-y-4 pb-4">
|
||||
<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<div class="rounded-lg border border-border bg-surface p-3">
|
||||
<div class="text-xs text-muted-fg">Lists</div>
|
||||
@@ -92,7 +97,7 @@
|
||||
bind:value={searchState.query}
|
||||
placeholder="Search lists…"
|
||||
autocapitalize="none"
|
||||
class="h-9 w-full rounded-md border border-border bg-bg pl-8 pr-8 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
class="h-10 w-full rounded-md border border-border bg-bg pl-8 pr-8 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
{#if searchState.query}
|
||||
<button
|
||||
@@ -148,14 +153,14 @@
|
||||
|
||||
<div class="overflow-x-auto rounded-lg border border-border bg-bg p-3">
|
||||
{#if viewMode.mode === 'list'}
|
||||
<ListsTable lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
|
||||
<ListsTable lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
|
||||
{:else}
|
||||
<ListsGrid lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
|
||||
<ListsGrid lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<section class="rounded-lg border border-border bg-surface">
|
||||
<Paginator
|
||||
<section class="pagination-card rounded-lg border border-border bg-surface p-3">
|
||||
<Pagination
|
||||
{page}
|
||||
{pageSize}
|
||||
pageLength={pageItems.length}
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
import { resolve } from '$app/paths';
|
||||
import { ArrowLeft, LoaderCircle } from '@lucide/svelte';
|
||||
import Button from '$lib/components/ui/button.svelte';
|
||||
import Paginator from '$lib/components/ui/paginator.svelte';
|
||||
import { Pagination } from '@gabriel20xx/web-ui';
|
||||
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();
|
||||
|
||||
@@ -22,13 +22,14 @@
|
||||
const list = $derived(overview.lists.find((l) => l.id === data.id));
|
||||
const listFields = $derived(listFieldsFor(overview.fields, data.id));
|
||||
const listItems = $derived(listItemsFor(overview.items, data.id));
|
||||
const valuesByItem = $derived(groupByKey(overview.values, (v) => v.itemId));
|
||||
|
||||
let page = $state(1);
|
||||
let pageSize = $state(24);
|
||||
const pageItems = $derived(listItems.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize));
|
||||
</script>
|
||||
|
||||
<div class="space-y-4 py-4">
|
||||
<div class="space-y-4 pb-4">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<Button type="button" variant="secondary" size="sm" class="shrink-0" onclick={goBack}>
|
||||
<ArrowLeft class="size-4" />
|
||||
@@ -91,7 +92,7 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
{#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">
|
||||
<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)}
|
||||
@@ -103,16 +104,18 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Paginator
|
||||
{page}
|
||||
{pageSize}
|
||||
pageLength={pageItems.length}
|
||||
totalLength={listItems.length}
|
||||
onPaging={(e) => {
|
||||
page = e.page;
|
||||
pageSize = e.pageSize;
|
||||
}}
|
||||
/>
|
||||
<div class="mt-4">
|
||||
<Pagination
|
||||
{page}
|
||||
{pageSize}
|
||||
pageLength={pageItems.length}
|
||||
totalLength={listItems.length}
|
||||
onPaging={(e) => {
|
||||
page = e.page;
|
||||
pageSize = e.pageSize;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/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 { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import adapter from '@sveltejs/adapter-static';
|
||||
|
||||
// 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.
|
||||
@@ -29,7 +30,21 @@ const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) =
|
||||
});
|
||||
|
||||
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: {
|
||||
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||
},
|
||||
@@ -38,6 +53,7 @@ export default defineConfig({
|
||||
proxy: {
|
||||
'/web': 'http://localhost:8080',
|
||||
'/health': 'http://localhost:8080',
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gabriel20xx/node-backend": patch
|
||||
---
|
||||
|
||||
`AuthClient` accepts a `projectKey` option, sent as `X-Project-Key` on every request, so AuthGuard can enforce per-user project-access restriction for Node consumers the same way the Go and Python clients already do.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gabriel20xx/node-backend": minor
|
||||
---
|
||||
|
||||
Add a `coreconfig` module (`Info`/`Store`), the Node equivalent of `shared/backend/coreconfig` (Go) and `shared_backend.coreconfig` (Python): lets a service receive AuthGuard's/CarrierNode's current URL(s) pushed live from ProjectConfigurator instead of hardcoding them in its own env vars. `AuthClient` also gains `setBaseUrl(url)`, mirroring the Go/Python/Java clients, so a service can construct it once with an empty/unknown base URL and retarget it live once a URL is pushed, rather than needing the URL to be known at construction time.
|
||||
@@ -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.
|
||||
@@ -26,6 +26,17 @@ jobs:
|
||||
go-version-file: backend/go.mod
|
||||
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
|
||||
working-directory: backend
|
||||
run: go test ./...
|
||||
|
||||
@@ -29,6 +29,11 @@ jobs:
|
||||
npm ci
|
||||
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
|
||||
env:
|
||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||
|
||||
@@ -23,6 +23,13 @@ jobs:
|
||||
with:
|
||||
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
|
||||
env:
|
||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||
|
||||
Regular → Executable
+6
@@ -1,6 +1,12 @@
|
||||
#!/bin/sh
|
||||
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)"
|
||||
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
||||
|
||||
|
||||
Vendored
+6
@@ -43,8 +43,14 @@ jobs:
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install dependencies
|
||||
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
|
||||
run: npm run lint
|
||||
- name: Check Prettier formatting
|
||||
run: npm run format:check
|
||||
|
||||
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:
|
||||
run:
|
||||
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:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -62,8 +82,16 @@ jobs:
|
||||
with:
|
||||
go-version-file: backend/go.mod
|
||||
cache: true
|
||||
# -p 1 runs one package at a time, because the database tests share one scratch database.
|
||||
- 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:
|
||||
name: Test (Python)
|
||||
@@ -78,6 +106,27 @@ jobs:
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install package
|
||||
run: python -m pip install --upgrade pip -e packages/python-backend
|
||||
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi,test]"
|
||||
- name: Run Python tests
|
||||
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$''',
|
||||
]
|
||||
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user