mirror of
https://github.com/fluxerapp/fluxer
synced 2026-10-09 20:22:11 +09:00
Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bbfe809bef | ||
|
|
e0843ac4f5 | ||
|
|
43741cdad8 | ||
|
|
b8e3807262 | ||
|
|
3304f01a84 | ||
|
|
2ba463235b | ||
|
|
15136fed59 | ||
|
|
6013581dd9 | ||
|
|
7a91f128e9 | ||
|
|
963ffc5550 | ||
|
|
a90991612c | ||
|
|
50ad23b760 | ||
|
|
425dab983b | ||
|
|
a0825e77c4 | ||
|
|
88038a1d5b | ||
|
|
c2c0fdb445 | ||
|
|
dcd5f09d6a | ||
|
|
590b1f36fd | ||
|
|
168ac727f1 | ||
|
|
deb86dd92e | ||
|
|
7ccec4d3b8 | ||
|
|
2f38bcdf26 | ||
|
|
f2785941aa | ||
|
|
ea9f83a443 | ||
|
|
bd6ca7290e | ||
|
|
b85e975fb5 | ||
|
|
b6e504f68c | ||
|
|
5fde6eb484 | ||
|
|
b16989d567 | ||
|
|
c9754ac11a | ||
|
|
f34e4a5115 | ||
|
|
44b3615298 | ||
|
|
211e98307d | ||
|
|
18c303abf6 | ||
|
|
7021a58090 | ||
|
|
320725a587 | ||
|
|
8450edc072 | ||
|
|
a1e2bf2c8d | ||
|
|
82b2f4ec5e | ||
|
|
c92e5d03a7 | ||
|
|
91340c5c84 | ||
|
|
045dd5d027 | ||
|
|
a21b9c4659 | ||
|
|
4b1b869802 | ||
|
|
1ab7e7dfcc | ||
|
|
31c53d2dff | ||
|
|
412a1ae79d |
@@ -32,6 +32,7 @@
|
||||
/fluxer_docs/.astro/
|
||||
/fluxer_app/.devserver-cache.json
|
||||
/fluxer_app/pkgs/libfluxcore/
|
||||
/fluxer_app/pkgs/libfluxwebp/
|
||||
/fluxer_app/src/features/i18n/locales/*/messages.mjs
|
||||
/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
/fluxer_app/src/features/theme/styles/generated/
|
||||
|
||||
@@ -28,6 +28,9 @@ f:media_proxy:
|
||||
f:messages:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: fluxer_messages/**/*
|
||||
f:push:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: fluxer_push/**/*
|
||||
f:snowflakes:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: fluxer_snowflakes/**/*
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
name: build push
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build-version:
|
||||
description: "Explicit Fluxer CalVer build version (YYYY.MDD.MICRO, UTC HHMMSS without leading zeroes) to use instead of automatic UTC clock allocation"
|
||||
type: string
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
approve:
|
||||
name: approve build release
|
||||
permissions: {}
|
||||
runs-on: ubuntu-24.04
|
||||
environment: builds
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: approved
|
||||
run: echo "Build release approved."
|
||||
|
||||
image:
|
||||
needs: approve
|
||||
uses: ./.github/workflows/_build-image.yaml
|
||||
secrets: inherit
|
||||
with:
|
||||
image: fluxer-push
|
||||
dockerfile: fluxer_push/Dockerfile
|
||||
build-version: ${{ inputs['build-version'] }}
|
||||
@@ -123,12 +123,16 @@ jobs:
|
||||
with:
|
||||
path: |
|
||||
fluxer_app/pkgs/libfluxcore
|
||||
fluxer_app/pkgs/libfluxwebp
|
||||
fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
key: >-
|
||||
app-wasm-${{ runner.os }}-1.98.1-${{ hashFiles('Cargo.lock', 'tools/ci/src/app_wasm.rs',
|
||||
'tools/ci/templates/libfluxcore_wrapper.js', 'tools/ci/templates/libfluxcore_wrapper.d.ts',
|
||||
'fluxer_app/rust/libfluxcore/Cargo.toml', 'fluxer_app/rust/libfluxcore/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxcore/.cargo/config.toml', 'fluxer_app/rust/libfluxcore/src/**',
|
||||
'fluxer_app/rust/libfluxwebp/Cargo.toml', 'fluxer_app/rust/libfluxwebp/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxwebp/src/**', 'fluxer_app/rust/libfluxwebp/shim/**',
|
||||
'fluxer_app/rust/libfluxwebp/simd/**',
|
||||
'packages/markdown_parser/rust/Cargo.toml', 'packages/markdown_parser/rust/.cargo/config.toml',
|
||||
'packages/markdown_parser/rust/src/**') }}
|
||||
|
||||
@@ -142,12 +146,16 @@ jobs:
|
||||
with:
|
||||
path: |
|
||||
fluxer_app/pkgs/libfluxcore
|
||||
fluxer_app/pkgs/libfluxwebp
|
||||
fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
key: >-
|
||||
app-wasm-${{ runner.os }}-1.98.1-${{ hashFiles('Cargo.lock', 'tools/ci/src/app_wasm.rs',
|
||||
'tools/ci/templates/libfluxcore_wrapper.js', 'tools/ci/templates/libfluxcore_wrapper.d.ts',
|
||||
'fluxer_app/rust/libfluxcore/Cargo.toml', 'fluxer_app/rust/libfluxcore/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxcore/.cargo/config.toml', 'fluxer_app/rust/libfluxcore/src/**',
|
||||
'fluxer_app/rust/libfluxwebp/Cargo.toml', 'fluxer_app/rust/libfluxwebp/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxwebp/src/**', 'fluxer_app/rust/libfluxwebp/shim/**',
|
||||
'fluxer_app/rust/libfluxwebp/simd/**',
|
||||
'packages/markdown_parser/rust/Cargo.toml', 'packages/markdown_parser/rust/.cargo/config.toml',
|
||||
'packages/markdown_parser/rust/src/**') }}
|
||||
|
||||
@@ -190,6 +198,9 @@ jobs:
|
||||
- name: Check Rust dependencies
|
||||
run: cargo deny --locked check -D warnings
|
||||
|
||||
- name: Check libfluxwebp dependencies
|
||||
run: cargo deny --manifest-path fluxer_app/rust/libfluxwebp/Cargo.toml --config deny.toml --locked check licenses bans sources
|
||||
|
||||
- name: Check desktop native dependencies
|
||||
run: tools/ci/check-desktop-native-workspaces.sh dependencies
|
||||
|
||||
@@ -242,6 +253,9 @@ jobs:
|
||||
- name: Check formatting
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: Check formatting (libfluxwebp)
|
||||
run: cargo fmt --manifest-path fluxer_app/rust/libfluxwebp/Cargo.toml -- --check
|
||||
|
||||
- name: Check formatting (desktop native workspaces)
|
||||
run: tools/ci/check-desktop-native-workspaces.sh fmt
|
||||
|
||||
@@ -398,12 +412,16 @@ jobs:
|
||||
with:
|
||||
path: |
|
||||
fluxer_app/pkgs/libfluxcore
|
||||
fluxer_app/pkgs/libfluxwebp
|
||||
fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
key: >-
|
||||
app-wasm-${{ runner.os }}-1.98.1-${{ hashFiles('Cargo.lock', 'tools/ci/src/app_wasm.rs',
|
||||
'tools/ci/templates/libfluxcore_wrapper.js', 'tools/ci/templates/libfluxcore_wrapper.d.ts',
|
||||
'fluxer_app/rust/libfluxcore/Cargo.toml', 'fluxer_app/rust/libfluxcore/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxcore/.cargo/config.toml', 'fluxer_app/rust/libfluxcore/src/**',
|
||||
'fluxer_app/rust/libfluxwebp/Cargo.toml', 'fluxer_app/rust/libfluxwebp/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxwebp/src/**', 'fluxer_app/rust/libfluxwebp/shim/**',
|
||||
'fluxer_app/rust/libfluxwebp/simd/**',
|
||||
'packages/markdown_parser/rust/Cargo.toml', 'packages/markdown_parser/rust/.cargo/config.toml',
|
||||
'packages/markdown_parser/rust/src/**') }}
|
||||
|
||||
@@ -417,12 +435,16 @@ jobs:
|
||||
with:
|
||||
path: |
|
||||
fluxer_app/pkgs/libfluxcore
|
||||
fluxer_app/pkgs/libfluxwebp
|
||||
fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
key: >-
|
||||
app-wasm-${{ runner.os }}-1.98.1-${{ hashFiles('Cargo.lock', 'tools/ci/src/app_wasm.rs',
|
||||
'tools/ci/templates/libfluxcore_wrapper.js', 'tools/ci/templates/libfluxcore_wrapper.d.ts',
|
||||
'fluxer_app/rust/libfluxcore/Cargo.toml', 'fluxer_app/rust/libfluxcore/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxcore/.cargo/config.toml', 'fluxer_app/rust/libfluxcore/src/**',
|
||||
'fluxer_app/rust/libfluxwebp/Cargo.toml', 'fluxer_app/rust/libfluxwebp/Cargo.lock',
|
||||
'fluxer_app/rust/libfluxwebp/src/**', 'fluxer_app/rust/libfluxwebp/shim/**',
|
||||
'fluxer_app/rust/libfluxwebp/simd/**',
|
||||
'packages/markdown_parser/rust/Cargo.toml', 'packages/markdown_parser/rust/.cargo/config.toml',
|
||||
'packages/markdown_parser/rust/src/**') }}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
/fluxer_app/.devserver-cache.json
|
||||
/fluxer_app/pkgs/libfluxcore/
|
||||
/fluxer_app/pkgs/libfluxwebp/
|
||||
/fluxer_app/src/features/i18n/locales/*/messages.mjs
|
||||
/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasmBytes.ts
|
||||
/fluxer_app/src/features/theme/styles/generated/
|
||||
|
||||
Generated
+37
@@ -1607,6 +1607,7 @@ dependencies = [
|
||||
"ff",
|
||||
"generic-array",
|
||||
"group",
|
||||
"hkdf",
|
||||
"pem-rfc7468",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
@@ -1881,6 +1882,32 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluxer-push"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"base64 0.23.1",
|
||||
"clap",
|
||||
"fluxer-svc",
|
||||
"futures",
|
||||
"hmac 0.13.0",
|
||||
"p256",
|
||||
"percent-encoding",
|
||||
"rand 0.10.2",
|
||||
"reqwest",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluxer-snowflakes"
|
||||
version = "0.1.0"
|
||||
@@ -2308,6 +2335,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
|
||||
dependencies = [
|
||||
"hmac 0.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
@@ -3893,6 +3929,7 @@ dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http 1.5.0",
|
||||
"http-body 1.1.0",
|
||||
"http-body-util",
|
||||
|
||||
@@ -7,6 +7,7 @@ members = [
|
||||
"fluxer_gifs",
|
||||
"fluxer_svc",
|
||||
"fluxer_messages",
|
||||
"fluxer_push",
|
||||
"fluxer_snowflakes",
|
||||
"tools/ci",
|
||||
"tools/dev",
|
||||
|
||||
@@ -16,6 +16,11 @@
|
||||
<img src="https://img.shields.io/badge/License-AGPLv3-purple" alt="AGPLv3 License" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://flathub.org/apps/app.fluxer.Fluxer">
|
||||
<img src="https://dl.flathub.org/assets/badges/flathub-badge-en.svg" alt="Get it on Flathub" height="60" /></a>
|
||||
</p>
|
||||
|
||||
# Fluxer
|
||||
|
||||
Fluxer is a free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
|
||||
@@ -28,7 +33,7 @@ Fluxer is a free and open source instant messaging and VoIP chat app built for f
|
||||
|
||||
| Windows | macOS | Linux | Android | iOS |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [Installer (x64)][win-setup-x64] | [Disk image][mac-dmg] | [Flatpak][flatpak-ref] | [APK][android-apk] | [TestFlight][ios-testflight] |
|
||||
| [Installer (x64)][win-setup-x64] | [Disk image][mac-dmg] | [Flathub][flathub] | [APK][android-apk] | [TestFlight][ios-testflight] |
|
||||
| [Installer (ARM64)][win-setup-arm64] | | [deb (x64)][linux-deb-x64] | [Obtainium][obtainium] | |
|
||||
| [Portable (x64)][win-portable-x64] | | [deb (ARM64)][linux-deb-arm64] | | |
|
||||
| [Portable (ARM64)][win-portable-arm64] | | [rpm (x64)][linux-rpm-x64] | | |
|
||||
@@ -38,17 +43,23 @@ Fluxer is a free and open source instant messaging and VoIP chat app built for f
|
||||
| | | [tar.gz (x64)][linux-targz-x64] | | |
|
||||
| | | [tar.gz (ARM64)][linux-targz-arm64] | | |
|
||||
|
||||
The macOS disk image is universal and runs on both Apple silicon and Intel. Windows and Linux need the build that matches your processor.
|
||||
The macOS disk image runs on both Apple silicon and Intel. Windows and Linux need the build matching your processor.
|
||||
|
||||
On Linux, prefer a package repository over a file. Fluxer then updates with the rest of your system.
|
||||
On Linux, prefer a repository over a single file so Fluxer updates with the rest of your system.
|
||||
|
||||
## Linux package repositories
|
||||
|
||||
All four repositories serve stable and canary. The package is `fluxer` for stable and `fluxer-canary` for canary.
|
||||
The package is `fluxer` for stable and `fluxer-canary` for canary. apt and dnf subscribe to one channel per entry file. pacman and Flatpak serve both from one repository.
|
||||
|
||||
### Flatpak
|
||||
|
||||
Opening [this reference file][flatpak-ref] hands the install to your desktop software manager. Some desktops also accept `flatpak+https://pkgs.fluxer.com/flatpak/fluxer.flatpakref` pasted into the address bar.
|
||||
Stable is on [Flathub][flathub], the easiest route on most desktops:
|
||||
|
||||
```sh
|
||||
flatpak install flathub app.fluxer.Fluxer
|
||||
```
|
||||
|
||||
Flathub has stable only. To use Fluxer's own repository, open [the stable][flatpak-ref] or [the canary][flatpak-canary-ref] reference file and your software manager takes over. Some desktops also accept `flatpak+https://pkgs.fluxer.com/flatpak/fluxer.flatpakref` in the address bar.
|
||||
|
||||
From a terminal:
|
||||
|
||||
@@ -65,6 +76,15 @@ sudo curl -fsSL -o /etc/apt/sources.list.d/fluxer.sources https://pkgs.fluxer.co
|
||||
sudo apt update && sudo apt install fluxer
|
||||
```
|
||||
|
||||
For canary, use the canary entry file and package.
|
||||
|
||||
```sh
|
||||
sudo curl -fsSL -o /etc/apt/sources.list.d/fluxer-canary.sources https://pkgs.fluxer.com/deb/fluxer-canary.sources
|
||||
sudo apt update && sudo apt install fluxer-canary
|
||||
```
|
||||
|
||||
A `.deb` installed from a download only updates once its channel's entry is added.
|
||||
|
||||
### Fedora and RHEL
|
||||
|
||||
```sh
|
||||
@@ -72,11 +92,18 @@ sudo curl -fsSL -o /etc/yum.repos.d/fluxer.repo https://pkgs.fluxer.com/rpm/flux
|
||||
sudo dnf install fluxer
|
||||
```
|
||||
|
||||
RHEL, Rocky, Alma and CentOS Stream need `sudo dnf install epel-release` first, because the base repositories do not ship `libXScrnSaver`. Fedora does not need this.
|
||||
For canary, use the canary entry file and package.
|
||||
|
||||
```sh
|
||||
sudo curl -fsSL -o /etc/yum.repos.d/fluxer-canary.repo https://pkgs.fluxer.com/rpm/fluxer-canary.repo
|
||||
sudo dnf install fluxer-canary
|
||||
```
|
||||
|
||||
RHEL, Rocky, Alma and CentOS Stream need `sudo dnf install epel-release` first, because their base repositories lack `libXScrnSaver`. Fedora does not.
|
||||
|
||||
### Arch Linux
|
||||
|
||||
The repository is signed, so pacman needs the key in its own keyring once:
|
||||
The repository is signed, so pacman needs the key once:
|
||||
|
||||
```sh
|
||||
sudo pacman-key --init
|
||||
@@ -85,7 +112,7 @@ sudo pacman-key --add /tmp/fluxer-archive-keyring.asc
|
||||
sudo pacman-key --lsign-key 09D01339EE128925F75E675C855C5BDE34D205D2
|
||||
```
|
||||
|
||||
`--lsign-key` is the step that makes pacman trust the key. Then add the repository:
|
||||
`--lsign-key` is what makes pacman trust it. Then add the repository:
|
||||
|
||||
```sh
|
||||
sudo tee -a /etc/pacman.conf >/dev/null <<'REPO'
|
||||
@@ -97,13 +124,13 @@ REPO
|
||||
sudo pacman -Syu fluxer
|
||||
```
|
||||
|
||||
Write `$repo` and `$arch` literally. Both are pacman variables, not shell ones, which is why the heredoc above is quoted.
|
||||
Write `$repo` and `$arch` literally. Both are pacman variables, not shell ones, hence the quoted heredoc.
|
||||
|
||||
Full setup notes, including the canary channel, live in the [Linux repositories documentation][docs-linux].
|
||||
Full setup notes, including canary, are in the [Linux repositories documentation][docs-linux].
|
||||
|
||||
## Other ways to run it
|
||||
|
||||
- [Open Fluxer in a browser](https://web.fluxer.app) with no install at all.
|
||||
- [Open Fluxer in a browser](https://web.fluxer.app), no install needed.
|
||||
- [Host your own instance][docs-selfhost] from this repository.
|
||||
|
||||
## Documentation
|
||||
@@ -117,9 +144,9 @@ Full setup notes, including the canary channel, live in the [Linux repositories
|
||||
The source is licensed under the [AGPL-3.0-or-later](./LICENSE) license.
|
||||
|
||||
Fluxer branding, icons, default avatars, badge artwork, screenshots and marketing
|
||||
imagery are copyright Fluxer and all rights reserved, as set out in
|
||||
[fluxer_static/LICENSE](./fluxer_static/LICENSE). Third-party material keeps its
|
||||
own terms, listed in
|
||||
imagery are copyright Fluxer, all rights reserved, as set out in
|
||||
[fluxer_static/LICENSE](./fluxer_static/LICENSE). Third-party material keeps its own
|
||||
terms, listed in
|
||||
[fluxer_static/THIRD_PARTY_LICENSES.md](./fluxer_static/THIRD_PARTY_LICENSES.md).
|
||||
|
||||
Public availability of this repository does not grant trademark, brand, or
|
||||
@@ -139,6 +166,8 @@ endorsement rights.
|
||||
[linux-targz-x64]: https://pkgs.fluxer.com/desktop/stable/linux/x64/latest/tar_gz
|
||||
[linux-targz-arm64]: https://pkgs.fluxer.com/desktop/stable/linux/arm64/latest/tar_gz
|
||||
[flatpak-ref]: https://pkgs.fluxer.com/flatpak/fluxer.flatpakref
|
||||
[flatpak-canary-ref]: https://pkgs.fluxer.com/flatpak/fluxer-canary.flatpakref
|
||||
[flathub]: https://flathub.org/apps/app.fluxer.Fluxer
|
||||
[android-apk]: https://github.com/fluxerapp/flutter_client/releases
|
||||
[obtainium]: https://obtainium.imranr.dev/
|
||||
[ios-testflight]: https://testflight.apple.com/join/PKZR6pK9
|
||||
|
||||
@@ -147,6 +147,12 @@ FLUXER_VAPID_PRIVATE_KEY=CHANGE_ME
|
||||
#FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS=https://chat.example.com
|
||||
#FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS=http://chat.example.com:19080
|
||||
|
||||
# Notification jobs the push container holds at once, 1 to 1000000.
|
||||
#FLUXER_PUSH_SERVICE_QUEUE_CAPACITY=10000
|
||||
# Provider requests the push container sends at once, 1 to 65536.
|
||||
#FLUXER_PUSH_SERVICE_SEND_CONCURRENCY=256
|
||||
|
||||
|
||||
# Optional media policies, both off by default. See the operator docs.
|
||||
#
|
||||
# CORS limits which web origins may read media. A request with no Origin is
|
||||
@@ -245,6 +251,7 @@ FLUXER_DISCOVERY_ENABLED=true
|
||||
#FLUXER_GATEWAY_MEMORY_LIMIT=1gb
|
||||
#FLUXER_GATEWAY_MEMORY_RESERVATION=384mb
|
||||
#FLUXER_MEDIA_PROXY_MEMORY_LIMIT=512mb
|
||||
#FLUXER_PUSH_MEMORY_LIMIT=256mb
|
||||
#FLUXER_STATIC_PROXY_MEMORY_LIMIT=256mb
|
||||
#FLUXER_APP_PROXY_MEMORY_LIMIT=256mb
|
||||
#FLUXER_SNOWFLAKES_MEMORY_LIMIT=128mb
|
||||
|
||||
@@ -482,6 +482,30 @@ services:
|
||||
seaweedfs-init: {condition: service_completed_successfully}
|
||||
nats: {condition: service_healthy}
|
||||
|
||||
push:
|
||||
<<: *fluxer-service
|
||||
image: ${FLUXER_REGISTRY:-ghcr.io/${FLUXER_REGISTRY_OWNER:-fluxerapp}}/fluxer-push:${FLUXER_IMAGE_TAG:-v1}
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: ${FLUXER_PUSH_MEMORY_LIMIT:-256mb}
|
||||
environment:
|
||||
<<: *fluxer-env
|
||||
FLUXER_PUSH_SERVICE_HOST: 0.0.0.0
|
||||
FLUXER_PUSH_SERVICE_PORT: "8126"
|
||||
FLUXER_PUSH_SERVICE_QUEUE_CAPACITY: "${FLUXER_PUSH_SERVICE_QUEUE_CAPACITY:-}"
|
||||
FLUXER_PUSH_SERVICE_SEND_CONCURRENCY: "${FLUXER_PUSH_SERVICE_SEND_CONCURRENCY:-}"
|
||||
healthcheck:
|
||||
test: ["CMD", "/usr/local/bin/fluxer-push", "healthcheck"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
start_period: 60s
|
||||
start_interval: 1s
|
||||
depends_on:
|
||||
nats: {condition: service_healthy}
|
||||
api: {condition: service_healthy}
|
||||
|
||||
static-proxy:
|
||||
<<: *fluxer-service
|
||||
image: ${FLUXER_REGISTRY:-ghcr.io/${FLUXER_REGISTRY_OWNER:-fluxerapp}}/fluxer-static:${FLUXER_IMAGE_TAG:-v1}
|
||||
|
||||
@@ -10524,7 +10524,7 @@
|
||||
},
|
||||
"gateway_rollout": {"$ref": "#/components/schemas/GatewayRolloutConfigResponse"},
|
||||
"voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionConfigResponse"},
|
||||
"screen_share_delivery": {"$ref": "#/components/schemas/ScreenShareDeliveryConfigResponse"},
|
||||
"push_service_delivery": {"$ref": "#/components/schemas/PushServiceDeliveryConfigResponse"},
|
||||
"experiment_delivery": {"$ref": "#/components/schemas/ExperimentDeliveryConfigResponse"},
|
||||
"registration": {
|
||||
"type": "object",
|
||||
@@ -10952,7 +10952,7 @@
|
||||
"sso",
|
||||
"gateway_rollout",
|
||||
"voice_noise_suppression",
|
||||
"screen_share_delivery",
|
||||
"push_service_delivery",
|
||||
"experiment_delivery",
|
||||
"registration",
|
||||
"self_hosted",
|
||||
@@ -11087,9 +11087,9 @@
|
||||
"nullable": true,
|
||||
"allOf": [{"$ref": "#/components/schemas/VoiceNoiseSuppressionConfigUpdateRequest"}]
|
||||
},
|
||||
"screen_share_delivery": {
|
||||
"push_service_delivery": {
|
||||
"nullable": true,
|
||||
"allOf": [{"$ref": "#/components/schemas/ScreenShareDeliveryConfigUpdateRequest"}]
|
||||
"allOf": [{"$ref": "#/components/schemas/PushServiceDeliveryConfigUpdateRequest"}]
|
||||
},
|
||||
"experiment_delivery": {
|
||||
"nullable": true,
|
||||
@@ -15184,12 +15184,12 @@
|
||||
"poll_jitter_percent": {"type": "integer", "minimum": 0, "maximum": 50}
|
||||
}
|
||||
},
|
||||
"ScreenShareDeliveryConfigUpdateRequest": {
|
||||
"PushServiceDeliveryConfigUpdateRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {"type": "boolean"},
|
||||
"rollout_basis_points": {"type": "integer", "minimum": 0, "maximum": 10000},
|
||||
"rollout_salt": {"type": "string", "minLength": 1, "maxLength": 64},
|
||||
"rollout_salt": {"type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[\\x20-\\x7e]+$"},
|
||||
"included_user_ids": {
|
||||
"maxItems": 1000,
|
||||
"type": "array",
|
||||
@@ -15267,13 +15267,19 @@
|
||||
"required": ["poll_interval_seconds", "poll_jitter_percent"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ScreenShareDeliveryConfigResponse": {
|
||||
"PushServiceDeliveryConfigResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {"default": false, "type": "boolean"},
|
||||
"config_version": {"default": 0, "type": "integer", "minimum": 0, "maximum": 9007199254740991},
|
||||
"rollout_basis_points": {"default": 0, "type": "integer", "minimum": 0, "maximum": 10000},
|
||||
"rollout_salt": {"default": "screen-share-delivery-v1", "type": "string", "minLength": 1, "maxLength": 64},
|
||||
"rollout_salt": {
|
||||
"default": "push-service-delivery-v1",
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"pattern": "^[\\x20-\\x7e]+$"
|
||||
},
|
||||
"included_user_ids": {
|
||||
"default": [],
|
||||
"maxItems": 1000,
|
||||
|
||||
@@ -23,7 +23,7 @@ pub struct InstanceConfigResponse {
|
||||
#[serde(default)]
|
||||
pub voice_noise_suppression: VoiceNoiseSuppressionConfigResponse,
|
||||
#[serde(default)]
|
||||
pub screen_share_delivery: ScreenShareDeliveryConfigResponse,
|
||||
pub push_service_delivery: PushServiceDeliveryConfigResponse,
|
||||
#[serde(default)]
|
||||
pub experiment_delivery: ExperimentDeliveryConfigResponse,
|
||||
}
|
||||
@@ -449,7 +449,7 @@ impl VoiceE2eeScope {
|
||||
}
|
||||
|
||||
pub const EXPERIMENT_MAX_TARGETED_USERS: usize = 1_000;
|
||||
pub const SCREEN_SHARE_DELIVERY_DEFAULT_SALT: &str = "screen-share-delivery-v1";
|
||||
pub const PUSH_SERVICE_DELIVERY_DEFAULT_SALT: &str = "push-service-delivery-v1";
|
||||
pub const VOICE_NS_MAX_GUILD_OVERRIDES: usize = 200;
|
||||
|
||||
impl NoiseSuppressionBackend {
|
||||
@@ -542,7 +542,7 @@ pub struct VoiceNoiseSuppressionConfigUpdateRequest {
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct ScreenShareDeliveryConfigResponse {
|
||||
pub struct PushServiceDeliveryConfigResponse {
|
||||
pub enabled: bool,
|
||||
pub config_version: u64,
|
||||
pub rollout_basis_points: u32,
|
||||
@@ -551,13 +551,13 @@ pub struct ScreenShareDeliveryConfigResponse {
|
||||
pub excluded_user_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for ScreenShareDeliveryConfigResponse {
|
||||
impl Default for PushServiceDeliveryConfigResponse {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
config_version: 0,
|
||||
rollout_basis_points: 0,
|
||||
rollout_salt: SCREEN_SHARE_DELIVERY_DEFAULT_SALT.to_owned(),
|
||||
rollout_salt: PUSH_SERVICE_DELIVERY_DEFAULT_SALT.to_owned(),
|
||||
included_user_ids: Vec::new(),
|
||||
excluded_user_ids: Vec::new(),
|
||||
}
|
||||
@@ -565,7 +565,7 @@ impl Default for ScreenShareDeliveryConfigResponse {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
pub struct ScreenShareDeliveryConfigUpdateRequest {
|
||||
pub struct PushServiceDeliveryConfigUpdateRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -694,7 +694,7 @@ pub struct InstanceConfigUpdateRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub voice_noise_suppression: Option<VoiceNoiseSuppressionConfigUpdateRequest>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub screen_share_delivery: Option<ScreenShareDeliveryConfigUpdateRequest>,
|
||||
pub push_service_delivery: Option<PushServiceDeliveryConfigUpdateRequest>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub experiment_delivery: Option<ExperimentDeliveryConfigUpdateRequest>,
|
||||
}
|
||||
@@ -1033,30 +1033,18 @@ mod tests {
|
||||
.expect("admin schema");
|
||||
let noise = serde_json::from_value::<VoiceNoiseSuppressionConfigResponse>(json!({}))
|
||||
.expect("default noise config");
|
||||
let screen_share = serde_json::from_value::<ScreenShareDeliveryConfigResponse>(json!({}))
|
||||
.expect("default screen share config");
|
||||
let delivery = serde_json::from_value::<ExperimentDeliveryConfigResponse>(json!({}))
|
||||
.expect("default delivery config");
|
||||
let noise = serde_json::to_value(noise).expect("serializable noise config");
|
||||
let screen_share =
|
||||
serde_json::to_value(screen_share).expect("serializable screen share config");
|
||||
let delivery = serde_json::to_value(delivery).expect("serializable delivery config");
|
||||
let generated_noise: generated_types::VoiceNoiseSuppressionConfigResponse =
|
||||
serde_json::from_value(noise.clone()).expect("generated noise config contract");
|
||||
let generated_screen_share: generated_types::ScreenShareDeliveryConfigResponse =
|
||||
serde_json::from_value(screen_share.clone())
|
||||
.expect("generated screen share config contract");
|
||||
let generated_delivery: generated_types::ExperimentDeliveryConfigResponse =
|
||||
serde_json::from_value(delivery.clone()).expect("generated delivery config contract");
|
||||
assert_eq!(
|
||||
serde_json::to_value(generated_noise).expect("serializable generated noise config"),
|
||||
noise
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(generated_screen_share)
|
||||
.expect("serializable generated screen share config"),
|
||||
screen_share
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(generated_delivery)
|
||||
.expect("serializable generated delivery config"),
|
||||
@@ -1064,7 +1052,6 @@ mod tests {
|
||||
);
|
||||
for (name, value) in [
|
||||
("VoiceNoiseSuppressionConfigResponse", noise),
|
||||
("ScreenShareDeliveryConfigResponse", screen_share),
|
||||
("ExperimentDeliveryConfigResponse", delivery),
|
||||
] {
|
||||
for (field, value) in value.as_object().expect("config object") {
|
||||
@@ -1076,29 +1063,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_share_delivery_update_preserves_empty_lists_and_omitted_fields() {
|
||||
let update = ScreenShareDeliveryConfigUpdateRequest {
|
||||
included_user_ids: Some(Vec::new()),
|
||||
excluded_user_ids: Some(Vec::new()),
|
||||
..Default::default()
|
||||
};
|
||||
let value = serde_json::to_value(update).expect("serializable update");
|
||||
serde_json::from_value::<generated_types::ScreenShareDeliveryConfigUpdateRequest>(
|
||||
value.clone(),
|
||||
)
|
||||
.expect("generated update contract");
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({"included_user_ids": [], "excluded_user_ids": []})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(ScreenShareDeliveryConfigUpdateRequest::default())
|
||||
.expect("serializable update"),
|
||||
json!({})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_suppression_update_preserves_empty_lists_and_omitted_fields() {
|
||||
let update = VoiceNoiseSuppressionConfigUpdateRequest {
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn reports_list(
|
||||
return reports_error_page(
|
||||
config,
|
||||
&auth.0,
|
||||
"That page is out of range. The reports search returns at most the first 10000 reports, so narrow the filters and start again.",
|
||||
"That page is out of range. The reports search returns at most the first 10000 reports. Narrow the filters and start again.",
|
||||
);
|
||||
}
|
||||
let search_query = query.q.as_deref().and_then(clean_string);
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::{
|
||||
InstancePolicyUpdateRequest, InstanceRegistrationConfigUpdateRequest,
|
||||
InstanceServicesUpdateRequest, InstanceYoutubeIntegrationUpdateRequest,
|
||||
LimitConfigUpdateRequest, LimitRule, LimitRuleFilters, NoiseSuppressionBackend,
|
||||
PremiumMode, RegistrationMode, ScreenShareDeliveryConfigUpdateRequest,
|
||||
PremiumMode, PushServiceDeliveryConfigUpdateRequest, RegistrationMode,
|
||||
SsoConfigUpdateRequest, VOICE_NS_MAX_GUILD_OVERRIDES, VoiceE2eeScope,
|
||||
VoiceNoiseSuppressionConfigUpdateRequest, VoiceNoiseSuppressionGuildOverride,
|
||||
},
|
||||
@@ -207,7 +207,7 @@ pub async fn instance_config_post(
|
||||
Ok(update) => instance_config_result(client.update_instance_config(&update).await),
|
||||
Err(message) => FlashData::error(message),
|
||||
},
|
||||
"update_screen_share_delivery" => match build_screen_share_delivery_update(&form) {
|
||||
"update_push_service_delivery" => match build_push_service_delivery_update(&form) {
|
||||
Ok(update) => instance_config_result(client.update_instance_config(&update).await),
|
||||
Err(message) => FlashData::error(message),
|
||||
},
|
||||
@@ -496,6 +496,21 @@ fn parse_experiment_rollout_salt(
|
||||
Ok(Some(salt.to_owned()))
|
||||
}
|
||||
|
||||
fn parse_push_service_delivery_rollout_salt(
|
||||
form: &MultiValueForm,
|
||||
key: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let salt = parse_experiment_rollout_salt(form, key)?;
|
||||
if let Some(value) = salt.as_deref()
|
||||
&& !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_graphic() || byte == b' ')
|
||||
{
|
||||
return Err("Rollout salt must use printable ASCII".to_owned());
|
||||
}
|
||||
Ok(salt)
|
||||
}
|
||||
|
||||
fn is_experiment_snowflake(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= EXPERIMENT_MAX_SNOWFLAKE_LENGTH
|
||||
@@ -633,30 +648,30 @@ fn build_voice_noise_suppression_update(
|
||||
})
|
||||
}
|
||||
|
||||
fn build_screen_share_delivery_update(
|
||||
fn build_push_service_delivery_update(
|
||||
form: &MultiValueForm,
|
||||
) -> Result<InstanceConfigUpdateRequest, String> {
|
||||
Ok(InstanceConfigUpdateRequest {
|
||||
screen_share_delivery: Some(ScreenShareDeliveryConfigUpdateRequest {
|
||||
enabled: Some(form.bool_value("screen_share_delivery_enabled")),
|
||||
push_service_delivery: Some(PushServiceDeliveryConfigUpdateRequest {
|
||||
enabled: Some(form.bool_value("push_service_delivery_enabled")),
|
||||
rollout_basis_points: parse_form_number(
|
||||
form,
|
||||
"screen_share_delivery_rollout_basis_points",
|
||||
"push_service_delivery_rollout_basis_points",
|
||||
"Rollout basis points",
|
||||
0,
|
||||
EXPERIMENT_ROLLOUT_BASIS_POINTS_MAX,
|
||||
)?,
|
||||
rollout_salt: parse_experiment_rollout_salt(
|
||||
rollout_salt: parse_push_service_delivery_rollout_salt(
|
||||
form,
|
||||
"screen_share_delivery_rollout_salt",
|
||||
"push_service_delivery_rollout_salt",
|
||||
)?,
|
||||
included_user_ids: Some(parse_experiment_user_ids(
|
||||
form.first("screen_share_delivery_included_user_ids")
|
||||
form.first("push_service_delivery_included_user_ids")
|
||||
.unwrap_or_default(),
|
||||
"Included user IDs",
|
||||
)?),
|
||||
excluded_user_ids: Some(parse_experiment_user_ids(
|
||||
form.first("screen_share_delivery_excluded_user_ids")
|
||||
form.first("push_service_delivery_excluded_user_ids")
|
||||
.unwrap_or_default(),
|
||||
"Excluded user IDs",
|
||||
)?),
|
||||
@@ -1586,83 +1601,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_screen_share_delivery_update_reads_the_rollout_fields() {
|
||||
let form = MultiValueForm::parse(
|
||||
b"screen_share_delivery_enabled=true&screen_share_delivery_rollout_basis_points=%20250%20&screen_share_delivery_rollout_salt=%20screen-share-delivery-v2%20&screen_share_delivery_included_user_ids=1500000000000000001%0A1500000000000000002&screen_share_delivery_excluded_user_ids=1500000000000000003%2C%201500000000000000004",
|
||||
);
|
||||
let update = build_screen_share_delivery_update(&form)
|
||||
.expect("valid form")
|
||||
.screen_share_delivery
|
||||
.expect("screen share delivery update");
|
||||
assert_eq!(update.enabled, Some(true));
|
||||
assert_eq!(update.rollout_basis_points, Some(250));
|
||||
assert_eq!(
|
||||
update.rollout_salt,
|
||||
Some("screen-share-delivery-v2".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
update.included_user_ids,
|
||||
Some(vec![
|
||||
"1500000000000000001".to_owned(),
|
||||
"1500000000000000002".to_owned()
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
update.excluded_user_ids,
|
||||
Some(vec![
|
||||
"1500000000000000003".to_owned(),
|
||||
"1500000000000000004".to_owned()
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_screen_share_delivery_update_leaves_the_feature_inert_when_nothing_is_submitted() {
|
||||
let form = MultiValueForm::parse(b"_csrf=token");
|
||||
let request = build_screen_share_delivery_update(&form).expect("valid form");
|
||||
assert_eq!(
|
||||
serde_json::to_value(request).expect("serializable update"),
|
||||
serde_json::json!({"screen_share_delivery": {
|
||||
"enabled": false,
|
||||
"included_user_ids": [],
|
||||
"excluded_user_ids": [],
|
||||
}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_screen_share_delivery_update_rejects_invalid_rollout_fields() {
|
||||
for (form, message) in [
|
||||
(
|
||||
"screen_share_delivery_rollout_basis_points=10001",
|
||||
"Rollout basis points must be a whole number between 0 and 10000",
|
||||
),
|
||||
(
|
||||
"screen_share_delivery_rollout_basis_points=abc",
|
||||
"Rollout basis points must be a whole number between 0 and 10000",
|
||||
),
|
||||
(
|
||||
"screen_share_delivery_rollout_salt=%20%20",
|
||||
"Rollout salt must be between 1 and 64 characters",
|
||||
),
|
||||
(
|
||||
"screen_share_delivery_included_user_ids=123%2Cinvalid",
|
||||
"Included user IDs entry 2 must contain 1 to 20 decimal digits",
|
||||
),
|
||||
(
|
||||
"screen_share_delivery_excluded_user_ids=123%2Cinvalid",
|
||||
"Excluded user IDs entry 2 must contain 1 to 20 decimal digits",
|
||||
),
|
||||
] {
|
||||
let form = MultiValueForm::parse(form.as_bytes());
|
||||
assert_eq!(
|
||||
build_screen_share_delivery_update(&form).expect_err("invalid rollout field"),
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_experiment_delivery_update_leaves_both_fields_unchanged_when_absent() {
|
||||
let form = MultiValueForm::parse(b"_csrf=token");
|
||||
|
||||
@@ -5,10 +5,9 @@ use crate::{
|
||||
AppPublicConfigResponse, EXPERIMENT_MAX_TARGETED_USERS, ExperimentDeliveryConfigResponse,
|
||||
GatewayRolloutConfigResponse, InstanceConfigResponse, InstanceIntegrationsResponse,
|
||||
InstanceMediaResponse, InstancePolicyResponse, InstanceRegistrationResponse,
|
||||
LimitConfigResponse, NoiseSuppressionBackend, PendingRegistrationResponse,
|
||||
RegistrationUrlResponse, SCREEN_SHARE_DELIVERY_DEFAULT_SALT,
|
||||
ScreenShareDeliveryConfigResponse, SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES,
|
||||
VoiceNoiseSuppressionConfigResponse,
|
||||
LimitConfigResponse, NoiseSuppressionBackend, PUSH_SERVICE_DELIVERY_DEFAULT_SALT,
|
||||
PendingRegistrationResponse, PushServiceDeliveryConfigResponse, RegistrationUrlResponse,
|
||||
SsoConfigResponse, VOICE_NS_MAX_GUILD_OVERRIDES, VoiceNoiseSuppressionConfigResponse,
|
||||
},
|
||||
config::AdminConfig,
|
||||
middleware::auth::AuthContext,
|
||||
@@ -149,7 +148,7 @@ pub fn instance_config_page(
|
||||
html! {
|
||||
(gateway_rollout_section(base, csrf_token, &instance_config.gateway_rollout))
|
||||
(voice_noise_suppression_section(base, csrf_token, &instance_config.voice_noise_suppression))
|
||||
(screen_share_delivery_section(base, csrf_token, &instance_config.screen_share_delivery))
|
||||
(push_service_delivery_section(base, csrf_token, &instance_config.push_service_delivery))
|
||||
(experiment_delivery_section(base, csrf_token, &instance_config.experiment_delivery))
|
||||
@if let Some(limit_config) = limit_config {
|
||||
(limit_config_section(base, limit_config))
|
||||
@@ -1112,7 +1111,7 @@ fn voice_noise_suppression_section(
|
||||
p class="text-xs text-neutral-500" {
|
||||
"One snowflake per line, or comma separated. These users are targeted \
|
||||
regardless of the percentage above. IDs must contain 1 to 20 decimal \
|
||||
digits. Invalid entries prevent the save; blank entries and duplicate \
|
||||
digits. Invalid entries prevent the save. Blank entries and duplicate \
|
||||
IDs are ignored."
|
||||
}
|
||||
}
|
||||
@@ -1131,7 +1130,7 @@ fn voice_noise_suppression_section(
|
||||
))
|
||||
p class="text-xs text-neutral-500" {
|
||||
"Same format. Exclusion wins over both the always-on list and the \
|
||||
percentage, so this is the per-user kill switch."
|
||||
percentage. This is the per-user kill switch."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1178,62 +1177,60 @@ fn voice_noise_suppression_section(
|
||||
)
|
||||
}
|
||||
|
||||
fn screen_share_delivery_section(
|
||||
fn push_service_delivery_section(
|
||||
base: &str,
|
||||
csrf_token: &str,
|
||||
screen_share_delivery: &ScreenShareDeliveryConfigResponse,
|
||||
push_service_delivery: &PushServiceDeliveryConfigResponse,
|
||||
) -> Markup {
|
||||
let status = if screen_share_delivery.enabled {
|
||||
let status = if push_service_delivery.enabled {
|
||||
("Live", BadgeVariant::Success)
|
||||
} else {
|
||||
("Inert", BadgeVariant::Default)
|
||||
};
|
||||
let included_user_ids = screen_share_delivery.included_user_ids.join("\n");
|
||||
let excluded_user_ids = screen_share_delivery.excluded_user_ids.join("\n");
|
||||
let included_user_ids = push_service_delivery.included_user_ids.join("\n");
|
||||
let excluded_user_ids = push_service_delivery.excluded_user_ids.join("\n");
|
||||
section_card_with_description(
|
||||
"Screen Share Delivery",
|
||||
"Pick how many clients publish screen shares through the reworked delivery path. While \
|
||||
the master switch below is off nothing on this form reaches any client: every user \
|
||||
keeps the screen share pipeline they have today, whatever the rest of these fields say. \
|
||||
A client that is already sharing keeps the path it started on until the share ends.",
|
||||
"Push Service Delivery",
|
||||
"Routes push notification delivery for the selected accounts through the push service. \
|
||||
Accounts the rollout does not select keep the current path.",
|
||||
html! {
|
||||
form method="post" action={(base) "/instance-config?action=update_screen_share_delivery"} {
|
||||
form method="post" action={(base) "/instance-config?action=update_push_service_delivery"} {
|
||||
(csrf_input(csrf_token))
|
||||
div class="space-y-6" {
|
||||
div class="flex flex-wrap items-center gap-2" {
|
||||
h3 class="text-sm font-semibold text-neutral-900" { "Master switch" }
|
||||
(badge(status.0, status.1))
|
||||
span class="text-xs text-neutral-500" {
|
||||
"Config version " (screen_share_delivery.config_version)
|
||||
"Config version " (push_service_delivery.config_version)
|
||||
}
|
||||
}
|
||||
(checkbox(
|
||||
"screen_share_delivery_enabled",
|
||||
"push_service_delivery_enabled",
|
||||
"true",
|
||||
"Serve screen share delivery assignments to clients",
|
||||
screen_share_delivery.enabled,
|
||||
"Hand push notifications to the push service",
|
||||
push_service_delivery.enabled,
|
||||
true,
|
||||
))
|
||||
p class="text-xs text-neutral-500" {
|
||||
"Off is the safe state. With this unchecked every client is told the \
|
||||
feature is inert and keeps its current behavior, so the rollout and \
|
||||
targeting fields below have no effect at all."
|
||||
"Off is the safe state. With this unchecked every notification keeps the \
|
||||
current delivery path, so the rollout and targeting fields below have no \
|
||||
effect at all."
|
||||
}
|
||||
|
||||
h3 class="text-sm font-semibold text-neutral-900" { "Rollout" }
|
||||
(number_field(
|
||||
"screen_share_delivery_rollout_basis_points",
|
||||
"push_service_delivery_rollout_basis_points",
|
||||
"Rollout (basis points)",
|
||||
&screen_share_delivery.rollout_basis_points.to_string(),
|
||||
&push_service_delivery.rollout_basis_points.to_string(),
|
||||
Some(0), Some(10000), "1",
|
||||
Some("Share of users bucketed into the canary, in basis points: 0 is nobody, 100 is 1%, 10000 is everybody."),
|
||||
))
|
||||
div class="flex flex-col gap-2" {
|
||||
(text_input(
|
||||
"screen_share_delivery_rollout_salt",
|
||||
"push_service_delivery_rollout_salt",
|
||||
"Rollout Salt",
|
||||
&screen_share_delivery.rollout_salt,
|
||||
SCREEN_SHARE_DELIVERY_DEFAULT_SALT,
|
||||
&push_service_delivery.rollout_salt,
|
||||
PUSH_SERVICE_DELIVERY_DEFAULT_SALT,
|
||||
))
|
||||
p class="text-xs text-neutral-500" {
|
||||
"Seeds the bucketing hash. Changing it reshuffles which users fall \
|
||||
@@ -1243,7 +1240,7 @@ fn screen_share_delivery_section(
|
||||
}
|
||||
div class="flex flex-col gap-2" {
|
||||
(textarea_input(
|
||||
"screen_share_delivery_included_user_ids",
|
||||
"push_service_delivery_included_user_ids",
|
||||
"Always-on User IDs",
|
||||
"1500000000000000001\n1500000000000000002",
|
||||
&included_user_ids,
|
||||
@@ -1251,19 +1248,19 @@ fn screen_share_delivery_section(
|
||||
false,
|
||||
))
|
||||
(entry_count_hint(
|
||||
screen_share_delivery.included_user_ids.len(),
|
||||
push_service_delivery.included_user_ids.len(),
|
||||
EXPERIMENT_MAX_TARGETED_USERS,
|
||||
))
|
||||
p class="text-xs text-neutral-500" {
|
||||
"One snowflake per line, or comma separated. These users are targeted \
|
||||
regardless of the percentage above. IDs must contain 1 to 20 decimal \
|
||||
digits. Invalid entries prevent the save; blank entries and duplicate \
|
||||
digits. Invalid entries prevent the save. Blank entries and duplicate \
|
||||
IDs are ignored."
|
||||
}
|
||||
}
|
||||
div class="flex flex-col gap-2" {
|
||||
(textarea_input(
|
||||
"screen_share_delivery_excluded_user_ids",
|
||||
"push_service_delivery_excluded_user_ids",
|
||||
"Never-on User IDs",
|
||||
"1500000000000000003\n1500000000000000004",
|
||||
&excluded_user_ids,
|
||||
@@ -1271,17 +1268,17 @@ fn screen_share_delivery_section(
|
||||
false,
|
||||
))
|
||||
(entry_count_hint(
|
||||
screen_share_delivery.excluded_user_ids.len(),
|
||||
push_service_delivery.excluded_user_ids.len(),
|
||||
EXPERIMENT_MAX_TARGETED_USERS,
|
||||
))
|
||||
p class="text-xs text-neutral-500" {
|
||||
"Same format. Exclusion wins over both the always-on list and the \
|
||||
percentage, so this is the per-user kill switch."
|
||||
percentage. This is the per-user kill switch."
|
||||
}
|
||||
}
|
||||
|
||||
(form_actions(html! {
|
||||
(submit_button("Save Screen Share Delivery Configuration"))
|
||||
(submit_button("Save Push Service Delivery Configuration"))
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -1932,25 +1929,6 @@ mod tests {
|
||||
assert!(!markup.contains("at the cap"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_share_delivery_section_shows_list_counts_and_the_master_switch() {
|
||||
let screen_share_delivery = ScreenShareDeliveryConfigResponse {
|
||||
included_user_ids: vec!["1500000000000000001".to_owned()],
|
||||
excluded_user_ids: vec![
|
||||
"1500000000000000002".to_owned(),
|
||||
"1500000000000000003".to_owned(),
|
||||
],
|
||||
..ScreenShareDeliveryConfigResponse::default()
|
||||
};
|
||||
let markup =
|
||||
screen_share_delivery_section("/admin", "csrf", &screen_share_delivery).into_string();
|
||||
assert!(markup.contains("action=update_screen_share_delivery"));
|
||||
assert!(markup.contains("screen_share_delivery_enabled"));
|
||||
assert!(markup.contains("1 of 1000 stored"));
|
||||
assert!(markup.contains("2 of 1000 stored"));
|
||||
assert!(!markup.contains("at the cap"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_noise_suppression_section_flags_a_list_at_its_cap() {
|
||||
let voice_noise_suppression = VoiceNoiseSuppressionConfigResponse {
|
||||
|
||||
@@ -114,7 +114,10 @@ pub fn users_list_page(
|
||||
let content = html! {
|
||||
div class="space-y-6" {
|
||||
(page_header("Users", None))
|
||||
div class="rounded-lg bg-white transition-all border border-neutral-200 p-4" {
|
||||
div class="rounded-lg bg-white transition-all border border-neutral-200 p-3" {
|
||||
p class="mb-1 text-xs text-neutral-500" {
|
||||
"For example, type " span class="font-mono" { "*" } " in to search for all users."
|
||||
}
|
||||
(search_form(base, params))
|
||||
}
|
||||
(results_markup)
|
||||
|
||||
@@ -409,13 +409,12 @@ fn deserialize_instance_config_response_with_unknown_keys() {
|
||||
"future_object_knob": {"nested": true},
|
||||
"future_list_knob": ["a", "b"]
|
||||
},
|
||||
"screen_share_delivery": {
|
||||
"push_service_delivery": {
|
||||
"enabled": true,
|
||||
"config_version": 2,
|
||||
"rollout_basis_points": 2500,
|
||||
"rollout_salt": "screen-share-delivery-v1",
|
||||
"included_user_ids": ["1500000000000000001"],
|
||||
"future_delivery_knob": 9,
|
||||
"config_version": 3,
|
||||
"rollout_basis_points": 5000,
|
||||
"rollout_salt": "push-service-delivery-v1",
|
||||
"included_user_ids": ["1500000000000000002"],
|
||||
"excluded_user_ids": []
|
||||
},
|
||||
"experiment_delivery": {"poll_interval_seconds": 300, "poll_jitter_percent": 15},
|
||||
@@ -547,14 +546,6 @@ fn deserialize_instance_config_response_with_unknown_keys() {
|
||||
assert_eq!(resp.voice_noise_suppression.rollout_basis_points, 10000);
|
||||
assert_eq!(*resp.voice_noise_suppression.rollout_salt, "voice-ns-v1");
|
||||
assert_eq!(resp.voice_noise_suppression.enabled_backends.len(), 3);
|
||||
assert!(resp.screen_share_delivery.enabled);
|
||||
assert_eq!(resp.screen_share_delivery.config_version, 2);
|
||||
assert_eq!(resp.screen_share_delivery.rollout_basis_points, 2500);
|
||||
assert_eq!(
|
||||
*resp.screen_share_delivery.rollout_salt,
|
||||
"screen-share-delivery-v1"
|
||||
);
|
||||
assert_eq!(resp.screen_share_delivery.included_user_ids.len(), 1);
|
||||
assert_eq!(resp.experiment_delivery.poll_interval_seconds, 300);
|
||||
assert!(resp.policy.single_community_guild_id.is_none());
|
||||
assert_eq!(resp.policy.services.gif_enabled, Some(true));
|
||||
@@ -565,7 +556,6 @@ fn deserialize_instance_config_response_with_unknown_keys() {
|
||||
.replace("\"future_rollout_knob\": 3,", "")
|
||||
.replace("\"future_presentation_knob\": \"verbose\",", "")
|
||||
.replace("\"future_knob\": 7,", "")
|
||||
.replace("\"future_delivery_knob\": 9,", "")
|
||||
.replace("\"future_object_knob\": {\"nested\": true},", "")
|
||||
.replace("\"future_list_knob\": [\"a\", \"b\"],", "")
|
||||
.replace(
|
||||
|
||||
@@ -465,7 +465,6 @@ async fn mutating_admin_pages_render_usable_csrf_tokens() {
|
||||
"/instance-config?action=update_gateway_rollout",
|
||||
"/instance-config?action=update_sso",
|
||||
"/instance-config?action=update_voice_noise_suppression",
|
||||
"/instance-config?action=update_screen_share_delivery",
|
||||
"/instance-config?action=update_experiment_delivery",
|
||||
][..],
|
||||
),
|
||||
@@ -817,6 +816,9 @@ async fn spawn_mock_api() -> String {
|
||||
|
||||
async fn mock_api(method: Method, uri: Uri) -> Response {
|
||||
let path = uri.path().to_owned();
|
||||
if method == Method::PATCH && path == "/admin/instance/config" {
|
||||
return json_response(instance_config());
|
||||
}
|
||||
match (method, path.as_str()) {
|
||||
(Method::GET, "/admin/users/@me") => json_response(json!({ "user": admin_user() })),
|
||||
(Method::GET, "/admin/api-keys") => json_response(json!([])),
|
||||
@@ -1197,14 +1199,6 @@ fn instance_config() -> Value {
|
||||
"guild_overrides": [],
|
||||
"suppression_strength": 80
|
||||
},
|
||||
"screen_share_delivery": {
|
||||
"enabled": false,
|
||||
"config_version": 0,
|
||||
"rollout_basis_points": 0,
|
||||
"rollout_salt": "screen-share-delivery-v1",
|
||||
"included_user_ids": [],
|
||||
"excluded_user_ids": []
|
||||
},
|
||||
"experiment_delivery": {
|
||||
"poll_interval_seconds": 300,
|
||||
"poll_jitter_percent": 15
|
||||
|
||||
@@ -272,8 +272,6 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
|
||||
donationProxyKey,
|
||||
},
|
||||
hosts: {
|
||||
invite: extractHostname(master.endpoints.invite),
|
||||
gift: extractHostname(master.endpoints.gift),
|
||||
marketing: extractHostname(master.endpoints.marketing),
|
||||
unfurlIgnored: master.services.api.unfurl_ignored_hosts,
|
||||
},
|
||||
@@ -478,6 +476,10 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
|
||||
},
|
||||
abusePolicy: {
|
||||
inboundPhoneCountryCodes: master.instance.abuse_policy.inbound_phone_country_codes,
|
||||
phoneFlagging: {
|
||||
enabled: master.instance.abuse_policy.phone_flagging.enabled,
|
||||
exemptCountryCodes: master.instance.abuse_policy.phone_flagging.exempt_country_codes,
|
||||
},
|
||||
phoneVerification: {
|
||||
inboundRequiredPrefixes: master.instance.abuse_policy.phone_verification.inbound_required_prefixes,
|
||||
},
|
||||
|
||||
@@ -13,7 +13,11 @@ import {deriveSsoRedirectUri, normalizeAndValidateSsoConfig} from '@app/api/inst
|
||||
import {requireAdminACL} from '@app/api/middleware/AdminMiddleware';
|
||||
import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
|
||||
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
|
||||
import {getGatewayRolloutConfigPublisher, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
|
||||
import {
|
||||
getGatewayRolloutConfigPublisher,
|
||||
getInstanceConfigRepository,
|
||||
getPushServiceDeliveryConfigPublisher,
|
||||
} from '@app/api/middleware/ServiceSingletons';
|
||||
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
|
||||
import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
|
||||
import {Validator} from '@app/api/Validator';
|
||||
@@ -31,7 +35,7 @@ import {
|
||||
RegistrationUrlIdParam,
|
||||
} from '@fluxer/schema/src/domains/admin/AdminSchemas';
|
||||
import {GatewayRolloutConfigSchema} from '@fluxer/schema/src/domains/admin/GatewayRolloutSchemas';
|
||||
import {ScreenShareDeliveryConfigSchema} from '@fluxer/schema/src/domains/admin/ScreenShareDeliverySchemas';
|
||||
import {PushServiceDeliveryConfigSchema} from '@fluxer/schema/src/domains/admin/PushServiceDeliverySchemas';
|
||||
import {VoiceNoiseSuppressionConfigSchema} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';
|
||||
import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
|
||||
import {ExperimentDeliveryConfigSchema} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
|
||||
@@ -60,7 +64,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {
|
||||
ssoConfig,
|
||||
gatewayRollout,
|
||||
voiceNoiseSuppression,
|
||||
screenShareDelivery,
|
||||
pushServiceDelivery,
|
||||
experimentDelivery,
|
||||
registrationConfig,
|
||||
registrationUrls,
|
||||
@@ -69,7 +73,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {
|
||||
instanceConfigRepository.getSsoConfig(),
|
||||
instanceConfigRepository.getGatewayRolloutConfig(),
|
||||
instanceConfigRepository.getVoiceNoiseSuppressionConfig(),
|
||||
instanceConfigRepository.getScreenShareDeliveryConfig(),
|
||||
instanceConfigRepository.getPushServiceDeliveryConfig(),
|
||||
instanceConfigRepository.getExperimentDeliveryConfig(),
|
||||
instanceConfigRepository.getRegistrationConfig(),
|
||||
instanceConfigRepository.getRegistrationUrlsForAdmin(),
|
||||
@@ -101,7 +105,7 @@ async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {
|
||||
},
|
||||
gateway_rollout: gatewayRollout,
|
||||
voice_noise_suppression: voiceNoiseSuppression,
|
||||
screen_share_delivery: screenShareDelivery,
|
||||
push_service_delivery: pushServiceDelivery,
|
||||
experiment_delivery: experimentDelivery,
|
||||
registration: {
|
||||
...registrationConfig,
|
||||
@@ -247,43 +251,42 @@ export function InstanceConfigAdminController(app: HonoApp) {
|
||||
const shouldGrantSetupCompleterAdmin =
|
||||
appPublicBeforeUpdate !== null && completesInitialSetup(data, appPublicBeforeUpdate.setup.configured);
|
||||
if (data.gateway_rollout) {
|
||||
const currentRollout = await instanceConfigRepository.getGatewayRolloutConfig();
|
||||
const merged = {...currentRollout, ...data.gateway_rollout};
|
||||
const validated = GatewayRolloutConfigSchema.parse(merged);
|
||||
await instanceConfigRepository.setGatewayRolloutConfig(validated);
|
||||
await getGatewayRolloutConfigPublisher().publish(validated);
|
||||
const patch = data.gateway_rollout;
|
||||
const landed = await instanceConfigRepository.updateGatewayRolloutConfig((current) =>
|
||||
GatewayRolloutConfigSchema.parse({...current, ...patch}),
|
||||
);
|
||||
await getGatewayRolloutConfigPublisher().publish(landed);
|
||||
}
|
||||
if (data.voice_noise_suppression) {
|
||||
const patch = omitUndefinedFields(data.voice_noise_suppression);
|
||||
if (Object.keys(patch).length > 0) {
|
||||
const currentNoiseSuppression = await instanceConfigRepository.getVoiceNoiseSuppressionConfig();
|
||||
const validated = VoiceNoiseSuppressionConfigSchema.parse({
|
||||
...currentNoiseSuppression,
|
||||
...patch,
|
||||
config_version: currentNoiseSuppression.config_version + 1,
|
||||
});
|
||||
await instanceConfigRepository.setVoiceNoiseSuppressionConfig(validated);
|
||||
await instanceConfigRepository.updateVoiceNoiseSuppressionConfig((current) =>
|
||||
VoiceNoiseSuppressionConfigSchema.parse({
|
||||
...current,
|
||||
...patch,
|
||||
config_version: current.config_version + 1,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (data.screen_share_delivery) {
|
||||
const patch = omitUndefinedFields(data.screen_share_delivery);
|
||||
if (data.push_service_delivery) {
|
||||
const patch = omitUndefinedFields(data.push_service_delivery);
|
||||
if (Object.keys(patch).length > 0) {
|
||||
const currentScreenShareDelivery = await instanceConfigRepository.getScreenShareDeliveryConfig();
|
||||
const validated = ScreenShareDeliveryConfigSchema.parse({
|
||||
...currentScreenShareDelivery,
|
||||
...patch,
|
||||
config_version: currentScreenShareDelivery.config_version + 1,
|
||||
});
|
||||
await instanceConfigRepository.setScreenShareDeliveryConfig(validated);
|
||||
const landed = await instanceConfigRepository.updatePushServiceDeliveryConfig((current) =>
|
||||
PushServiceDeliveryConfigSchema.parse({
|
||||
...current,
|
||||
...patch,
|
||||
config_version: current.config_version + 1,
|
||||
}),
|
||||
);
|
||||
await getPushServiceDeliveryConfigPublisher().publish(landed);
|
||||
}
|
||||
}
|
||||
if (data.experiment_delivery) {
|
||||
const currentExperimentDelivery = await instanceConfigRepository.getExperimentDeliveryConfig();
|
||||
const validated = ExperimentDeliveryConfigSchema.parse({
|
||||
...currentExperimentDelivery,
|
||||
...data.experiment_delivery,
|
||||
});
|
||||
await instanceConfigRepository.setExperimentDeliveryConfig(validated);
|
||||
const patch = data.experiment_delivery;
|
||||
await instanceConfigRepository.updateExperimentDeliveryConfig((current) =>
|
||||
ExperimentDeliveryConfigSchema.parse({...current, ...patch}),
|
||||
);
|
||||
}
|
||||
if (data.sso) {
|
||||
const sso = data.sso;
|
||||
@@ -308,21 +311,22 @@ export function InstanceConfigAdminController(app: HonoApp) {
|
||||
const validated = await normalizeAndValidateSsoConfig(next, {
|
||||
testModeEnabled: Config.dev.testModeEnabled,
|
||||
});
|
||||
const supplied = <T>(field: keyof typeof sso, value: T): T | undefined =>
|
||||
readOptionalField(sso, field) === undefined ? undefined : value;
|
||||
await instanceConfigRepository.setSsoConfig({
|
||||
enabled: validated.enabled,
|
||||
enforced: validated.enforced,
|
||||
displayName: next.displayName,
|
||||
issuer: validated.issuer,
|
||||
authorizationUrl: validated.authorizationUrl,
|
||||
tokenUrl: validated.tokenUrl,
|
||||
userInfoUrl: validated.userInfoUrl,
|
||||
jwksUrl: validated.jwksUrl,
|
||||
clientId: validated.clientId,
|
||||
enabled: supplied('enabled', validated.enabled),
|
||||
enforced: supplied('enforced', validated.enforced),
|
||||
displayName: supplied('display_name', next.displayName),
|
||||
issuer: supplied('issuer', validated.issuer),
|
||||
authorizationUrl: supplied('authorization_url', validated.authorizationUrl),
|
||||
tokenUrl: supplied('token_url', validated.tokenUrl),
|
||||
userInfoUrl: supplied('userinfo_url', validated.userInfoUrl),
|
||||
jwksUrl: supplied('jwks_url', validated.jwksUrl),
|
||||
clientId: supplied('client_id', validated.clientId),
|
||||
clientSecret: readOptionalField(sso, 'client_secret'),
|
||||
scope: next.scope,
|
||||
allowedEmailDomains: validated.allowedEmailDomains,
|
||||
autoProvision: next.autoProvision,
|
||||
redirectUri: null,
|
||||
scope: supplied('scope', next.scope),
|
||||
allowedEmailDomains: supplied('allowed_domains', validated.allowedEmailDomains),
|
||||
autoProvision: supplied('auto_provision', next.autoProvision),
|
||||
});
|
||||
}
|
||||
if (data.registration) {
|
||||
@@ -625,7 +629,6 @@ export function InstanceConfigAdminController(app: HonoApp) {
|
||||
async (ctx) => {
|
||||
const userId = ctx.req.valid('param').user_id.toString();
|
||||
const decision = ctx.req.valid('json').status === 'approved' ? 'approve' : 'reject';
|
||||
await instanceConfigRepository.getPendingRegistrations();
|
||||
await updatePendingRegistrationUser(ctx, userId, decision);
|
||||
await instanceConfigRepository.removePendingRegistration(userId);
|
||||
return ctx.json(await buildInstanceConfigResponse());
|
||||
@@ -638,27 +641,47 @@ async function applyInstancePolicyUpdate(
|
||||
policy: NonNullable<InstanceConfigUpdateRequest['policy']>,
|
||||
): Promise<void> {
|
||||
const instanceConfigRepository = getInstanceConfigRepository();
|
||||
const [current, appPublic] = await Promise.all([
|
||||
instanceConfigRepository.getInstancePolicyConfig(),
|
||||
instanceConfigRepository.getAppPublicConfig(),
|
||||
]);
|
||||
const appPublic = await instanceConfigRepository.getAppPublicConfig();
|
||||
const adminUser =
|
||||
policy.single_community_enabled === true
|
||||
? await ctx.get('userRepository').findUnique(ctx.get('adminUserId'))
|
||||
: null;
|
||||
let enablesSingleCommunity = false;
|
||||
await instanceConfigRepository.updateInstancePolicyConfig((current) => {
|
||||
const planned = planInstancePolicyPatch(policy, current, {
|
||||
setupConfigured: appPublic.setup.configured,
|
||||
adminUserFound: adminUser !== null,
|
||||
});
|
||||
enablesSingleCommunity = planned.enablesSingleCommunity;
|
||||
return planned.patch;
|
||||
});
|
||||
if (enablesSingleCommunity && adminUser) {
|
||||
await ctx.get('singleCommunityService').ensureStockCommunity({
|
||||
owner: adminUser,
|
||||
name: policy.single_community_name?.trim() || appPublic.branding.product_name,
|
||||
});
|
||||
}
|
||||
if (policy.premium_mode !== undefined) {
|
||||
await ctx.get('limitConfigService').updatePolicyConfig({premium_mode: policy.premium_mode});
|
||||
}
|
||||
}
|
||||
|
||||
function planInstancePolicyPatch(
|
||||
policy: NonNullable<InstanceConfigUpdateRequest['policy']>,
|
||||
current: InstancePolicyConfig,
|
||||
context: {setupConfigured: boolean; adminUserFound: boolean},
|
||||
): {patch: Partial<InstancePolicyConfig>; enablesSingleCommunity: boolean} {
|
||||
const patch: Partial<InstancePolicyConfig> = {};
|
||||
let enablesSingleCommunity = false;
|
||||
if (
|
||||
policy.single_community_enabled !== undefined &&
|
||||
policy.single_community_enabled !== current.single_community_enabled
|
||||
) {
|
||||
if (policy.single_community_enabled) {
|
||||
if (appPublic.setup.configured && current.single_community_guild_id == null) {
|
||||
if ((context.setupConfigured && current.single_community_guild_id == null) || !context.adminUserFound) {
|
||||
throw new InstancePolicyTransitionNotAllowedError();
|
||||
}
|
||||
const adminUser = await ctx.get('userRepository').findUnique(ctx.get('adminUserId'));
|
||||
if (!adminUser) {
|
||||
throw new InstancePolicyTransitionNotAllowedError();
|
||||
}
|
||||
await ctx.get('singleCommunityService').ensureStockCommunity({
|
||||
owner: adminUser,
|
||||
name: policy.single_community_name?.trim() || appPublic.branding.product_name,
|
||||
});
|
||||
enablesSingleCommunity = true;
|
||||
} else {
|
||||
patch.single_community_enabled = false;
|
||||
}
|
||||
@@ -679,9 +702,6 @@ async function applyInstancePolicyUpdate(
|
||||
patch.direct_messages_locked = true;
|
||||
}
|
||||
}
|
||||
if (policy.premium_mode !== undefined) {
|
||||
patch.premium_mode = policy.premium_mode;
|
||||
}
|
||||
if (policy.services) {
|
||||
if (policy.services.gif_enabled !== undefined) {
|
||||
patch.gif_enabled = policy.services.gif_enabled ?? null;
|
||||
@@ -704,11 +724,7 @@ async function applyInstancePolicyUpdate(
|
||||
patch.deferred_phone_gate_member_threshold = policy.deferred_phone_gate.member_threshold;
|
||||
}
|
||||
}
|
||||
if (patch.premium_mode !== undefined) {
|
||||
await ctx.get('limitConfigService').updatePolicyConfig(patch);
|
||||
} else if (Object.keys(patch).length > 0) {
|
||||
await instanceConfigRepository.setInstancePolicyConfig(patch);
|
||||
}
|
||||
return {patch, enablesSingleCommunity};
|
||||
}
|
||||
|
||||
async function updatePendingRegistrationUser(
|
||||
|
||||
@@ -11,6 +11,7 @@ import {Logger} from '@app/api/Logger';
|
||||
import {getGuildSearchService, getUserSearchService} from '@app/api/SearchFactory';
|
||||
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
|
||||
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
|
||||
import type {UserSearchFilters} from '@fluxer/schema/src/contracts/search/SearchDocumentTypes';
|
||||
import type {WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';
|
||||
|
||||
interface RefreshSearchIndexJobPayload extends WorkerJobPayload {
|
||||
@@ -130,16 +131,28 @@ export class AdminSearchService {
|
||||
throw new FeatureTemporarilyDisabledError();
|
||||
}
|
||||
const query = data.query?.trim() || '';
|
||||
const isBrowseAll = query === '' || query === '*';
|
||||
const searchFilters: UserSearchFilters = isBrowseAll
|
||||
? {sortBy: 'createdAt', sortOrder: 'asc'}
|
||||
: {sortBy: 'relevance'};
|
||||
const directUserId = /^\d+$/.test(query) ? createUserID(BigInt(query)) : null;
|
||||
const canResolveDirectUser = directUserId !== null && !isSyntheticUserId(directUserId) && data.offset === 0;
|
||||
const [searchResult, directUser] = await Promise.all([
|
||||
userSearchService.search(query, {}, {limit: data.limit, offset: data.offset}),
|
||||
userSearchService.search(query, searchFilters, {limit: data.limit, offset: data.offset}),
|
||||
canResolveDirectUser ? userRepository.findUnique(directUserId).catch(() => null) : Promise.resolve(null),
|
||||
]);
|
||||
const {hits, total} = searchResult;
|
||||
const userIds = hits.map((hit) => createUserID(BigInt(hit.id)));
|
||||
const users = await userRepository.listUsers(userIds);
|
||||
const response = await Promise.all(users.map((user) => mapUserToAdminResponse(user, cacheService, acls)));
|
||||
const usersById = new Map(users.map((user) => [user.id.toString(), user]));
|
||||
const orderedUsers = [];
|
||||
for (const userId of userIds) {
|
||||
const user = usersById.get(userId.toString());
|
||||
if (user) {
|
||||
orderedUsers.push(user);
|
||||
}
|
||||
}
|
||||
const response = await Promise.all(orderedUsers.map((user) => mapUserToAdminResponse(user, cacheService, acls)));
|
||||
if (directUser && data.offset === 0) {
|
||||
const directId = directUser.id.toString();
|
||||
if (!response.some((u) => u.id === directId)) {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type {AdminAuditLog} from '@app/api/admin/IAdminRepository';
|
||||
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
|
||||
import {PushServiceDeliveryConfigPublisher} from '@app/api/instance/PushServiceDeliveryConfigPublisher';
|
||||
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
|
||||
import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';
|
||||
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {createApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder} from '@app/api/test/TestRequestBuilder';
|
||||
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
|
||||
import {
|
||||
DEFAULT_PUSH_SERVICE_DELIVERY_CONFIG,
|
||||
type PushServiceDeliveryConfig,
|
||||
} from '@fluxer/schema/src/domains/admin/PushServiceDeliverySchemas';
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
const PUSH_SERVICE_DELIVERY_CONFIG_KEY = 'push_service_delivery_config';
|
||||
|
||||
describe('instance config admin PATCH under concurrent writes', () => {
|
||||
let harness: ApiTestHarness;
|
||||
let executor: InstanceConfigWriteRaceExecutor;
|
||||
|
||||
beforeAll(async () => {
|
||||
harness = await createApiTestHarness();
|
||||
executor = new InstanceConfigWriteRaceExecutor(new InMemoryCassandraQueryExecutor());
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await harness.reset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await harness.shutdown();
|
||||
});
|
||||
|
||||
const createAdmin = async (): Promise<TestAccount> =>
|
||||
await setUserACLs(harness, await createTestAccount(harness), [
|
||||
AdminACLs.AUTHENTICATE,
|
||||
AdminACLs.INSTANCE_CONFIG_VIEW,
|
||||
AdminACLs.INSTANCE_CONFIG_UPDATE,
|
||||
]);
|
||||
|
||||
const patchConfig = (admin: TestAccount, body: Record<string, unknown>) =>
|
||||
createBuilder<InstanceConfigResponse>(harness, admin.token).patch('/admin/instance/config').body(body);
|
||||
|
||||
const spyOnPushDeliveryPublishes = () =>
|
||||
vi.spyOn(PushServiceDeliveryConfigPublisher.prototype, 'publish').mockResolvedValue(undefined);
|
||||
|
||||
async function readStoredPushServiceDelivery(): Promise<PushServiceDeliveryConfig> {
|
||||
const raw = await executor.readDirectly(PUSH_SERVICE_DELIVERY_CONFIG_KEY);
|
||||
if (raw === null) throw new Error('push service delivery config was never stored');
|
||||
return JSON.parse(raw) as PushServiceDeliveryConfig;
|
||||
}
|
||||
|
||||
async function listConfigUpdateAudits(): Promise<Array<AdminAuditLog>> {
|
||||
const logs = await getAdminRepository().listAllAuditLogsPaginated(100000);
|
||||
return logs.filter((log) => log.action === 'update_instance_config');
|
||||
}
|
||||
|
||||
it('answers with a conflict and neither writes, publishes nor audits once every attempt has lost the race', async () => {
|
||||
const publish = spyOnPushDeliveryPublishes();
|
||||
const admin = await createAdmin();
|
||||
await patchConfig(admin, {push_service_delivery: {enabled: true, rollout_basis_points: 1000}}).execute();
|
||||
publish.mockClear();
|
||||
const auditsBefore = await listConfigUpdateAudits();
|
||||
executor.watch(PUSH_SERVICE_DELIVERY_CONFIG_KEY);
|
||||
let competingWrites = 0;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
competingWrites++;
|
||||
await executor.writeDirectly(
|
||||
PUSH_SERVICE_DELIVERY_CONFIG_KEY,
|
||||
JSON.stringify({
|
||||
...DEFAULT_PUSH_SERVICE_DELIVERY_CONFIG,
|
||||
enabled: false,
|
||||
rollout_basis_points: 1000,
|
||||
config_version: 100 + competingWrites,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
await patchConfig(admin, {push_service_delivery: {rollout_basis_points: 5000}})
|
||||
.expect(HTTP_STATUS.CONFLICT, APIErrorCodes.CONFLICT)
|
||||
.execute();
|
||||
|
||||
expect(executor.events).not.toContain('write');
|
||||
expect(await readStoredPushServiceDelivery()).toEqual({
|
||||
...DEFAULT_PUSH_SERVICE_DELIVERY_CONFIG,
|
||||
enabled: false,
|
||||
rollout_basis_points: 1000,
|
||||
config_version: 100 + competingWrites,
|
||||
});
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(await listConfigUpdateAudits()).toHaveLength(auditsBefore.length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
|
||||
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
|
||||
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {createApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder} from '@app/api/test/TestRequestBuilder';
|
||||
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';
|
||||
|
||||
describe('instance config admin PATCH against state another node changed', () => {
|
||||
let harness: ApiTestHarness;
|
||||
let executor: InstanceConfigWriteRaceExecutor;
|
||||
|
||||
beforeAll(async () => {
|
||||
harness = await createApiTestHarness();
|
||||
executor = new InstanceConfigWriteRaceExecutor(new InMemoryCassandraQueryExecutor());
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await harness.reset();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await harness.shutdown();
|
||||
});
|
||||
|
||||
const createAdmin = async (): Promise<TestAccount> =>
|
||||
await setUserACLs(harness, await createTestAccount(harness), [
|
||||
AdminACLs.AUTHENTICATE,
|
||||
AdminACLs.INSTANCE_CONFIG_VIEW,
|
||||
AdminACLs.INSTANCE_CONFIG_UPDATE,
|
||||
]);
|
||||
|
||||
const patchConfig = (admin: TestAccount, body: Record<string, unknown>) =>
|
||||
createBuilder<InstanceConfigResponse>(harness, admin.token).patch('/admin/instance/config').body(body);
|
||||
|
||||
it('keeps an SSO field another node changed when a patch changes a different one', async () => {
|
||||
const admin = await createAdmin();
|
||||
await patchConfig(admin, {sso: {display_name: 'Before', client_id: 'client-before'}}).execute();
|
||||
await executor.writeDirectly('sso_display_name', 'Changed on another node');
|
||||
|
||||
await patchConfig(admin, {sso: {client_id: 'client-after'}}).execute();
|
||||
|
||||
expect(await executor.readDirectly('sso_display_name')).toBe('Changed on another node');
|
||||
expect(await executor.readDirectly('sso_client_id')).toBe('client-after');
|
||||
});
|
||||
|
||||
it('refuses to disable direct messages when their lock lands between the read and the write', async () => {
|
||||
const admin = await createAdmin();
|
||||
await patchConfig(admin, {policy: {services: {gif_enabled: true}}}).execute();
|
||||
executor.watch(INSTANCE_POLICY_CONFIG_KEY);
|
||||
let competed = false;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
if (competed) return;
|
||||
competed = true;
|
||||
await executor.writeDirectly(
|
||||
INSTANCE_POLICY_CONFIG_KEY,
|
||||
JSON.stringify({direct_messages_disabled: false, direct_messages_locked: true, gif_enabled: true}),
|
||||
);
|
||||
});
|
||||
|
||||
await patchConfig(admin, {policy: {direct_messages_disabled: true}})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INSTANCE_POLICY_TRANSITION_NOT_ALLOWED)
|
||||
.execute();
|
||||
|
||||
const stored = JSON.parse((await executor.readDirectly(INSTANCE_POLICY_CONFIG_KEY)) ?? 'null');
|
||||
expect(stored).toMatchObject({direct_messages_disabled: false, direct_messages_locked: true, gif_enabled: true});
|
||||
});
|
||||
|
||||
it('applies the DM rule and a premium mode change from one request', async () => {
|
||||
const admin = await createAdmin();
|
||||
await patchConfig(admin, {policy: {direct_messages_disabled: true}}).execute();
|
||||
|
||||
const updated = await patchConfig(admin, {
|
||||
policy: {direct_messages_disabled: false, premium_mode: 'mirror'},
|
||||
}).execute();
|
||||
|
||||
expect(updated.policy).toMatchObject({
|
||||
direct_messages_disabled: false,
|
||||
direct_messages_locked: true,
|
||||
premium_mode: 'mirror',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {configureMiddleware} from '@app/api/app/MiddlewarePipeline';
|
||||
import {Config} from '@app/api/Config';
|
||||
import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
|
||||
import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
|
||||
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
|
||||
import type {HonoEnv} from '@app/api/types/HonoEnv';
|
||||
import {AppErrorHandler, AppNotFoundHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';
|
||||
import {Hono} from 'hono';
|
||||
import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
const CLIENT_IP_HEADER_NAME = 'x-real-ip';
|
||||
|
||||
function createProductionApp(): Hono<HonoEnv> {
|
||||
const routes = new Hono<HonoEnv>({strict: true});
|
||||
configureMiddleware(routes, {
|
||||
logger: new NoopLogger(),
|
||||
nodeEnv: 'production',
|
||||
corsOrigins: ['https://web.fluxer.app'],
|
||||
trustClientIpHeader: true,
|
||||
clientIpHeaderName: CLIENT_IP_HEADER_NAME,
|
||||
maxInflightRequests: 100,
|
||||
torExitBlockingEnabled: false,
|
||||
});
|
||||
routes.onError(AppErrorHandler);
|
||||
routes.notFound(AppNotFoundHandler);
|
||||
routes.post('/internal/rpc', (ctx) => ctx.json({ok: true}));
|
||||
routes.get('/connections/bluesky/jwks.json', (ctx) => ctx.json({keys: []}));
|
||||
routes.get('/users/@me', (ctx) => ctx.json({ok: true}));
|
||||
const app = new Hono<HonoEnv>({strict: true});
|
||||
app.route('/v1', routes);
|
||||
app.route('/', routes);
|
||||
app.onError(AppErrorHandler);
|
||||
app.notFound(AppNotFoundHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('client ip requirements across the production middleware pipeline', () => {
|
||||
let previousTestModeEnabled: boolean;
|
||||
let previousTrustClientIpHeader: boolean;
|
||||
let previousClientIpHeader: string;
|
||||
|
||||
beforeAll(() => {
|
||||
setInjectedWorkerService(new NoopWorkerService());
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
previousTestModeEnabled = Config.dev.testModeEnabled;
|
||||
previousTrustClientIpHeader = Config.proxy.trust_client_ip_header;
|
||||
previousClientIpHeader = Config.proxy.client_ip_header;
|
||||
Config.dev.testModeEnabled = false;
|
||||
Config.proxy.trust_client_ip_header = true;
|
||||
Config.proxy.client_ip_header = CLIENT_IP_HEADER_NAME;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Config.dev.testModeEnabled = previousTestModeEnabled;
|
||||
Config.proxy.trust_client_ip_header = previousTrustClientIpHeader;
|
||||
Config.proxy.client_ip_header = previousClientIpHeader;
|
||||
});
|
||||
|
||||
it('serves the internal rpc route without a client ip header', async () => {
|
||||
const app = createProductionApp();
|
||||
const response = await app.request('http://api:8080/internal/rpc', {
|
||||
method: 'POST',
|
||||
headers: {'content-type': 'application/json'},
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('serves the internal rpc route with a client ip header', async () => {
|
||||
const app = createProductionApp();
|
||||
const response = await app.request('http://api:8080/internal/rpc', {
|
||||
method: 'POST',
|
||||
headers: {'content-type': 'application/json', [CLIENT_IP_HEADER_NAME]: '203.0.113.10'},
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('serves an exempt public route without a client ip header', async () => {
|
||||
const app = createProductionApp();
|
||||
const response = await app.request('http://api:8080/connections/bluesky/jwks.json');
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('still rejects a non exempt route without a client ip header', async () => {
|
||||
const app = createProductionApp();
|
||||
const response = await app.request('http://api:8080/users/@me');
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toMatchObject({code: 'FORBIDDEN'});
|
||||
});
|
||||
});
|
||||
@@ -7,12 +7,14 @@ import * as AuthUtility from '@app/api/auth/AuthUtility';
|
||||
import type {IRegistrationRiskEvaluator} from '@app/api/auth/services/IRegistrationRiskEvaluator';
|
||||
import {createEmailVerificationToken, createInviteCode, createUserID, type UserID} from '@app/api/BrandedTypes';
|
||||
import type {APIConfig} from '@app/api/config/APIConfig';
|
||||
import type {UserRow} from '@app/api/database/types/UserTypes';
|
||||
import type {IDiscriminatorService} from '@app/api/infrastructure/DiscriminatorService';
|
||||
import type {KVActivityTracker} from '@app/api/infrastructure/KVActivityTracker';
|
||||
import {
|
||||
type InstanceConfigRepository,
|
||||
type InstanceRegistrationUrl,
|
||||
REGISTRATION_PENDING_APPROVAL_TRAIT,
|
||||
type RegistrationUrlClaim,
|
||||
} from '@app/api/instance/InstanceConfigRepository';
|
||||
import type {SingleCommunityService} from '@app/api/instance/SingleCommunityService';
|
||||
import type {InviteService} from '@app/api/invite/InviteService';
|
||||
@@ -21,7 +23,7 @@ import {profileSubstringBlocklistCache} from '@app/api/middleware/ProfileSubstri
|
||||
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import {UserSettings} from '@app/api/models/UserSettings';
|
||||
import {countryRequiresInboundPhoneVerification} from '@app/api/risk/AbusePolicy';
|
||||
import {countryRequiresInboundPhoneVerification, stripDisallowedPhoneFlags} from '@app/api/risk/AbusePolicy';
|
||||
import {
|
||||
type IAccountPolicyEvaluator,
|
||||
isAssessmentThresholdAuditEvent,
|
||||
@@ -135,9 +137,6 @@ export async function register(
|
||||
}
|
||||
const now = new Date();
|
||||
const registrationAccess = await resolveRegistrationAccess(instanceConfigRepository, data.registration_url_code);
|
||||
if (registrationAccess.pendingApproval) {
|
||||
await instanceConfigRepository.getPendingRegistrations();
|
||||
}
|
||||
const clientIp = requireClientIp(request, {
|
||||
trustClientIpHeader: config.proxy.trust_client_ip_header,
|
||||
clientIpHeaderName: config.proxy.client_ip_header,
|
||||
@@ -228,7 +227,7 @@ export async function register(
|
||||
const userLocale = parseAcceptLanguage(acceptLanguage);
|
||||
const passwordHash = data.password ? await AuthPassword.hashPassword(ctx, data.password) : null;
|
||||
const flags = config.nodeEnv === 'development' ? UserFlags.STAFF : 0n;
|
||||
let user = await users.create({
|
||||
const userRow: UserRow = {
|
||||
user_id: userId,
|
||||
username,
|
||||
discriminator,
|
||||
@@ -287,7 +286,39 @@ export async function register(
|
||||
mention_flags: null,
|
||||
last_voice_activity_sharing_change_at: null,
|
||||
version: 1,
|
||||
});
|
||||
};
|
||||
const registrationUrlUse = await claimRegistrationUrlUse(
|
||||
instanceConfigRepository,
|
||||
registrationAccess.registrationUrl,
|
||||
userId,
|
||||
);
|
||||
let user: User;
|
||||
let createAttempted = false;
|
||||
try {
|
||||
if (registrationAccess.pendingApproval) {
|
||||
await instanceConfigRepository.addPendingRegistration({
|
||||
user_id: userId.toString(),
|
||||
username: userRow.username,
|
||||
discriminator: userRow.discriminator,
|
||||
global_name: userRow.global_name,
|
||||
email: rawEmail,
|
||||
requested_at: now.toISOString(),
|
||||
registration_url_id: registrationAccess.registrationUrl?.id ?? null,
|
||||
client_ip: clientIp,
|
||||
});
|
||||
}
|
||||
createAttempted = true;
|
||||
user = await users.create(userRow);
|
||||
} catch (error) {
|
||||
if (!createAttempted) {
|
||||
await withdrawSignupOfUncreatedAccount(instanceConfigRepository, {
|
||||
userId,
|
||||
registrationUrlUse,
|
||||
pendingApproval: registrationAccess.pendingApproval,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await users.upsertSettings(
|
||||
UserSettings.getDefaultUserSettings({
|
||||
userId,
|
||||
@@ -331,7 +362,9 @@ export async function register(
|
||||
action: riskResult.recommendedAction,
|
||||
},
|
||||
});
|
||||
const combinedFlags = await deferPhoneFlagsUntilCommunityJoin(policyDecision.flagBits);
|
||||
const combinedFlags = await deferPhoneFlagsUntilCommunityJoin(
|
||||
await stripDisallowedPhoneFlags(policyDecision.flagBits, async () => countryCode),
|
||||
);
|
||||
const createdAt = new Date();
|
||||
const riskContext = deriveLatestRiskContext({
|
||||
userId: userId.toString(),
|
||||
@@ -401,20 +434,7 @@ export async function register(
|
||||
}
|
||||
if (rawEmail && emailEnabled) await maybeSendVerificationEmail(ctx, {user, email: rawEmail});
|
||||
await users.createAuthorizedIp(userId, clientIp);
|
||||
if (registrationAccess.registrationUrl) {
|
||||
await instanceConfigRepository.recordRegistrationUrlUse(registrationAccess.registrationUrl.id, user.id.toString());
|
||||
}
|
||||
if (registrationAccess.pendingApproval) {
|
||||
await instanceConfigRepository.addPendingRegistration({
|
||||
user_id: user.id.toString(),
|
||||
username: user.username,
|
||||
discriminator: user.discriminator,
|
||||
global_name: user.globalName,
|
||||
email: rawEmail,
|
||||
requested_at: now.toISOString(),
|
||||
registration_url_id: registrationAccess.registrationUrl?.id ?? null,
|
||||
client_ip: clientIp,
|
||||
});
|
||||
return {
|
||||
registration_pending_approval: true,
|
||||
user_id: user.id.toString(),
|
||||
@@ -469,6 +489,38 @@ function shouldAttemptBootstrapAdminGrant(
|
||||
);
|
||||
}
|
||||
|
||||
async function claimRegistrationUrlUse(
|
||||
instanceConfigRepository: InstanceConfigRepository,
|
||||
registrationUrl: InstanceRegistrationUrl | null,
|
||||
userId: UserID,
|
||||
): Promise<RegistrationUrlClaim | null> {
|
||||
if (registrationUrl === null) return null;
|
||||
const use = await instanceConfigRepository.claimRegistrationUrlUse(registrationUrl.id, userId.toString());
|
||||
if (use === null) {
|
||||
throw new RegistrationUrlInvalidError();
|
||||
}
|
||||
return use;
|
||||
}
|
||||
|
||||
async function withdrawSignupOfUncreatedAccount(
|
||||
instanceConfigRepository: InstanceConfigRepository,
|
||||
signup: {userId: UserID; registrationUrlUse: RegistrationUrlClaim | null; pendingApproval: boolean},
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (signup.registrationUrlUse !== null) {
|
||||
await instanceConfigRepository.releaseRegistrationUrlUse(signup.registrationUrlUse);
|
||||
}
|
||||
if (signup.pendingApproval) {
|
||||
await instanceConfigRepository.removePendingRegistration(signup.userId.toString());
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.warn(
|
||||
{userId: signup.userId.toString(), registrationUrlId: signup.registrationUrlUse?.registration_url_id, error},
|
||||
'[AuthRegistration] Failed to withdraw the registration URL use or pending approval of an account that was never created',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveRegistrationAccess(
|
||||
instanceConfigRepository: InstanceConfigRepository,
|
||||
registrationUrlCode: string | null | undefined,
|
||||
|
||||
@@ -382,21 +382,8 @@ export class SsoService {
|
||||
throw new RegistrationClosedError();
|
||||
}
|
||||
const pendingApproval = registrationConfig.mode === 'approval';
|
||||
if (pendingApproval) {
|
||||
await this.instanceConfigRepository.getPendingRegistrations();
|
||||
}
|
||||
const user = await this.provisionUserFromClaims(claims, config, {pendingApproval});
|
||||
if (pendingApproval) {
|
||||
await this.instanceConfigRepository.addPendingRegistration({
|
||||
user_id: user.id.toString(),
|
||||
username: user.username,
|
||||
discriminator: user.discriminator,
|
||||
global_name: user.globalName,
|
||||
email: user.email,
|
||||
requested_at: new Date().toISOString(),
|
||||
registration_url_id: null,
|
||||
client_ip: null,
|
||||
});
|
||||
throw new RegistrationPendingApprovalError();
|
||||
}
|
||||
return user;
|
||||
@@ -537,8 +524,22 @@ export class SsoService {
|
||||
version: 1,
|
||||
} as const;
|
||||
await this.claimSsoIdentity(userId, claims.sub, config);
|
||||
let createAttempted = false;
|
||||
let userCreated = false;
|
||||
try {
|
||||
if (options?.pendingApproval) {
|
||||
await this.instanceConfigRepository.addPendingRegistration({
|
||||
user_id: userId.toString(),
|
||||
username,
|
||||
discriminator: discriminatorResult.discriminator,
|
||||
global_name: globalName,
|
||||
email: userRow.email,
|
||||
requested_at: now.toISOString(),
|
||||
registration_url_id: null,
|
||||
client_ip: null,
|
||||
});
|
||||
}
|
||||
createAttempted = true;
|
||||
const user = await users.create(userRow);
|
||||
userCreated = true;
|
||||
await users.upsertSettings(
|
||||
@@ -557,6 +558,16 @@ export class SsoService {
|
||||
await this.ssoIdentityRepository.releaseIdentity(config.providerId, claims.sub).catch((releaseError) => {
|
||||
getLogger().error({releaseError}, 'Failed to release SSO identity after user provisioning failed');
|
||||
});
|
||||
if (options?.pendingApproval && !createAttempted) {
|
||||
await this.instanceConfigRepository
|
||||
.removePendingRegistration(userId.toString())
|
||||
.catch((removeError: unknown) => {
|
||||
getLogger().error(
|
||||
{userId: userId.toString(), removeError},
|
||||
'Failed to withdraw the pending approval of an SSO user that was never created',
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
loginAccount,
|
||||
registerUser,
|
||||
} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {Config} from '@app/api/Config';
|
||||
import {setInjectedRegistrationRiskEvaluator} from '@app/api/middleware/ServiceMiddleware';
|
||||
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
|
||||
import {
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
SuspiciousActivityFlags,
|
||||
} from '@fluxer/constants/src/UserConstants';
|
||||
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
function phoneRiskEvaluator(level: RiskLevelType, riskScore: number): IRegistrationRiskEvaluator {
|
||||
return {
|
||||
@@ -241,6 +242,59 @@ describe('Deferred phone verification gate', () => {
|
||||
expect(flags & SuspiciousActivityFlags.REQUIRE_VERIFIED_PHONE).not.toBe(0);
|
||||
});
|
||||
|
||||
describe('with phone flagging disabled', () => {
|
||||
const originalPhoneFlagging = {...Config.abusePolicy.phoneFlagging};
|
||||
afterEach(() => {
|
||||
Config.abusePolicy.phoneFlagging = originalPhoneFlagging;
|
||||
});
|
||||
|
||||
it('sets no phone requirement and no deferral at registration', async () => {
|
||||
await getInstanceConfigRepository().setInstancePolicyConfig({deferred_phone_gate_enabled: true});
|
||||
Config.abusePolicy.phoneFlagging = {enabled: false, exemptCountryCodes: []};
|
||||
setInjectedRegistrationRiskEvaluator(phoneRiskEvaluator(RiskLevel.High, 70));
|
||||
const registration = await registerUser(harness, {
|
||||
email: createUniqueEmail('flagging-off'),
|
||||
username: createUniqueUsername('flagging_off'),
|
||||
global_name: 'Flagging Off',
|
||||
password: 'StrongPassword!123',
|
||||
date_of_birth: '2000-01-01',
|
||||
consent: true,
|
||||
});
|
||||
const flags = await readFlags(registration.user_id);
|
||||
expect(flags & SuspiciousActivityFlags.REQUIRE_VERIFIED_PHONE).toBe(0);
|
||||
expect(flags & DEFERRED_PHONE_ON_COMMUNITY_JOIN).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps an existing deferral dormant on a qualifying join', async () => {
|
||||
await getInstanceConfigRepository().setInstancePolicyConfig({
|
||||
deferred_phone_gate_enabled: true,
|
||||
deferred_phone_gate_member_threshold: 1,
|
||||
deferred_phone_gate_window_hours: 24,
|
||||
});
|
||||
const {inviteCode} = await createGuildWithInvite(harness);
|
||||
const filler = await createTestAccount(harness);
|
||||
await createBuilder(harness, filler.token).post(`/invites/${inviteCode}`).expect(200).execute();
|
||||
setInjectedRegistrationRiskEvaluator(phoneRiskEvaluator(RiskLevel.High, 70));
|
||||
const registration = await registerUser(harness, {
|
||||
email: createUniqueEmail('flagging-off-join'),
|
||||
username: createUniqueUsername('flagging_off_join'),
|
||||
global_name: 'Flagging Off Join',
|
||||
password: 'StrongPassword!123',
|
||||
date_of_birth: '2000-01-01',
|
||||
consent: true,
|
||||
});
|
||||
setInjectedRegistrationRiskEvaluator(undefined);
|
||||
expect((await readFlags(registration.user_id)) & DEFERRED_PHONE_ON_COMMUNITY_JOIN).not.toBe(0);
|
||||
|
||||
Config.abusePolicy.phoneFlagging = {enabled: false, exemptCountryCodes: []};
|
||||
await createBuilder(harness, registration.token).post(`/invites/${inviteCode}`).expect(200).execute();
|
||||
|
||||
const flags = await readFlags(registration.user_id);
|
||||
expect(flags & DEFERRED_PHONE_ON_COMMUNITY_JOIN).not.toBe(0);
|
||||
expect(flags & PHONE_GATE_PROMOTED_FROM_DEFERRAL).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('phone gate escape', () => {
|
||||
async function configurePhoneGate(
|
||||
overrides: {
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {createHash} from 'node:crypto';
|
||||
import {
|
||||
createAuthHarness,
|
||||
createTestAccount,
|
||||
createUniqueEmail,
|
||||
createUniqueUsername,
|
||||
enableSso,
|
||||
setUserACLs,
|
||||
type TestAccount,
|
||||
} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {createUserID} from '@app/api/BrandedTypes';
|
||||
import type {UserRow} from '@app/api/database/types/UserTypes';
|
||||
import {
|
||||
InstanceConfigRepository,
|
||||
REGISTRATION_PENDING_APPROVAL_TRAIT,
|
||||
} from '@app/api/instance/InstanceConfigRepository';
|
||||
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
|
||||
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
|
||||
import {UserRepository} from '@app/api/user/repositories/UserRepository';
|
||||
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
const REGISTRATION_URLS_KEY = 'registration_urls';
|
||||
const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';
|
||||
|
||||
interface RegistrationResponse {
|
||||
user_id?: string;
|
||||
token?: string;
|
||||
registration_pending_approval?: true;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
function registrationBody(prefix: string, registrationUrlCode?: string): Record<string, unknown> {
|
||||
return {
|
||||
email: createUniqueEmail(prefix),
|
||||
username: createUniqueUsername(prefix),
|
||||
global_name: 'Signup Race',
|
||||
password: 'a-strong-password',
|
||||
date_of_birth: '2000-01-01',
|
||||
consent: true,
|
||||
...(registrationUrlCode === undefined ? {} : {registration_url_code: registrationUrlCode}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('signups racing on registration URLs and pending approvals', () => {
|
||||
let harness: ApiTestHarness;
|
||||
let admin: TestAccount;
|
||||
|
||||
beforeAll(async () => {
|
||||
harness = await createAuthHarness();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await harness.reset();
|
||||
admin = await setUserACLs(harness, await createTestAccount(harness), [
|
||||
AdminACLs.AUTHENTICATE,
|
||||
AdminACLs.INSTANCE_CONFIG_VIEW,
|
||||
AdminACLs.INSTANCE_CONFIG_UPDATE,
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await harness?.shutdown();
|
||||
});
|
||||
|
||||
const register = (prefix: string, registrationUrlCode?: string) =>
|
||||
createBuilderWithoutAuth<RegistrationResponse>(harness)
|
||||
.post('/auth/register')
|
||||
.body(registrationBody(prefix, registrationUrlCode))
|
||||
.executeRaw();
|
||||
|
||||
const readAdminConfig = (): Promise<InstanceConfigResponse> =>
|
||||
createBuilder<InstanceConfigResponse>(harness, admin.token).get('/admin/instance/config').execute();
|
||||
|
||||
const completeSso = async (prefix: string) => {
|
||||
const start = await createBuilderWithoutAuth<{state: string}>(harness)
|
||||
.post('/auth/sso/start')
|
||||
.body({redirect_to: '/me'})
|
||||
.execute();
|
||||
return createBuilderWithoutAuth(harness)
|
||||
.post('/auth/sso/complete')
|
||||
.body({code: createUniqueEmail(prefix), state: start.state})
|
||||
.executeRaw();
|
||||
};
|
||||
|
||||
const failCreateAfterTheUserRowIsWritten = () => {
|
||||
const create = UserRepository.prototype.create;
|
||||
vi.spyOn(UserRepository.prototype, 'create').mockImplementationOnce(async function (
|
||||
this: UserRepository,
|
||||
row: UserRow,
|
||||
) {
|
||||
await create.call(this, row);
|
||||
throw new Error('the user indexes could not be written after the user row');
|
||||
});
|
||||
};
|
||||
|
||||
const failAfterThePendingApprovalIsStored = () => {
|
||||
const addPendingRegistration = InstanceConfigRepository.prototype.addPendingRegistration;
|
||||
vi.spyOn(InstanceConfigRepository.prototype, 'addPendingRegistration').mockImplementationOnce(async function (
|
||||
this: InstanceConfigRepository,
|
||||
entry: Parameters<InstanceConfigRepository['addPendingRegistration']>[0],
|
||||
) {
|
||||
await addPendingRegistration.call(this, entry);
|
||||
throw new Error('the pending approval could not be published');
|
||||
});
|
||||
};
|
||||
|
||||
const expectOnePendingAccount = async () => {
|
||||
const pending = (await readAdminConfig()).registration.pending_registrations;
|
||||
expect(pending).toHaveLength(1);
|
||||
const account = await new UserRepository().findUnique(createUserID(BigInt(pending[0]!.user_id)));
|
||||
expect(account?.traits.has(REGISTRATION_PENDING_APPROVAL_TRAIT)).toBe(true);
|
||||
};
|
||||
|
||||
it('never lets concurrent signups through a capped registration URL exceed max_uses', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Capped',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: 2,
|
||||
approvalRequired: false,
|
||||
});
|
||||
|
||||
const attempts = await Promise.all(Array.from({length: 6}, (_, index) => register(`capped${index}`, code)));
|
||||
|
||||
const admitted = attempts.filter((attempt) => attempt.response.status === HTTP_STATUS.OK);
|
||||
const refused = attempts.filter((attempt) => attempt.response.status !== HTTP_STATUS.OK);
|
||||
expect(admitted).toHaveLength(2);
|
||||
for (const attempt of refused) {
|
||||
expect(attempt.response.status).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(attempt.json.code).toBe(APIErrorCodes.REGISTRATION_URL_INVALID);
|
||||
}
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored?.use_count).toBe(2);
|
||||
expect(admitted.map((attempt) => attempt.json.user_id)).toContain(stored?.last_used_by_user_id);
|
||||
});
|
||||
|
||||
it('admits exactly max_uses when 120 signups race through a registration URL capped at 40', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Capped at 40',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: 40,
|
||||
approvalRequired: false,
|
||||
});
|
||||
const registerUntilDecided = async (prefix: string) => {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
const result = await register(`${prefix}r${attempt}`, code);
|
||||
if (result.response.status !== HTTP_STATUS.SERVICE_UNAVAILABLE) return result;
|
||||
}
|
||||
throw new Error('a signup never reached a decision');
|
||||
};
|
||||
|
||||
const attempts = await Promise.all(Array.from({length: 120}, (_, index) => registerUntilDecided(`surge${index}`)));
|
||||
|
||||
const admitted = attempts.filter((attempt) => attempt.response.status === HTTP_STATUS.OK);
|
||||
expect(admitted).toHaveLength(40);
|
||||
for (const attempt of attempts.filter((entry) => entry.response.status !== HTTP_STATUS.OK)) {
|
||||
expect(attempt.response.status).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(attempt.json.code).toBe(APIErrorCodes.REGISTRATION_URL_INVALID);
|
||||
}
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored?.use_count).toBe(40);
|
||||
});
|
||||
|
||||
it('counts every concurrent signup through an uncapped registration URL', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Uncapped',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: null,
|
||||
approvalRequired: false,
|
||||
});
|
||||
|
||||
const attempts = await Promise.all(Array.from({length: 5}, (_, index) => register(`uncapped${index}`, code)));
|
||||
|
||||
expect(attempts.map((attempt) => attempt.response.status)).toEqual(Array(5).fill(HTTP_STATUS.OK));
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored?.use_count).toBe(5);
|
||||
});
|
||||
|
||||
it('gives the seat and the pending entry back when the signup failed before the account was created', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Single use',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: 1,
|
||||
approvalRequired: true,
|
||||
});
|
||||
failAfterThePendingApprovalIsStored();
|
||||
|
||||
const failed = await register('seatreleased', code);
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
const withdrawn = await readAdminConfig();
|
||||
expect(withdrawn.registration.pending_registrations).toEqual([]);
|
||||
expect(withdrawn.registration.urls.find((url) => url.id === registrationUrl.id)?.use_count).toBe(0);
|
||||
|
||||
const retried = await register('seatreleasedretry', code);
|
||||
|
||||
expect(retried.response.status).toBe(HTTP_STATUS.OK);
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored).toMatchObject({use_count: 1, last_used_by_user_id: retried.json.user_id});
|
||||
});
|
||||
|
||||
it('keeps the seat when the account create itself failed, because the row may still have landed', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Single use',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: 1,
|
||||
approvalRequired: false,
|
||||
});
|
||||
vi.spyOn(UserRepository.prototype, 'create').mockRejectedValueOnce(new Error('the user row write failed'));
|
||||
|
||||
const failed = await register('seatkeptoncreate', code);
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
const second = await register('seatkeptcreate2', code);
|
||||
|
||||
expect(second.response.status).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(second.json.code).toBe(APIErrorCodes.REGISTRATION_URL_INVALID);
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored?.use_count).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the seat of an account whose row was written before its creation failed', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const {code, registrationUrl} = await repository.createRegistrationUrl({
|
||||
label: 'Single use',
|
||||
createdByUserId: '1',
|
||||
expiresAt: null,
|
||||
maxUses: 1,
|
||||
approvalRequired: false,
|
||||
});
|
||||
failCreateAfterTheUserRowIsWritten();
|
||||
|
||||
const failed = await register('seatkept', code);
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
const second = await register('seatkeptsecond', code);
|
||||
|
||||
expect(second.response.status).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(second.json.code).toBe(APIErrorCodes.REGISTRATION_URL_INVALID);
|
||||
const stored = (await readAdminConfig()).registration.urls.find((url) => url.id === registrationUrl.id);
|
||||
expect(stored?.use_count).toBe(1);
|
||||
});
|
||||
|
||||
it('honours the use count and cap already stored on a registration URL', async () => {
|
||||
const repository = getInstanceConfigRepository();
|
||||
await repository.setRegistrationConfig({mode: 'closed', admin_registration_urls_enabled: true});
|
||||
const id = 'b3c4f0b2-8a6e-4c41-9f55-3f0c2a7d1e90';
|
||||
await repository.setConfig(
|
||||
REGISTRATION_URLS_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id,
|
||||
label: 'Issued earlier',
|
||||
code_hash: createHash('sha256').update(id).digest('hex'),
|
||||
created_by_user_id: '1400000000000000001',
|
||||
created_at: '2026-09-01T00:00:00.000Z',
|
||||
expires_at: null,
|
||||
max_uses: 2,
|
||||
use_count: 1,
|
||||
revoked_at: null,
|
||||
approval_required: false,
|
||||
last_used_at: '2026-09-02T00:00:00.000Z',
|
||||
last_used_by_user_id: '1400000000000000002',
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const before = (await readAdminConfig()).registration.urls.find((url) => url.id === id);
|
||||
expect(before).toMatchObject({use_count: 1, max_uses: 2, last_used_by_user_id: '1400000000000000002'});
|
||||
|
||||
const first = await register('storedinvite', id);
|
||||
expect(first.response.status).toBe(HTTP_STATUS.OK);
|
||||
const second = await register('storedinviteagain', id);
|
||||
expect(second.response.status).toBe(HTTP_STATUS.BAD_REQUEST);
|
||||
expect(second.json.code).toBe(APIErrorCodes.REGISTRATION_URL_INVALID);
|
||||
|
||||
const after = (await readAdminConfig()).registration.urls.find((url) => url.id === id);
|
||||
expect(after).toMatchObject({use_count: 2, max_uses: 2, last_used_by_user_id: first.json.user_id});
|
||||
});
|
||||
|
||||
it('keeps every pending approval when approval-mode signups race', async () => {
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
|
||||
const attempts = await Promise.all(Array.from({length: 5}, (_, index) => register(`pending${index}`)));
|
||||
|
||||
expect(attempts.map((attempt) => attempt.json.registration_pending_approval)).toEqual(Array(5).fill(true));
|
||||
const pending = (await readAdminConfig()).registration.pending_registrations.map((entry) => entry.user_id);
|
||||
expect(pending.toSorted()).toEqual(attempts.map((attempt) => attempt.json.user_id).toSorted());
|
||||
});
|
||||
|
||||
it('lists an approval-mode account whose signup failed after the account was created', async () => {
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
vi.spyOn(UserRepository.prototype, 'createAuthorizedIp').mockRejectedValueOnce(
|
||||
new Error('the authorized IP write failed'),
|
||||
);
|
||||
|
||||
const failed = await register('pendingstranded');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
await expectOnePendingAccount();
|
||||
});
|
||||
|
||||
it('lists an approval-mode account whose row was written before its creation failed', async () => {
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
failCreateAfterTheUserRowIsWritten();
|
||||
|
||||
const failed = await register('pendingrowwritten');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
await expectOnePendingAccount();
|
||||
});
|
||||
|
||||
it('keeps the pending approval of an approval-mode signup whose account create failed', async () => {
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
vi.spyOn(UserRepository.prototype, 'create').mockRejectedValueOnce(new Error('the user row write failed'));
|
||||
|
||||
const failed = await register('pendingkept');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
expect((await readAdminConfig()).registration.pending_registrations).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('lists no pending approval for an approval-mode signup that failed before the account was created', async () => {
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
failAfterThePendingApprovalIsStored();
|
||||
|
||||
const failed = await register('pendingnever');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
expect((await readAdminConfig()).registration.pending_registrations).toEqual([]);
|
||||
});
|
||||
|
||||
it('lists an SSO account provisioned in approval mode whose provisioning failed after the account was created', async () => {
|
||||
await enableSso(harness, admin.token, {enforced: false});
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
vi.spyOn(UserRepository.prototype, 'upsertSettings').mockRejectedValueOnce(new Error('the settings write failed'));
|
||||
|
||||
const failed = await completeSso('ssopendingstranded');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
await expectOnePendingAccount();
|
||||
});
|
||||
|
||||
it('lists an SSO account provisioned in approval mode whose row was written before its creation failed', async () => {
|
||||
await enableSso(harness, admin.token, {enforced: false});
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
failCreateAfterTheUserRowIsWritten();
|
||||
|
||||
const failed = await completeSso('ssopendingrowwritten');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
await expectOnePendingAccount();
|
||||
});
|
||||
|
||||
it('keeps the pending approval of an SSO signup in approval mode whose account create failed', async () => {
|
||||
await enableSso(harness, admin.token, {enforced: false});
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
vi.spyOn(UserRepository.prototype, 'create').mockRejectedValueOnce(new Error('the user row write failed'));
|
||||
|
||||
const failed = await completeSso('ssopendingkept');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
expect((await readAdminConfig()).registration.pending_registrations).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('lists no pending approval for an SSO signup in approval mode that failed before the account was created', async () => {
|
||||
await enableSso(harness, admin.token, {enforced: false});
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
failAfterThePendingApprovalIsStored();
|
||||
|
||||
const failed = await completeSso('ssopendingnever');
|
||||
|
||||
expect(failed.response.status).toBe(HTTP_STATUS.INTERNAL_SERVER_ERROR);
|
||||
expect((await readAdminConfig()).registration.pending_registrations).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps a stored pending approval listed until an admin decides it', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await getInstanceConfigRepository().setConfig(
|
||||
REGISTRATION_PENDING_APPROVALS_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
user_id: account.userId,
|
||||
username: 'stored_pending',
|
||||
discriminator: 1,
|
||||
global_name: null,
|
||||
email: account.email,
|
||||
requested_at: '2026-09-01T00:00:00.000Z',
|
||||
registration_url_id: null,
|
||||
client_ip: '127.0.0.1',
|
||||
},
|
||||
]),
|
||||
);
|
||||
await getInstanceConfigRepository().setRegistrationConfig({mode: 'approval'});
|
||||
const fresh = await register('pendingafter');
|
||||
|
||||
const listed = (await readAdminConfig()).registration.pending_registrations.map((entry) => entry.user_id);
|
||||
expect(listed.toSorted()).toEqual([account.userId, fresh.json.user_id].toSorted());
|
||||
|
||||
const decided = await createBuilder<InstanceConfigResponse>(harness, admin.token)
|
||||
.patch(`/admin/instance/pending-registrations/${account.userId}`)
|
||||
.body({status: 'approved'})
|
||||
.expect(HTTP_STATUS.OK)
|
||||
.execute();
|
||||
|
||||
expect(decided.registration.pending_registrations.map((entry) => entry.user_id)).toEqual([fresh.json.user_id]);
|
||||
expect(
|
||||
JSON.parse(
|
||||
(await getInstanceConfigRepository().getConfig(REGISTRATION_PENDING_APPROVALS_KEY)) ?? 'null',
|
||||
) as Array<{user_id: string}>,
|
||||
).toEqual([expect.objectContaining({user_id: fresh.json.user_id})]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {createChannelID, createUserID, type UserID} from '@app/api/BrandedTypes';
|
||||
import type {IChannelRepository} from '@app/api/channel/IChannelRepository';
|
||||
import {CallService} from '@app/api/channel/services/CallService';
|
||||
import type {IGuildRepositoryAggregate} from '@app/api/guild/repositories/IGuildRepositoryAggregate';
|
||||
import type {CallCaller, CallData, IGatewayService} from '@app/api/infrastructure/IGatewayService';
|
||||
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
|
||||
import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
|
||||
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
|
||||
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
|
||||
import type {Channel} from '@app/api/models/Channel';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import type {ReadStateService} from '@app/api/read_state/ReadStateService';
|
||||
import type {IUserRepository} from '@app/api/user/IUserRepository';
|
||||
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
|
||||
import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
const CALLER_ID = createUserID(1n);
|
||||
const RECIPIENT_ID = createUserID(2n);
|
||||
const CHANNEL_ID = createChannelID(12n);
|
||||
|
||||
interface CallerOverrides {
|
||||
username?: string;
|
||||
globalName?: string | null;
|
||||
avatar?: string | null;
|
||||
nickname?: string;
|
||||
userRowMissing?: boolean;
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
service: CallService;
|
||||
created: Array<CallCaller | undefined>;
|
||||
rung: Array<CallCaller | undefined>;
|
||||
}
|
||||
|
||||
const EXISTING_CALL: CallData = {
|
||||
channel_id: CHANNEL_ID.toString(),
|
||||
message_id: '99',
|
||||
region: 'automatic',
|
||||
ringing: [],
|
||||
recipients: [CALLER_ID.toString(), RECIPIENT_ID.toString()],
|
||||
voice_states: [],
|
||||
};
|
||||
|
||||
function harness(overrides: CallerOverrides, existingCall: CallData | null): Harness {
|
||||
const username = overrides.username ?? 'elias';
|
||||
const globalName = overrides.globalName === undefined ? 'Elias' : overrides.globalName;
|
||||
const avatar = overrides.avatar === undefined ? 'a1b2c3d4' : overrides.avatar;
|
||||
const nicknames = new Map<string, string>();
|
||||
if (overrides.nickname !== undefined) {
|
||||
nicknames.set(CALLER_ID.toString(), overrides.nickname);
|
||||
}
|
||||
const channel = {
|
||||
id: CHANNEL_ID,
|
||||
type: ChannelTypes.GROUP_DM,
|
||||
recipientIds: new Set<UserID>([CALLER_ID, RECIPIENT_ID]),
|
||||
nicknames,
|
||||
} as unknown as Channel;
|
||||
const created: Array<CallCaller | undefined> = [];
|
||||
const rung: Array<CallCaller | undefined> = [];
|
||||
const channelRepository = {
|
||||
findUnique: async () => channel,
|
||||
upsertMessage: async () => {},
|
||||
getMessage: async () => null,
|
||||
} as unknown as IChannelRepository;
|
||||
const userRepository = {
|
||||
findUnique: async () => (overrides.userRowMissing ? null : ({...callerUser(username, globalName, avatar)} as User)),
|
||||
listUsers: async () => [],
|
||||
findSettings: async () => null,
|
||||
isDmChannelOpen: async () => true,
|
||||
} as unknown as IUserRepository;
|
||||
const gatewayService = {
|
||||
getCall: async () => existingCall,
|
||||
createCall: async (
|
||||
_channelId: unknown,
|
||||
_messageId: string,
|
||||
_region: string,
|
||||
_ringing: Array<string>,
|
||||
_recipients: Array<string>,
|
||||
caller?: CallCaller,
|
||||
) => {
|
||||
created.push(caller);
|
||||
return EXISTING_CALL;
|
||||
},
|
||||
ringCallRecipients: async (_channelId: unknown, _recipients: Array<string>, caller?: CallCaller) => {
|
||||
rung.push(caller);
|
||||
return true;
|
||||
},
|
||||
} as unknown as IGatewayService;
|
||||
const userCacheService = {
|
||||
getUserPartialResponse: async (): Promise<UserPartialResponse> =>
|
||||
({
|
||||
id: CALLER_ID.toString(),
|
||||
username,
|
||||
discriminator: '0001',
|
||||
global_name: globalName,
|
||||
avatar,
|
||||
avatar_color: null,
|
||||
flags: 0,
|
||||
}) as unknown as UserPartialResponse,
|
||||
} as unknown as UserCacheService;
|
||||
const snowflakeService = {
|
||||
generateForChannel: async () => 7777n,
|
||||
} as unknown as ISnowflakeService;
|
||||
const readStateService = {
|
||||
ackMessage: async () => {},
|
||||
bulkIncrementMentionCounts: async () => {},
|
||||
} as unknown as ReadStateService;
|
||||
const service = new CallService(
|
||||
channelRepository,
|
||||
userRepository,
|
||||
{} as unknown as IGuildRepositoryAggregate,
|
||||
gatewayService,
|
||||
userCacheService,
|
||||
snowflakeService,
|
||||
readStateService,
|
||||
null,
|
||||
{} as unknown as IVoiceRoomStore,
|
||||
);
|
||||
return {service, created, rung};
|
||||
}
|
||||
|
||||
function callerUser(username: string, globalName: string | null, avatar: string | null): Partial<User> {
|
||||
return {
|
||||
id: CALLER_ID,
|
||||
username,
|
||||
globalName,
|
||||
avatarHash: avatar,
|
||||
isBot: false,
|
||||
};
|
||||
}
|
||||
|
||||
const requestCache = {
|
||||
userPartials: new Map(),
|
||||
} as unknown as RequestCache;
|
||||
|
||||
describe('CallService caller identity', () => {
|
||||
let harnessState: Harness;
|
||||
|
||||
const createCall = (overrides: CallerOverrides = {}) => {
|
||||
harnessState = harness(overrides, null);
|
||||
return harnessState.service.createOrGetCall({
|
||||
userId: CALLER_ID,
|
||||
channelId: CHANNEL_ID,
|
||||
ringing: [RECIPIENT_ID],
|
||||
requestCache,
|
||||
});
|
||||
};
|
||||
|
||||
const ringExistingCall = (overrides: CallerOverrides = {}) => {
|
||||
harnessState = harness(overrides, EXISTING_CALL);
|
||||
return harnessState.service.ringCallRecipients({
|
||||
userId: CALLER_ID,
|
||||
channelId: CHANNEL_ID,
|
||||
requestCache,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
requestCache.userPartials.clear();
|
||||
});
|
||||
|
||||
it('sends the caller id, display name and avatar hash to createCall', async () => {
|
||||
await createCall();
|
||||
expect(harnessState.created).toEqual([{id: '1', name: 'Elias', avatar: 'a1b2c3d4'}]);
|
||||
});
|
||||
|
||||
it('prefers the group dm nickname over the global name on createCall', async () => {
|
||||
await createCall({nickname: 'Eli'});
|
||||
expect(harnessState.created[0]?.name).toBe('Eli');
|
||||
});
|
||||
|
||||
it('falls back to the username when the caller has no nickname and no global name', async () => {
|
||||
await createCall({globalName: null});
|
||||
expect(harnessState.created[0]?.name).toBe('elias');
|
||||
});
|
||||
|
||||
it('sends a null avatar when the caller has no custom avatar', async () => {
|
||||
await createCall({avatar: null});
|
||||
expect(harnessState.created[0]).toEqual({id: '1', name: 'Elias', avatar: null});
|
||||
});
|
||||
|
||||
it('sends no caller at all when the caller user row is gone', async () => {
|
||||
await createCall({userRowMissing: true});
|
||||
expect(harnessState.created).toEqual([undefined]);
|
||||
});
|
||||
|
||||
it('sends the caller id, display name and avatar hash to ringCallRecipients', async () => {
|
||||
await ringExistingCall();
|
||||
expect(harnessState.rung).toEqual([{id: '1', name: 'Elias', avatar: 'a1b2c3d4'}]);
|
||||
});
|
||||
|
||||
it('prefers the group dm nickname over the global name on ringCallRecipients', async () => {
|
||||
await ringExistingCall({nickname: 'Eli'});
|
||||
expect(harnessState.rung[0]?.name).toBe('Eli');
|
||||
});
|
||||
|
||||
it('falls back to the username on ringCallRecipients', async () => {
|
||||
await ringExistingCall({globalName: null});
|
||||
expect(harnessState.rung[0]?.name).toBe('elias');
|
||||
});
|
||||
|
||||
it('resolves the caller on the ring branch and not on the create branch', async () => {
|
||||
await ringExistingCall();
|
||||
expect(harnessState.created).toEqual([]);
|
||||
expect(harnessState.rung).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService'
|
||||
import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
|
||||
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
|
||||
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
|
||||
import type {Channel} from '@app/api/models/Channel';
|
||||
import type {ReadStateService} from '@app/api/read_state/ReadStateService';
|
||||
import type {IUserRepository} from '@app/api/user/IUserRepository';
|
||||
import type {VoiceAccessContext, VoiceAvailabilityService} from '@app/api/voice/VoiceAvailabilityService';
|
||||
@@ -208,14 +209,26 @@ export class CallService {
|
||||
has_reaction: false,
|
||||
version: 1,
|
||||
});
|
||||
const author = await this.userRepository.findUnique(userId);
|
||||
const call = await this.gatewayService.createCall(
|
||||
channelId,
|
||||
messageId.toString(),
|
||||
selectedRegion,
|
||||
ringing.map((id) => id.toString()),
|
||||
allRecipients.map((id) => id.toString()),
|
||||
author
|
||||
? {
|
||||
id: userId.toString(),
|
||||
name: this.resolveCallerName({
|
||||
channel,
|
||||
userId,
|
||||
globalName: author.globalName,
|
||||
username: author.username,
|
||||
}),
|
||||
avatar: author.avatarHash,
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
const author = await this.userRepository.findUnique(userId);
|
||||
await incrementDmMentionCounts({
|
||||
readStateService: this.readStateService,
|
||||
userRepository: this.userRepository,
|
||||
@@ -390,13 +403,45 @@ export class CallService {
|
||||
longitude,
|
||||
});
|
||||
} else {
|
||||
const caller = await this.userCacheService.getUserPartialResponse(userId, requestCache);
|
||||
await this.gatewayService.ringCallRecipients(
|
||||
channelId,
|
||||
recipientsToRing.map((id) => id.toString()),
|
||||
{
|
||||
id: userId.toString(),
|
||||
name: this.resolveCallerName({
|
||||
channel,
|
||||
userId,
|
||||
globalName: caller.global_name,
|
||||
username: caller.username,
|
||||
}),
|
||||
avatar: caller.avatar,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private resolveCallerName({
|
||||
channel,
|
||||
userId,
|
||||
globalName,
|
||||
username,
|
||||
}: {
|
||||
channel: Channel;
|
||||
userId: UserID;
|
||||
globalName: string | null;
|
||||
username: string;
|
||||
}): string {
|
||||
const nickname = channel.nicknames.get(userId.toString());
|
||||
if (nickname) {
|
||||
return nickname;
|
||||
}
|
||||
if (globalName) {
|
||||
return globalName;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
async stopRingingCallRecipients({
|
||||
userId,
|
||||
channelId,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import type {AttachmentID, ChannelID} from '@app/api/BrandedTypes';
|
||||
import type {AttachmentRequestData} from '@app/api/channel/AttachmentDTOs';
|
||||
import type {RichEmbedMediaWithMetadata} from '@app/api/channel/EmbedTypes';
|
||||
import {makeAttachmentCdnUrl} from '@app/api/channel/services/message/MessageHelpers';
|
||||
import {getContentType, makeAttachmentCdnUrl} from '@app/api/channel/services/message/MessageHelpers';
|
||||
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
|
||||
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
|
||||
import type {RichEmbedRequest} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
|
||||
@@ -26,7 +26,10 @@ interface RichEmbedRequestWithMetadata extends Omit<RichEmbedRequest, 'image' |
|
||||
thumbnail?: RichEmbedMediaWithMetadata | null;
|
||||
}
|
||||
|
||||
const SUPPORTED_IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif']);
|
||||
function isEmbeddableMediaType(contentType: string): boolean {
|
||||
const normalized = contentType.toLowerCase();
|
||||
return normalized.startsWith('image/') || normalized.startsWith('video/');
|
||||
}
|
||||
|
||||
export class MessageEmbedAttachmentResolver {
|
||||
validateAttachmentReferences(params: {
|
||||
@@ -69,8 +72,7 @@ export class MessageEmbedAttachmentResolver {
|
||||
{filename},
|
||||
);
|
||||
}
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
if (!extension || !SUPPORTED_IMAGE_EXTENSIONS.has(extension)) {
|
||||
if (!isEmbeddableMediaType(getContentType(filename))) {
|
||||
throw InputValidationError.fromCode(
|
||||
`embeds[${embedIndex}].${field}`,
|
||||
ValidationErrorCodes.ATTACHMENT_MUST_BE_IMAGE,
|
||||
@@ -137,8 +139,7 @@ export class MessageEmbedAttachmentResolver {
|
||||
if (!attachmentData) {
|
||||
throw InputValidationError.fromCode(field, ValidationErrorCodes.REFERENCED_ATTACHMENT_NOT_FOUND, {filename});
|
||||
}
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
if (!extension || !SUPPORTED_IMAGE_EXTENSIONS.has(extension)) {
|
||||
if (!isEmbeddableMediaType(attachmentData.metadata.content_type)) {
|
||||
throw InputValidationError.fromCode(field, ValidationErrorCodes.ATTACHMENT_MUST_BE_IMAGE, {filename});
|
||||
}
|
||||
return attachmentData;
|
||||
|
||||
@@ -252,9 +252,7 @@ export class MessageValidationService {
|
||||
const isAuthor = message.authorId === userId;
|
||||
if (!guild) return isAuthor;
|
||||
if (isAuthor) return true;
|
||||
const canManageMessages =
|
||||
(await hasPermission(Permissions.SEND_MESSAGES)) && (await hasPermission(Permissions.MANAGE_MESSAGES));
|
||||
return canManageMessages;
|
||||
return hasPermission(Permissions.MANAGE_MESSAGES);
|
||||
}
|
||||
|
||||
private validateVoiceMessageConstraints(
|
||||
|
||||
@@ -512,6 +512,34 @@ describe('Embed Attachment URL Resolution', () => {
|
||||
expect(json.embeds).toHaveLength(1);
|
||||
expect(json.embeds![0].image?.url).not.toContain('attachment://');
|
||||
});
|
||||
it('should accept image and video attachments beyond the legacy image extensions', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const guild = await createGuild(harness, account.token, 'Media Type Guild');
|
||||
const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
|
||||
const channelId = guild.system_channel_id ?? channel.id;
|
||||
const payload = {
|
||||
content: 'Test with jxl and mp4 embed media',
|
||||
attachments: [
|
||||
{id: 0, filename: 'photo.jxl'},
|
||||
{id: 1, filename: 'clip.mp4'},
|
||||
],
|
||||
embeds: [
|
||||
{
|
||||
title: 'Media Embed',
|
||||
image: {url: 'attachment://clip.mp4'},
|
||||
thumbnail: {url: 'attachment://photo.jxl'},
|
||||
},
|
||||
],
|
||||
};
|
||||
const {response, json} = await sendMessageWithAttachments(harness, account.token, channelId, payload, [
|
||||
{index: 0, filename: 'photo.jxl', data: Buffer.from('jxl bytes')},
|
||||
{index: 1, filename: 'clip.mp4', data: Buffer.from('mp4 bytes')},
|
||||
]);
|
||||
expect(response.status).toBe(200);
|
||||
expect(json.embeds).toHaveLength(1);
|
||||
expect(json.embeds![0].image?.url).not.toContain('attachment://');
|
||||
expect(json.embeds![0].thumbnail?.url).not.toContain('attachment://');
|
||||
});
|
||||
});
|
||||
describe('Multiple Embeds and Files', () => {
|
||||
it('should handle multiple embeds with different URL types', async () => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {
|
||||
createPermissionOverwrite,
|
||||
sendChannelMessage,
|
||||
setupTestGuildWithMembers,
|
||||
} from '@app/api/channel/tests/ChannelTestUtils';
|
||||
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder} from '@app/api/test/TestRequestBuilder';
|
||||
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
|
||||
import {afterAll, beforeAll, beforeEach, describe, it} from 'vitest';
|
||||
|
||||
describe('Message delete permissions', () => {
|
||||
let harness: ApiTestHarness;
|
||||
|
||||
beforeAll(async () => {
|
||||
harness = await createApiTestHarness();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await harness.reset();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await harness?.shutdown();
|
||||
});
|
||||
|
||||
it('lets a member with MANAGE_MESSAGES but without SEND_MESSAGES delete another member message', async () => {
|
||||
const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 2);
|
||||
const [author, moderator] = members as [TestAccount, TestAccount];
|
||||
const message = await sendChannelMessage(harness, author.token, systemChannel.id, 'delete me');
|
||||
await createPermissionOverwrite(harness, owner.token, systemChannel.id, moderator.userId, {
|
||||
type: 1,
|
||||
allow: Permissions.MANAGE_MESSAGES.toString(),
|
||||
deny: Permissions.SEND_MESSAGES.toString(),
|
||||
});
|
||||
|
||||
await createBuilder(harness, moderator.token)
|
||||
.delete(`/channels/${systemChannel.id}/messages/${message.id}`)
|
||||
.expect(HTTP_STATUS.NO_CONTENT)
|
||||
.execute();
|
||||
|
||||
await createBuilder(harness, author.token)
|
||||
.get(`/channels/${systemChannel.id}/messages/${message.id}`)
|
||||
.expect(HTTP_STATUS.NOT_FOUND)
|
||||
.execute();
|
||||
});
|
||||
|
||||
it('refuses a member without MANAGE_MESSAGES deleting another member message', async () => {
|
||||
const {members, systemChannel} = await setupTestGuildWithMembers(harness, 2);
|
||||
const [author, other] = members as [TestAccount, TestAccount];
|
||||
const message = await sendChannelMessage(harness, author.token, systemChannel.id, 'keep me');
|
||||
|
||||
await createBuilder(harness, other.token)
|
||||
.delete(`/channels/${systemChannel.id}/messages/${message.id}`)
|
||||
.expect(HTTP_STATUS.FORBIDDEN, 'MISSING_PERMISSIONS')
|
||||
.execute();
|
||||
});
|
||||
});
|
||||
@@ -143,8 +143,6 @@ export interface APIConfig {
|
||||
donationProxyKey: string;
|
||||
};
|
||||
hosts: {
|
||||
invite: string;
|
||||
gift: string;
|
||||
marketing: string;
|
||||
unfurlIgnored: Array<string>;
|
||||
};
|
||||
@@ -338,6 +336,10 @@ export interface APIConfig {
|
||||
};
|
||||
abusePolicy: {
|
||||
inboundPhoneCountryCodes: Array<string>;
|
||||
phoneFlagging: {
|
||||
enabled: boolean;
|
||||
exemptCountryCodes: Array<string>;
|
||||
};
|
||||
phoneVerification: {
|
||||
inboundRequiredPrefixes: Array<string>;
|
||||
};
|
||||
|
||||
@@ -15,7 +15,12 @@ import type {GuildFolderIcon, MentionReplyPreference} from '@fluxer/constants/sr
|
||||
import type {types} from 'cassandra-driver';
|
||||
|
||||
type Nullish<T> = T | null;
|
||||
export type PushSubscriptionPlatform = 'web_push' | 'android_fcm' | 'ios_apns' | 'android_unified_push';
|
||||
export type PushSubscriptionPlatform =
|
||||
| 'web_push'
|
||||
| 'android_fcm'
|
||||
| 'ios_apns'
|
||||
| 'ios_apns_voip'
|
||||
| 'android_unified_push';
|
||||
|
||||
export interface UserRow {
|
||||
user_id: UserID;
|
||||
|
||||
@@ -8,7 +8,6 @@ import {RateLimitConfigs} from '@app/api/RateLimitConfig';
|
||||
import type {HonoApp} from '@app/api/types/HonoEnv';
|
||||
import {entityTagMatches} from '@app/api/utils/EntityTag';
|
||||
import {Headers as HttpHeaders} from '@fluxer/constants/src/Headers';
|
||||
import {resolveScreenShareDeliveryAssignment} from '@fluxer/schema/src/domains/admin/ScreenShareDeliverySchemas';
|
||||
import {resolveVoiceNoiseSuppressionAssignment} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';
|
||||
import {ExperimentAssignmentsResponse} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
|
||||
|
||||
@@ -29,10 +28,9 @@ export function ExperimentController(app: HonoApp) {
|
||||
}),
|
||||
async (ctx) => {
|
||||
const instanceConfigRepository = ctx.get('instanceConfigRepository');
|
||||
const [delivery, voiceConfig, screenShareConfig] = await Promise.all([
|
||||
const [delivery, voiceConfig] = await Promise.all([
|
||||
instanceConfigRepository.getExperimentDeliveryConfig(),
|
||||
instanceConfigRepository.getVoiceNoiseSuppressionConfig(),
|
||||
instanceConfigRepository.getScreenShareDeliveryConfig(),
|
||||
]);
|
||||
const userId = ctx.get('user').id.toString();
|
||||
const body: ExperimentAssignmentsResponse = {
|
||||
@@ -40,7 +38,6 @@ export function ExperimentController(app: HonoApp) {
|
||||
poll_jitter_percent: delivery.poll_jitter_percent,
|
||||
assignments: {
|
||||
voice_noise_suppression: resolveVoiceNoiseSuppressionAssignment(voiceConfig, userId),
|
||||
screen_share_delivery: resolveScreenShareDeliveryAssignment(screenShareConfig, userId),
|
||||
},
|
||||
};
|
||||
const etag = `"${createHash('sha256').update(JSON.stringify(body)).digest('hex')}"`;
|
||||
|
||||
@@ -6,10 +6,6 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
|
||||
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
|
||||
import {
|
||||
DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
INERT_SCREEN_SHARE_DELIVERY_ASSIGNMENT,
|
||||
} from '@fluxer/schema/src/domains/admin/ScreenShareDeliverySchemas';
|
||||
import {
|
||||
DEFAULT_VOICE_NOISE_SUPPRESSION_CONFIG,
|
||||
INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,
|
||||
@@ -19,7 +15,6 @@ import {
|
||||
DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,
|
||||
type ExperimentAssignmentsResponse,
|
||||
type ExperimentDeliveryConfigResponse,
|
||||
readScreenShareDeliveryAssignment,
|
||||
readVoiceNoiseSuppressionAssignment,
|
||||
} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
|
||||
@@ -56,7 +51,6 @@ describe('GET /experiments', () => {
|
||||
poll_jitter_percent: DEFAULT_EXPERIMENT_POLL_JITTER_PERCENT,
|
||||
assignments: {
|
||||
voice_noise_suppression: INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,
|
||||
screen_share_delivery: INERT_SCREEN_SHARE_DELIVERY_ASSIGNMENT,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -88,52 +82,6 @@ describe('GET /experiments', () => {
|
||||
expect(readVoiceNoiseSuppressionAssignment(body).enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('populates the screen share assignment key even when the rollout is disabled', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
|
||||
const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();
|
||||
|
||||
expect(Object.hasOwn(body.assignments, 'screen_share_delivery')).toBe(true);
|
||||
expect(readScreenShareDeliveryAssignment(body).enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('resolves the screen share caller through the allowlist', async () => {
|
||||
const targeted = await createTestAccount(harness);
|
||||
const untargeted = await createTestAccount(harness);
|
||||
await getInstanceConfigRepository().setScreenShareDeliveryConfig({
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
config_version: 4,
|
||||
rollout_basis_points: 0,
|
||||
included_user_ids: [targeted.userId],
|
||||
});
|
||||
|
||||
const targetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, targeted.token)
|
||||
.get(ENDPOINT)
|
||||
.execute();
|
||||
expect(targetedBody.assignments.screen_share_delivery).toEqual({enabled: true});
|
||||
|
||||
const untargetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, untargeted.token)
|
||||
.get(ENDPOINT)
|
||||
.execute();
|
||||
expect(untargetedBody.assignments.screen_share_delivery).toEqual({enabled: false});
|
||||
});
|
||||
|
||||
it('keeps the screen share exclusion ahead of a full rollout', async () => {
|
||||
const excluded = await createTestAccount(harness);
|
||||
await getInstanceConfigRepository().setScreenShareDeliveryConfig({
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
rollout_basis_points: 10000,
|
||||
included_user_ids: [excluded.userId],
|
||||
excluded_user_ids: [excluded.userId],
|
||||
});
|
||||
|
||||
const body = await createBuilder<ExperimentAssignmentsResponse>(harness, excluded.token).get(ENDPOINT).execute();
|
||||
|
||||
expect(body.assignments.screen_share_delivery).toEqual({enabled: false});
|
||||
});
|
||||
|
||||
it('serves the delivery cadence from the delivery config and not from the voice config', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await getInstanceConfigRepository().setExperimentDeliveryConfig({
|
||||
@@ -248,30 +196,6 @@ describe('GET /experiments', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('serves a fresh body once the screen share config changes', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
|
||||
const first = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
|
||||
.get(ENDPOINT)
|
||||
.executeWithResponse();
|
||||
const staleEtag = first.response.headers.get('etag') as string;
|
||||
|
||||
await getInstanceConfigRepository().setScreenShareDeliveryConfig({
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
config_version: 1,
|
||||
rollout_basis_points: 10000,
|
||||
});
|
||||
|
||||
const refreshed = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
|
||||
.get(ENDPOINT)
|
||||
.header('If-None-Match', staleEtag)
|
||||
.executeWithResponse();
|
||||
expect(refreshed.response.status).toBe(HTTP_STATUS.OK);
|
||||
expect(refreshed.response.headers.get('etag')).not.toBe(staleEtag);
|
||||
expect(refreshed.json?.assignments.screen_share_delivery).toEqual({enabled: true});
|
||||
});
|
||||
|
||||
it('serves a fresh body once the delivery config changes', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
|
||||
@@ -328,44 +252,6 @@ describe('GET /experiments', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('bumps the screen share config version on every admin update without the client sending one', async () => {
|
||||
const admin = await setUserACLs(harness, await createTestAccount(harness), [
|
||||
AdminACLs.AUTHENTICATE,
|
||||
AdminACLs.INSTANCE_CONFIG_VIEW,
|
||||
AdminACLs.INSTANCE_CONFIG_UPDATE,
|
||||
]);
|
||||
|
||||
const afterFirst = await createBuilder<{screen_share_delivery: {config_version: number; enabled: boolean}}>(
|
||||
harness,
|
||||
admin.token,
|
||||
)
|
||||
.patch('/admin/instance/config')
|
||||
.body({screen_share_delivery: {enabled: true, rollout_basis_points: 10000}})
|
||||
.execute();
|
||||
expect(afterFirst.screen_share_delivery).toMatchObject({config_version: 1, enabled: true});
|
||||
|
||||
const afterSecond = await createBuilder<{screen_share_delivery: {config_version: number; enabled: boolean}}>(
|
||||
harness,
|
||||
admin.token,
|
||||
)
|
||||
.patch('/admin/instance/config')
|
||||
.body({screen_share_delivery: {rollout_salt: 'screen-share-delivery-v2'}})
|
||||
.execute();
|
||||
expect(afterSecond.screen_share_delivery).toMatchObject({config_version: 2, enabled: true});
|
||||
|
||||
const afterEmpty = await createBuilder<{screen_share_delivery: {config_version: number; enabled: boolean}}>(
|
||||
harness,
|
||||
admin.token,
|
||||
)
|
||||
.patch('/admin/instance/config')
|
||||
.body({screen_share_delivery: {}})
|
||||
.execute();
|
||||
expect(afterEmpty.screen_share_delivery).toMatchObject({config_version: 2, enabled: true});
|
||||
|
||||
const body = await createBuilder<ExperimentAssignmentsResponse>(harness, admin.token).get(ENDPOINT).execute();
|
||||
expect(body.assignments.screen_share_delivery).toEqual({enabled: true});
|
||||
});
|
||||
|
||||
it('leaves the config version alone for an admin update that sets no field', async () => {
|
||||
const admin = await setUserACLs(harness, await createTestAccount(harness), [
|
||||
AdminACLs.AUTHENTICATE,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import {requireEmailVerified} from '@app/api/auth/EmailVerificationUtils';
|
||||
import type {GuildID, InviteCode, RoleID, UserID} from '@app/api/BrandedTypes';
|
||||
import {createChannelID, createRoleID} from '@app/api/BrandedTypes';
|
||||
import {Config} from '@app/api/Config';
|
||||
import type {ChannelService} from '@app/api/channel/services/ChannelService';
|
||||
import {assertMutableUserId} from '@app/api/constants/Core';
|
||||
import type {GuildMemberRow} from '@app/api/database/types/GuildTypes';
|
||||
@@ -421,6 +422,13 @@ export class GuildMemberOperationsService {
|
||||
memberCount: guild.memberCount,
|
||||
accountAgeMs: Date.now() - snowflakeToDate(BigInt(user.id)).getTime(),
|
||||
};
|
||||
if (
|
||||
!Config.abusePolicy.phoneFlagging.enabled &&
|
||||
(getEffectiveSuspiciousFlags(user) & PHONE_REQUIREMENT_FLAGS) === 0
|
||||
) {
|
||||
Logger.info(logContext, 'deferred_phone_gate.skipped_phone_flagging_disabled');
|
||||
return;
|
||||
}
|
||||
if (status !== 'ok') {
|
||||
const undeferredFlags = getEffectiveSuspiciousFlags({
|
||||
...user,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import {Config} from '@app/api/Config';
|
||||
import {GatewayRpcMethodError, GatewayRpcMethodErrorCodes} from '@app/api/infrastructure/GatewayRpcError';
|
||||
import type {IGatewayRpcTransport} from '@app/api/infrastructure/IGatewayRpcTransport';
|
||||
import type {CallData} from '@app/api/infrastructure/IGatewayService';
|
||||
import {type CallCaller, type CallData, callCallerRpcParams} from '@app/api/infrastructure/IGatewayService';
|
||||
import {NatsGatewayRpcTransport} from '@app/api/infrastructure/NatsGatewayRpcTransport';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import {NatsConnectionManager} from '@pkgs/nats/src/NatsConnectionManager';
|
||||
@@ -128,6 +128,7 @@ export class GatewayRpcClient {
|
||||
region: string,
|
||||
ringing: Array<string>,
|
||||
recipients: Array<string>,
|
||||
caller?: CallCaller,
|
||||
): Promise<CallData> {
|
||||
return this.call<CallData>('call.create', {
|
||||
channel_id: channelId,
|
||||
@@ -135,6 +136,7 @@ export class GatewayRpcClient {
|
||||
region,
|
||||
ringing,
|
||||
recipients,
|
||||
...callCallerRpcParams(caller),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -142,8 +144,8 @@ export class GatewayRpcClient {
|
||||
return this.call('call.update_region', {channel_id: channelId, region});
|
||||
}
|
||||
|
||||
async ringCallRecipients(channelId: string, recipients: Array<string>): Promise<boolean> {
|
||||
return this.call('call.ring', {channel_id: channelId, recipients});
|
||||
async ringCallRecipients(channelId: string, recipients: Array<string>, caller?: CallCaller): Promise<boolean> {
|
||||
return this.call('call.ring', {channel_id: channelId, recipients, ...callCallerRpcParams(caller)});
|
||||
}
|
||||
|
||||
async stopRingingCallRecipients(channelId: string, recipients: Array<string>): Promise<boolean> {
|
||||
|
||||
@@ -6,16 +6,18 @@ import {SYSTEM_USER_ID} from '@app/api/constants/Core';
|
||||
import type {GatewayDispatchEvent} from '@app/api/constants/Gateway';
|
||||
import {GatewayRpcClient} from '@app/api/infrastructure/GatewayRpcClient';
|
||||
import {GatewayRpcMethodError, GatewayRpcMethodErrorCodes} from '@app/api/infrastructure/GatewayRpcError';
|
||||
import type {
|
||||
CallData,
|
||||
GatewayChannelMention,
|
||||
GatewayGuildMemoryStats,
|
||||
GatewayMentionSources,
|
||||
GatewayMentionSourcesPage,
|
||||
GatewayNodeStats,
|
||||
GatewayVoiceStateCounts,
|
||||
GatewayVoiceStateEntry,
|
||||
GuildChannelAuthContext,
|
||||
import {
|
||||
type CallCaller,
|
||||
type CallData,
|
||||
callCallerRpcParams,
|
||||
type GatewayChannelMention,
|
||||
type GatewayGuildMemoryStats,
|
||||
type GatewayMentionSources,
|
||||
type GatewayMentionSourcesPage,
|
||||
type GatewayNodeStats,
|
||||
type GatewayVoiceStateCounts,
|
||||
type GatewayVoiceStateEntry,
|
||||
type GuildChannelAuthContext,
|
||||
} from '@app/api/infrastructure/IGatewayService';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
@@ -1695,6 +1697,7 @@ export class GatewayService {
|
||||
region: string,
|
||||
ringing: Array<string>,
|
||||
recipients: Array<string>,
|
||||
caller?: CallCaller,
|
||||
): Promise<CallData> {
|
||||
return this.call<CallData>('call.create', {
|
||||
channel_id: channelId.toString(),
|
||||
@@ -1702,6 +1705,7 @@ export class GatewayService {
|
||||
region,
|
||||
ringing,
|
||||
recipients,
|
||||
...callCallerRpcParams(caller),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1709,8 +1713,12 @@ export class GatewayService {
|
||||
return this.call<boolean>('call.update_region', {channel_id: channelId.toString(), region});
|
||||
}
|
||||
|
||||
async ringCallRecipients(channelId: ChannelID, recipients: Array<string>): Promise<boolean> {
|
||||
return this.call<boolean>('call.ring', {channel_id: channelId.toString(), recipients});
|
||||
async ringCallRecipients(channelId: ChannelID, recipients: Array<string>, caller?: CallCaller): Promise<boolean> {
|
||||
return this.call<boolean>('call.ring', {
|
||||
channel_id: channelId.toString(),
|
||||
recipients,
|
||||
...callCallerRpcParams(caller),
|
||||
});
|
||||
}
|
||||
|
||||
async stopRingingCallRecipients(channelId: ChannelID, recipients: Array<string>): Promise<boolean> {
|
||||
|
||||
@@ -24,6 +24,19 @@ export interface CallData {
|
||||
voice_states: Array<VoiceState>;
|
||||
}
|
||||
|
||||
export interface CallCaller {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export function callCallerRpcParams(caller: CallCaller | undefined): Record<string, unknown> {
|
||||
if (!caller) {
|
||||
return {};
|
||||
}
|
||||
return {caller_id: caller.id, caller_name: caller.name, caller_avatar: caller.avatar};
|
||||
}
|
||||
|
||||
export interface GatewayGuildMemoryStatsEntry {
|
||||
node_id: string;
|
||||
guild_id: string | null;
|
||||
@@ -381,11 +394,12 @@ export abstract class IGatewayService {
|
||||
region: string,
|
||||
ringing: Array<string>,
|
||||
recipients: Array<string>,
|
||||
caller?: CallCaller,
|
||||
): Promise<CallData>;
|
||||
|
||||
abstract updateCallRegion(channelId: ChannelID, region: string | null): Promise<boolean>;
|
||||
|
||||
abstract ringCallRecipients(channelId: ChannelID, recipients: Array<string>): Promise<boolean>;
|
||||
abstract ringCallRecipients(channelId: ChannelID, recipients: Array<string>, caller?: CallCaller): Promise<boolean>;
|
||||
|
||||
abstract stopRingingCallRecipients(channelId: ChannelID, recipients: Array<string>): Promise<boolean>;
|
||||
|
||||
|
||||
@@ -84,6 +84,41 @@ describe('stripNonJpegImageMetadataForUpload', () => {
|
||||
});
|
||||
});
|
||||
|
||||
function riffChunk(type: string, data: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(8 + data.length + (data.length & 1));
|
||||
out.set(textBytes(type), 0);
|
||||
new DataView(out.buffer).setUint32(4, data.length, true);
|
||||
out.set(data, 8);
|
||||
return out;
|
||||
}
|
||||
|
||||
function webp(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
|
||||
const body = concatBytes(chunks);
|
||||
const header = concatBytes([textBytes('RIFF'), new Uint8Array(4), textBytes('WEBP')]);
|
||||
new DataView(header.buffer).setUint32(4, 4 + body.length, true);
|
||||
return concatBytes([header, body]);
|
||||
}
|
||||
|
||||
describe('stripNonJpegImageMetadataForUpload for WebP', () => {
|
||||
it('drops EXIF and XMP chunks without re-encoding frames', async () => {
|
||||
const vp8x = new Uint8Array(10);
|
||||
vp8x[0] = 0x02 | 0x08 | 0x04;
|
||||
const anmf = riffChunk('ANMF', new Uint8Array([9, 8, 7]));
|
||||
const input = webp([
|
||||
riffChunk('VP8X', vp8x),
|
||||
riffChunk('ANIM', new Uint8Array(6)),
|
||||
anmf,
|
||||
riffChunk('EXIF', textBytes('GPS=1,2')),
|
||||
riffChunk('XMP ', textBytes('private metadata')),
|
||||
]);
|
||||
const stripped = await stripNonJpegImageMetadataForUpload(input, 'image/webp');
|
||||
const expectedVp8x = new Uint8Array(10);
|
||||
expectedVp8x[0] = 0x02;
|
||||
expect(stripped.contentType).toBe('image/webp');
|
||||
expect(stripped.body).toEqual(webp([riffChunk('VP8X', expectedVp8x), riffChunk('ANIM', new Uint8Array(6)), anmf]));
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildProcessedMediaObject', () => {
|
||||
it('leaves non-media objects for plain copy', async () => {
|
||||
await expect(buildProcessedMediaObject(textBytes('plain text'), 'text/plain')).resolves.toBeNull();
|
||||
|
||||
@@ -162,6 +162,8 @@ export async function stripNonJpegImageMetadataForUpload(
|
||||
contentType: normalizedContentType === 'image/apng' ? 'image/apng' : 'image/png',
|
||||
};
|
||||
}
|
||||
const strippedWebp = isWebp(data) ? stripWebpMetadataChunks(data) : null;
|
||||
if (strippedWebp) return {body: strippedWebp, contentType: 'image/webp'};
|
||||
const image = sharp(data, {animated: true});
|
||||
const metadata = await image.metadata();
|
||||
switch (metadata.format) {
|
||||
@@ -242,6 +244,50 @@ function stripPngMetadataChunks(data: Uint8Array): Uint8Array {
|
||||
return output;
|
||||
}
|
||||
|
||||
const WEBP_CHUNKS_TO_KEEP = new Set(['VP8 ', 'VP8L', 'VP8X', 'ALPH', 'ANIM', 'ANMF', 'ICCP']);
|
||||
const WEBP_VP8X_EXIF_FLAG = 0x08;
|
||||
const WEBP_VP8X_XMP_FLAG = 0x04;
|
||||
|
||||
function readFourCc(data: Uint8Array, offset: number): string {
|
||||
return String.fromCharCode(data[offset]!, data[offset + 1]!, data[offset + 2]!, data[offset + 3]!);
|
||||
}
|
||||
|
||||
function readU32LE(data: Uint8Array, offset: number): number {
|
||||
return (data[offset]! | (data[offset + 1]! << 8) | (data[offset + 2]! << 16) | (data[offset + 3]! << 24)) >>> 0;
|
||||
}
|
||||
|
||||
function isWebp(data: Uint8Array): boolean {
|
||||
return data.length >= 12 && readFourCc(data, 0) === 'RIFF' && readFourCc(data, 8) === 'WEBP';
|
||||
}
|
||||
|
||||
function stripWebpMetadataChunks(data: Uint8Array): Uint8Array | null {
|
||||
const riffEnd = Math.min(data.length, 8 + readU32LE(data, 4));
|
||||
const chunks: Array<Uint8Array> = [];
|
||||
let offset = 12;
|
||||
while (offset + 8 <= riffEnd) {
|
||||
const length = readU32LE(data, offset + 4);
|
||||
const chunkEnd = offset + 8 + length + (length & 1);
|
||||
if (offset + 8 + length > riffEnd) return null;
|
||||
const type = readFourCc(data, offset);
|
||||
if (WEBP_CHUNKS_TO_KEEP.has(type)) {
|
||||
const chunk = data.slice(offset, Math.min(chunkEnd, riffEnd));
|
||||
if (type === 'VP8X' && length > 0) chunk[8] = (chunk[8] ?? 0) & ~(WEBP_VP8X_EXIF_FLAG | WEBP_VP8X_XMP_FLAG);
|
||||
chunks.push(chunk);
|
||||
}
|
||||
offset = chunkEnd;
|
||||
}
|
||||
const bodyLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
||||
const output = new Uint8Array(12 + bodyLength);
|
||||
output.set(data.subarray(0, 12));
|
||||
new DataView(output.buffer).setUint32(4, 4 + bodyLength, true);
|
||||
let cursor = 12;
|
||||
for (const chunk of chunks) {
|
||||
output.set(chunk, cursor);
|
||||
cursor += chunk.length;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function imageExtensionForContentType(contentType: string): string {
|
||||
if (contentType.includes('svg')) return 'svg';
|
||||
if (contentType.includes('tiff')) return 'tiff';
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {createChannelID} from '@app/api/BrandedTypes';
|
||||
import {GatewayRpcClient} from '@app/api/infrastructure/GatewayRpcClient';
|
||||
import {GatewayService} from '@app/api/infrastructure/GatewayService';
|
||||
import type {IGatewayRpcTransport} from '@app/api/infrastructure/IGatewayRpcTransport';
|
||||
import {afterEach, describe, expect, it} from 'vitest';
|
||||
|
||||
const CHANNEL_ID = createChannelID(12n);
|
||||
|
||||
interface RecordedCall {
|
||||
method: string;
|
||||
params: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function recordingService(recorded: Array<RecordedCall>): GatewayService {
|
||||
const transport: IGatewayRpcTransport = {
|
||||
async call(method: string, params: Record<string, unknown>): Promise<unknown> {
|
||||
recorded.push({method, params});
|
||||
return null;
|
||||
},
|
||||
async destroy(): Promise<void> {},
|
||||
};
|
||||
GatewayRpcClient.createForTests(transport);
|
||||
return new GatewayService();
|
||||
}
|
||||
|
||||
describe('call rpc caller params', () => {
|
||||
afterEach(async () => {
|
||||
await GatewayRpcClient.resetForTests();
|
||||
});
|
||||
|
||||
it('sends the caller to call.create as caller_id, caller_name and caller_avatar', async () => {
|
||||
const recorded: Array<RecordedCall> = [];
|
||||
const service = recordingService(recorded);
|
||||
await service.createCall(CHANNEL_ID, '99', 'automatic', ['2'], ['1', '2'], {
|
||||
id: '1',
|
||||
name: 'Elias',
|
||||
avatar: 'a1b2c3d4',
|
||||
});
|
||||
expect(recorded).toHaveLength(1);
|
||||
expect(recorded[0].method).toBe('call.create');
|
||||
expect(recorded[0].params.caller_id).toBe('1');
|
||||
expect(recorded[0].params.caller_name).toBe('Elias');
|
||||
expect(recorded[0].params.caller_avatar).toBe('a1b2c3d4');
|
||||
});
|
||||
|
||||
it('sends the caller to call.ring as caller_id, caller_name and caller_avatar', async () => {
|
||||
const recorded: Array<RecordedCall> = [];
|
||||
const service = recordingService(recorded);
|
||||
await service.ringCallRecipients(CHANNEL_ID, ['2'], {id: '1', name: 'Elias', avatar: 'a1b2c3d4'});
|
||||
expect(recorded).toHaveLength(1);
|
||||
expect(recorded[0].method).toBe('call.ring');
|
||||
expect(recorded[0].params.caller_id).toBe('1');
|
||||
expect(recorded[0].params.caller_name).toBe('Elias');
|
||||
expect(recorded[0].params.caller_avatar).toBe('a1b2c3d4');
|
||||
});
|
||||
|
||||
it('sends caller_avatar as null when the caller has no avatar', async () => {
|
||||
const recorded: Array<RecordedCall> = [];
|
||||
const service = recordingService(recorded);
|
||||
await service.ringCallRecipients(CHANNEL_ID, ['2'], {id: '1', name: 'Elias', avatar: null});
|
||||
expect(recorded[0].params.caller_avatar).toBeNull();
|
||||
expect(Object.hasOwn(recorded[0].params, 'caller_avatar')).toBe(true);
|
||||
});
|
||||
|
||||
it('omits every caller key from call.create when no caller was resolved', async () => {
|
||||
const recorded: Array<RecordedCall> = [];
|
||||
const service = recordingService(recorded);
|
||||
await service.createCall(CHANNEL_ID, '99', 'automatic', ['2'], ['1', '2']);
|
||||
expect(recorded[0].params).toEqual({
|
||||
channel_id: '12',
|
||||
message_id: '99',
|
||||
region: 'automatic',
|
||||
ringing: ['2'],
|
||||
recipients: ['1', '2'],
|
||||
});
|
||||
});
|
||||
|
||||
it('omits every caller key from call.ring when no caller was resolved', async () => {
|
||||
const recorded: Array<RecordedCall> = [];
|
||||
const service = recordingService(recorded);
|
||||
await service.ringCallRecipients(CHANNEL_ID, ['2']);
|
||||
expect(recorded[0].params).toEqual({channel_id: '12', recipients: ['2']});
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,23 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {createServer} from 'node:net';
|
||||
import type {CassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
|
||||
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
|
||||
import type {PreparedQuery} from '@app/api/database/CassandraTypes';
|
||||
import {ensurePostgresKvSchema, PostgresKvQueryExecutor} from '@app/api/database/PostgresKvQueryExecutor';
|
||||
import {
|
||||
INSTANCE_CONFIG_REFRESH_CHANNEL,
|
||||
INSTANCE_CONFIG_WRITE_ATTEMPTS,
|
||||
InstanceConfigRepository,
|
||||
InstanceConfigWriteConflictError,
|
||||
type InstanceRegistrationConfig,
|
||||
} from '@app/api/instance/InstanceConfigRepository';
|
||||
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
|
||||
import {startDockerContainer} from '@app/api/test/DockerTestContainer';
|
||||
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
|
||||
import {MockKVProvider} from '@app/api/test/mocks/MockKVProvider';
|
||||
import {
|
||||
DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
type ScreenShareDeliveryConfig,
|
||||
} from '@fluxer/schema/src/domains/admin/ScreenShareDeliverySchemas';
|
||||
import {
|
||||
DEFAULT_VOICE_NOISE_SUPPRESSION_CONFIG,
|
||||
type VoiceNoiseSuppressionConfig,
|
||||
@@ -21,14 +26,25 @@ import {
|
||||
DEFAULT_EXPERIMENT_DELIVERY_CONFIG,
|
||||
type ExperimentDeliveryConfig,
|
||||
} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
|
||||
import {afterEach, describe, expect, it, vi} from 'vitest';
|
||||
import {
|
||||
getDefaultPostgresClient,
|
||||
type IPostgresClient,
|
||||
initPostgres,
|
||||
shutdownPostgres,
|
||||
} from '@pkgs/postgres/src/Client';
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
const VOICE_NOISE_SUPPRESSION_CONFIG_KEY = 'voice_noise_suppression_config';
|
||||
const SCREEN_SHARE_DELIVERY_CONFIG_KEY = 'screen_share_delivery_config';
|
||||
const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';
|
||||
const APP_PUBLIC_CONFIG_KEY = 'app_public_config';
|
||||
const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';
|
||||
const INSTANCE_INTEGRATIONS_CONFIG_KEY = 'instance_integrations_config';
|
||||
const REGISTRATION_CONFIG_KEY = 'registration_config';
|
||||
const REGISTRATION_URLS_KEY = 'registration_urls';
|
||||
const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';
|
||||
const POSTGRES_KV_TABLE = 'kv_instance_config_races';
|
||||
const POSTGRES_CONTAINER = `fluxer-instance-config-races-${process.pid.toString(36)}-${Date.now().toString(36)}`;
|
||||
const dockerAvailable = spawnSync('docker', ['version'], {stdio: 'ignore'}).status === 0;
|
||||
|
||||
class CountingInMemoryCassandraQueryExecutor extends InMemoryCassandraQueryExecutor {
|
||||
instanceConfigSelects = 0;
|
||||
@@ -335,70 +351,6 @@ describe('InstanceConfigRepository', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the default screen share delivery config when the key is absent', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
const kvProvider = new MockKVProvider();
|
||||
const repository = createRepository(kvProvider);
|
||||
|
||||
await expect(repository.getScreenShareDeliveryConfig()).resolves.toEqual(DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{name: 'unparseable text', stored: 'not-json'},
|
||||
{name: 'a json array', stored: '[]'},
|
||||
{name: 'out-of-range values', stored: '{"rollout_basis_points":99999}'},
|
||||
{name: 'a non-boolean enabled flag', stored: '{"enabled":"yes"}'},
|
||||
])('falls back to the default screen share delivery config for $name', async ({stored}) => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
const kvProvider = new MockKVProvider();
|
||||
const repository = createRepository(kvProvider);
|
||||
|
||||
await repository.setConfig(SCREEN_SHARE_DELIVERY_CONFIG_KEY, stored);
|
||||
|
||||
await expect(repository.getScreenShareDeliveryConfig()).resolves.toEqual(DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG);
|
||||
});
|
||||
|
||||
it('round-trips a stored screen share delivery config', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
const kvProvider = new MockKVProvider();
|
||||
const repository = createRepository(kvProvider);
|
||||
|
||||
const config: ScreenShareDeliveryConfig = {
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
config_version: 5,
|
||||
rollout_basis_points: 2500,
|
||||
rollout_salt: 'screen-share-delivery-v2',
|
||||
included_user_ids: ['1400000000000000001'],
|
||||
excluded_user_ids: ['1400000000000000002'],
|
||||
};
|
||||
await repository.setScreenShareDeliveryConfig(config);
|
||||
|
||||
await expect(repository.getScreenShareDeliveryConfig()).resolves.toEqual(config);
|
||||
});
|
||||
|
||||
it('fills newly added screen share delivery fields from the schema defaults', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
const kvProvider = new MockKVProvider();
|
||||
const repository = createRepository(kvProvider);
|
||||
|
||||
await repository.setConfig(
|
||||
SCREEN_SHARE_DELIVERY_CONFIG_KEY,
|
||||
JSON.stringify({enabled: true, config_version: 2, rollout_basis_points: 1000}),
|
||||
);
|
||||
|
||||
await expect(repository.getScreenShareDeliveryConfig()).resolves.toEqual({
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
config_version: 2,
|
||||
rollout_basis_points: 1000,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the default experiment delivery config when the key is absent', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
@@ -471,26 +423,6 @@ describe('InstanceConfigRepository', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('publishes a refresh so another repository observes the screen share delivery config', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
const kvProvider = new MockKVProvider();
|
||||
const reader = createRepository(kvProvider);
|
||||
const writer = createRepository(kvProvider);
|
||||
|
||||
await expect(reader.getScreenShareDeliveryConfig()).resolves.toEqual(DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG);
|
||||
|
||||
await writer.setScreenShareDeliveryConfig({
|
||||
...DEFAULT_SCREEN_SHARE_DELIVERY_CONFIG,
|
||||
enabled: true,
|
||||
config_version: 1,
|
||||
});
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
expect(await reader.getScreenShareDeliveryConfig()).toMatchObject({enabled: true, config_version: 1});
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the registration URL id as the admin-visible registration code', async () => {
|
||||
const executor = new CountingInMemoryCassandraQueryExecutor();
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
@@ -512,3 +444,466 @@ describe('InstanceConfigRepository', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
async function sleep(ms: number): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = createServer();
|
||||
server.on('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
if (typeof address === 'string' || address === null) {
|
||||
reject(new Error('no port'));
|
||||
return;
|
||||
}
|
||||
server.close(() => resolve(address.port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function describeConcurrentInstanceConfigWrites(prepareBase: () => Promise<CassandraQueryExecutorForTesting>): void {
|
||||
const pods: Array<InstanceConfigRepository> = [];
|
||||
let executor: InstanceConfigWriteRaceExecutor;
|
||||
|
||||
beforeEach(async () => {
|
||||
executor = new InstanceConfigWriteRaceExecutor(await prepareBase());
|
||||
setCassandraQueryExecutorForTesting(executor);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(pods.map((pod) => pod.shutdown()));
|
||||
pods.length = 0;
|
||||
});
|
||||
|
||||
function createPod(): InstanceConfigRepository {
|
||||
const pod = new InstanceConfigRepository(new MockKVProvider());
|
||||
pods.push(pod);
|
||||
return pod;
|
||||
}
|
||||
|
||||
async function readStoredRegistrationConfig(): Promise<unknown> {
|
||||
const raw = await executor.readDirectly(REGISTRATION_CONFIG_KEY);
|
||||
return raw === null ? null : JSON.parse(raw);
|
||||
}
|
||||
|
||||
it('applies two concurrent patches on top of each other instead of dropping one', async () => {
|
||||
const first = createPod();
|
||||
const second = createPod();
|
||||
await first.setRegistrationConfig({mode: 'open', admin_registration_urls_enabled: true});
|
||||
await second.getRegistrationConfig();
|
||||
executor.watch(REGISTRATION_CONFIG_KEY);
|
||||
executor.pauseWritesUntil(2);
|
||||
|
||||
await Promise.all([
|
||||
first.setRegistrationConfig({mode: 'closed'}),
|
||||
second.setRegistrationConfig({admin_registration_urls_enabled: false}),
|
||||
]);
|
||||
|
||||
expect(executor.events.filter((event) => event === 'write rejected')).toHaveLength(1);
|
||||
expect(executor.events.filter((event) => event === 'write')).toHaveLength(2);
|
||||
expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
|
||||
});
|
||||
|
||||
it('lets one of two concurrent first writes create the config and applies the other on top', async () => {
|
||||
const first = createPod();
|
||||
const second = createPod();
|
||||
await first.getRegistrationConfig();
|
||||
await second.getRegistrationConfig();
|
||||
executor.watch(REGISTRATION_CONFIG_KEY);
|
||||
executor.pauseWritesUntil(2);
|
||||
|
||||
await Promise.all([
|
||||
first.setRegistrationConfig({mode: 'closed'}),
|
||||
second.setRegistrationConfig({admin_registration_urls_enabled: false}),
|
||||
]);
|
||||
|
||||
expect(executor.events.filter((event) => event === 'write rejected')).toHaveLength(1);
|
||||
expect(executor.events.filter((event) => event === 'write')).toHaveLength(2);
|
||||
expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
|
||||
});
|
||||
|
||||
it('re-reads the database, not its stale cache, when a concurrent write lands between its read and its write', async () => {
|
||||
const stale = createPod();
|
||||
const other = createPod();
|
||||
await stale.setRegistrationConfig({mode: 'open', admin_registration_urls_enabled: true});
|
||||
await stale.getRegistrationConfig();
|
||||
await other.setRegistrationConfig({mode: 'approval'});
|
||||
expect(await stale.getRegistrationConfig()).toEqual({mode: 'open', admin_registration_urls_enabled: true});
|
||||
executor.watch(REGISTRATION_CONFIG_KEY);
|
||||
let competed = false;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
if (competed) return;
|
||||
competed = true;
|
||||
await executor.writeDirectly(
|
||||
REGISTRATION_CONFIG_KEY,
|
||||
JSON.stringify({mode: 'approval', admin_registration_urls_enabled: false}),
|
||||
);
|
||||
});
|
||||
|
||||
await stale.setRegistrationConfig({mode: 'closed'});
|
||||
|
||||
expect(executor.events).toEqual(['read', 'write rejected', 'read', 'write']);
|
||||
expect(await readStoredRegistrationConfig()).toEqual({mode: 'closed', admin_registration_urls_enabled: false});
|
||||
});
|
||||
|
||||
it('fails loudly and writes nothing once every attempt has lost the race', async () => {
|
||||
const pod = createPod();
|
||||
await pod.setRegistrationConfig({mode: 'open', admin_registration_urls_enabled: true});
|
||||
executor.watch(REGISTRATION_CONFIG_KEY);
|
||||
let competingWrites = 0;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
competingWrites++;
|
||||
await executor.writeDirectly(
|
||||
REGISTRATION_CONFIG_KEY,
|
||||
JSON.stringify({mode: 'approval', admin_registration_urls_enabled: competingWrites % 2 === 0}),
|
||||
);
|
||||
});
|
||||
|
||||
const write = pod.setRegistrationConfig({mode: 'closed'});
|
||||
|
||||
await expect(write).rejects.toBeInstanceOf(InstanceConfigWriteConflictError);
|
||||
await expect(write).rejects.toMatchObject({
|
||||
status: 409,
|
||||
code: 'CONFLICT',
|
||||
message: expect.stringContaining(REGISTRATION_CONFIG_KEY),
|
||||
});
|
||||
expect(executor.events.filter((event) => event === 'write rejected')).toHaveLength(INSTANCE_CONFIG_WRITE_ATTEMPTS);
|
||||
expect(executor.events).not.toContain('write');
|
||||
expect(await readStoredRegistrationConfig()).toEqual({
|
||||
mode: 'approval',
|
||||
admin_registration_urls_enabled: INSTANCE_CONFIG_WRITE_ATTEMPTS % 2 === 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a pending registration another pod added while this pod held a stale list', async () => {
|
||||
const first = createPod();
|
||||
const second = createPod();
|
||||
await first.getPendingRegistrations();
|
||||
await second.getPendingRegistrations();
|
||||
|
||||
await first.addPendingRegistration(pendingRegistration('1400000000000000011'));
|
||||
await second.addPendingRegistration(pendingRegistration('1400000000000000012'));
|
||||
|
||||
const listed = await createPod().getPendingRegistrations();
|
||||
expect(listed.map((entry) => entry.user_id)).toEqual(['1400000000000000011', '1400000000000000012']);
|
||||
});
|
||||
|
||||
it('keeps a pending registration another pod stored and removes it once decided', async () => {
|
||||
const pod = createPod();
|
||||
await executor.writeDirectly(
|
||||
REGISTRATION_PENDING_APPROVALS_KEY,
|
||||
JSON.stringify([pendingRegistration('1400000000000000021')]),
|
||||
);
|
||||
await pod.addPendingRegistration(pendingRegistration('1400000000000000022'));
|
||||
|
||||
expect((await createPod().getPendingRegistrations()).map((entry) => entry.user_id)).toEqual([
|
||||
'1400000000000000021',
|
||||
'1400000000000000022',
|
||||
]);
|
||||
|
||||
await pod.removePendingRegistration('1400000000000000021');
|
||||
await pod.removePendingRegistration('1400000000000000022');
|
||||
|
||||
expect(await createPod().getPendingRegistrations()).toEqual([]);
|
||||
expect(await executor.readDirectly(REGISTRATION_PENDING_APPROVALS_KEY)).toBe('[]');
|
||||
});
|
||||
|
||||
it('keeps a registration URL another pod created while this pod held a stale list', async () => {
|
||||
const first = createPod();
|
||||
const second = createPod();
|
||||
await first.getRegistrationUrls();
|
||||
await second.getRegistrationUrls();
|
||||
|
||||
const created = [
|
||||
await first.createRegistrationUrl(registrationUrlParams(null)),
|
||||
await second.createRegistrationUrl(registrationUrlParams(null)),
|
||||
];
|
||||
|
||||
const listed = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed.map((url) => url.id).toSorted()).toEqual(created.map((entry) => entry.registrationUrl.id).toSorted());
|
||||
});
|
||||
|
||||
it('refuses a registration URL another pod revoked while this pod held a stale list', async () => {
|
||||
const admin = createPod();
|
||||
const signup = createPod();
|
||||
const {code, registrationUrl} = await admin.createRegistrationUrl(registrationUrlParams(null));
|
||||
expect(await signup.resolveRegistrationUrlCode(code)).not.toBeNull();
|
||||
|
||||
await admin.revokeRegistrationUrl(registrationUrl.id);
|
||||
|
||||
await expect(signup.resolveRegistrationUrlCode(code)).resolves.toBeNull();
|
||||
await expect(signup.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000501')).resolves.toBeNull();
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed?.use_count).toBe(0);
|
||||
});
|
||||
|
||||
it('admits a registration URL another pod created while this pod held a stale list', async () => {
|
||||
const admin = createPod();
|
||||
const signup = createPod();
|
||||
await signup.getRegistrationUrls();
|
||||
|
||||
const {code, registrationUrl} = await admin.createRegistrationUrl(registrationUrlParams(1));
|
||||
|
||||
await expect(signup.resolveRegistrationUrlCode(code)).resolves.toMatchObject({
|
||||
id: registrationUrl.id,
|
||||
approval_required: false,
|
||||
});
|
||||
await expect(signup.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000601')).resolves.not.toBeNull();
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed?.use_count).toBe(1);
|
||||
});
|
||||
|
||||
it('never seats more signups than max_uses when pods claim the same registration URL at once', async () => {
|
||||
const pods = [createPod(), createPod(), createPod()];
|
||||
const {code} = await pods[0]!.createRegistrationUrl(registrationUrlParams(2));
|
||||
const registrationUrl = await pods[0]!.resolveRegistrationUrlCode(code);
|
||||
if (registrationUrl === null) throw new Error('registration URL did not resolve');
|
||||
|
||||
const claims = await Promise.all(
|
||||
Array.from({length: 6}, (_, index) =>
|
||||
pods[index % pods.length]!.claimRegistrationUrlUse(registrationUrl.id, `14000000000000001${index}0`),
|
||||
),
|
||||
);
|
||||
|
||||
expect(claims.filter((claim) => claim !== null)).toHaveLength(2);
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed?.use_count).toBe(2);
|
||||
await expect(createPod().resolveRegistrationUrlCode(code)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('refuses a claim whose retry finds the registration URL exhausted, rather than reporting the lost attempt', async () => {
|
||||
const pod = createPod();
|
||||
const {code, registrationUrl} = await pod.createRegistrationUrl(registrationUrlParams(1));
|
||||
expect(await pod.resolveRegistrationUrlCode(code)).not.toBeNull();
|
||||
executor.watch(REGISTRATION_URLS_KEY);
|
||||
let competed = false;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
if (competed) return;
|
||||
competed = true;
|
||||
const stored = JSON.parse((await executor.readDirectly(REGISTRATION_URLS_KEY)) ?? 'null') as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
await executor.writeDirectly(
|
||||
REGISTRATION_URLS_KEY,
|
||||
JSON.stringify(
|
||||
stored.map((entry) => ({
|
||||
...entry,
|
||||
use_count: 1,
|
||||
last_used_at: '2026-09-20T00:00:00.000Z',
|
||||
last_used_by_user_id: '1400000000000000901',
|
||||
})),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await expect(pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000902')).resolves.toBeNull();
|
||||
|
||||
expect(executor.events).toEqual(['read', 'write rejected', 'read']);
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed).toMatchObject({use_count: 1, last_used_by_user_id: '1400000000000000901'});
|
||||
});
|
||||
|
||||
it('counts concurrent uses of an uncapped registration URL without ever refusing one', async () => {
|
||||
const pods = [createPod(), createPod()];
|
||||
const {code} = await pods[0]!.createRegistrationUrl(registrationUrlParams(null));
|
||||
const registrationUrl = await pods[0]!.resolveRegistrationUrlCode(code);
|
||||
if (registrationUrl === null) throw new Error('registration URL did not resolve');
|
||||
|
||||
const claims = await Promise.all(
|
||||
Array.from({length: 5}, (_, index) =>
|
||||
pods[index % pods.length]!.claimRegistrationUrlUse(registrationUrl.id, `14000000000000002${index}0`),
|
||||
),
|
||||
);
|
||||
|
||||
expect(claims.every((claim) => claim !== null)).toBe(true);
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed?.use_count).toBe(5);
|
||||
});
|
||||
|
||||
it('frees a released seat for the next signup', async () => {
|
||||
const pod = createPod();
|
||||
const {code} = await pod.createRegistrationUrl(registrationUrlParams(1));
|
||||
const registrationUrl = await pod.resolveRegistrationUrlCode(code);
|
||||
if (registrationUrl === null) throw new Error('registration URL did not resolve');
|
||||
|
||||
const failedSignup = await pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000301');
|
||||
if (failedSignup === null) throw new Error('the first claim was refused');
|
||||
await expect(pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000302')).resolves.toBeNull();
|
||||
await pod.releaseRegistrationUrlUse(failedSignup);
|
||||
|
||||
await expect(pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000303')).resolves.not.toBeNull();
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed).toMatchObject({use_count: 1, last_used_by_user_id: '1400000000000000303'});
|
||||
});
|
||||
|
||||
it('enforces max_uses against the use count already stored in the blob', async () => {
|
||||
const pod = createPod();
|
||||
const id = 'b3c4f0b2-8a6e-4c41-9f55-3f0c2a7d1e91';
|
||||
await executor.writeDirectly(
|
||||
REGISTRATION_URLS_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id,
|
||||
label: 'Issued earlier',
|
||||
code_hash: createHash('sha256').update(id).digest('hex'),
|
||||
created_by_user_id: '1400000000000000001',
|
||||
created_at: '2026-09-01T00:00:00.000Z',
|
||||
expires_at: null,
|
||||
max_uses: 3,
|
||||
use_count: 2,
|
||||
revoked_at: null,
|
||||
approval_required: true,
|
||||
last_used_at: '2026-09-02T00:00:00.000Z',
|
||||
last_used_by_user_id: '1400000000000000002',
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(await pod.getRegistrationUrlsForAdmin()).toEqual([
|
||||
expect.objectContaining({
|
||||
id,
|
||||
use_count: 2,
|
||||
max_uses: 3,
|
||||
approval_required: true,
|
||||
last_used_at: '2026-09-02T00:00:00.000Z',
|
||||
last_used_by_user_id: '1400000000000000002',
|
||||
}),
|
||||
]);
|
||||
const registrationUrl = await pod.resolveRegistrationUrlCode(id);
|
||||
if (registrationUrl === null) throw new Error('stored registration URL did not resolve');
|
||||
expect(registrationUrl).toMatchObject({id, approval_required: true});
|
||||
|
||||
await expect(pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000401')).resolves.not.toBeNull();
|
||||
await expect(pod.claimRegistrationUrlUse(registrationUrl.id, '1400000000000000402')).resolves.toBeNull();
|
||||
|
||||
const [listed] = await createPod().getRegistrationUrlsForAdmin();
|
||||
expect(listed).toMatchObject({use_count: 3, max_uses: 3, last_used_by_user_id: '1400000000000000401'});
|
||||
await expect(pod.resolveRegistrationUrlCode(id)).resolves.toBeNull();
|
||||
expect(JSON.parse((await executor.readDirectly(REGISTRATION_URLS_KEY)) ?? 'null')[0]).toMatchObject({
|
||||
use_count: 3,
|
||||
max_uses: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps an SSO field another pod changed while this pod held a stale snapshot', async () => {
|
||||
const first = createPod();
|
||||
const second = createPod();
|
||||
await first.getSsoConfig();
|
||||
await second.getSsoConfig();
|
||||
|
||||
await first.setSsoConfig({displayName: 'Set by the first pod'});
|
||||
await second.setSsoConfig({clientId: 'set-by-the-second-pod'});
|
||||
|
||||
expect(await createPod().getSsoConfig()).toMatchObject({
|
||||
displayName: 'Set by the first pod',
|
||||
clientId: 'set-by-the-second-pod',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves an SSO row alone when another pod wrote it between this pod reading and writing it', async () => {
|
||||
const pod = createPod();
|
||||
await pod.getSsoConfig();
|
||||
executor.watch('sso_enforced');
|
||||
let competed = false;
|
||||
executor.competeBeforeEachWrite(async () => {
|
||||
if (competed) return;
|
||||
competed = true;
|
||||
await executor.writeDirectly('sso_enforced', 'true');
|
||||
});
|
||||
|
||||
await pod.setSsoConfig({displayName: 'Only the display name'});
|
||||
|
||||
expect(await executor.readDirectly('sso_enforced')).toBe('true');
|
||||
expect(await executor.readDirectly('sso_display_name')).toBe('Only the display name');
|
||||
});
|
||||
}
|
||||
|
||||
function pendingRegistration(userId: string) {
|
||||
return {
|
||||
user_id: userId,
|
||||
username: `pending_${userId.slice(-3)}`,
|
||||
discriminator: 1,
|
||||
global_name: null,
|
||||
email: `${userId}@example.com`,
|
||||
requested_at: `2026-09-01T00:00:${userId.slice(-2)}.000Z`,
|
||||
registration_url_id: null,
|
||||
client_ip: '127.0.0.1',
|
||||
};
|
||||
}
|
||||
|
||||
function registrationUrlParams(maxUses: number | null) {
|
||||
return {
|
||||
label: maxUses === null ? 'Uncapped' : `Capped at ${maxUses}`,
|
||||
createdByUserId: '1400000000000000001',
|
||||
expiresAt: null,
|
||||
maxUses,
|
||||
approvalRequired: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe('InstanceConfigRepository concurrent writes', () => {
|
||||
describe('in memory', () => {
|
||||
describeConcurrentInstanceConfigWrites(async () => new InMemoryCassandraQueryExecutor());
|
||||
});
|
||||
|
||||
describe.skipIf(!dockerAvailable)('on postgres', () => {
|
||||
let client: IPostgresClient;
|
||||
|
||||
beforeAll(async () => {
|
||||
const port = await freePort();
|
||||
startDockerContainer([
|
||||
'run',
|
||||
'-d',
|
||||
'--name',
|
||||
POSTGRES_CONTAINER,
|
||||
'-e',
|
||||
'POSTGRES_USER=fluxer',
|
||||
'-e',
|
||||
'POSTGRES_PASSWORD=fluxer',
|
||||
'-e',
|
||||
'POSTGRES_DB=fluxer',
|
||||
'-p',
|
||||
`127.0.0.1:${port}:5432`,
|
||||
'postgres:16-alpine',
|
||||
'-c',
|
||||
'fsync=off',
|
||||
]);
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 180 && !ready; attempt += 1) {
|
||||
await sleep(500);
|
||||
const probe = spawnSync('docker', ['exec', POSTGRES_CONTAINER, 'pg_isready', '-U', 'fluxer', '-d', 'fluxer'], {
|
||||
stdio: 'ignore',
|
||||
});
|
||||
if (probe.status !== 0) continue;
|
||||
try {
|
||||
await initPostgres({
|
||||
url: `postgres://fluxer:[email protected]:${port}/fluxer`,
|
||||
maxConnections: 4,
|
||||
kvTable: POSTGRES_KV_TABLE,
|
||||
});
|
||||
await getDefaultPostgresClient().query('SELECT 1');
|
||||
ready = true;
|
||||
} catch {
|
||||
await shutdownPostgres().catch(() => {});
|
||||
}
|
||||
}
|
||||
if (!ready) throw new Error('postgres never came up');
|
||||
client = getDefaultPostgresClient();
|
||||
await ensurePostgresKvSchema(client);
|
||||
}, 900_000);
|
||||
|
||||
afterAll(async () => {
|
||||
setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
|
||||
await shutdownPostgres().catch(() => {});
|
||||
spawnSync('docker', ['rm', '-f', POSTGRES_CONTAINER], {stdio: 'ignore'});
|
||||
});
|
||||
|
||||
describeConcurrentInstanceConfigWrites(async () => {
|
||||
await client.query(`DELETE FROM ${POSTGRES_KV_TABLE}`);
|
||||
return new PostgresKvQueryExecutor(client);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import crypto from 'node:crypto';
|
||||
import {Config} from '@app/api/Config';
|
||||
import type {APIConfig, BlueskyOAuthConfig, BlueskyOAuthKeyConfig} from '@app/api/config/APIConfig';
|
||||
import {fetchMany, fetchOne, upsertOne} from '@app/api/database/CassandraQueryExecution';
|
||||
import {executeConditional, fetchMany, fetchOne, upsertOne} from '@app/api/database/CassandraQueryExecution';
|
||||
import {Db, type PreparedQuery} from '@app/api/database/CassandraTypes';
|
||||
import type {InstanceConfigurationRow} from '@app/api/database/types/InstanceConfigTypes';
|
||||
import {
|
||||
getDefaultDateOfBirthCollection,
|
||||
@@ -17,6 +18,9 @@ import {resolveDeferredPhoneGateEnabled, setCachedDeferredPhoneGateEnabled} from
|
||||
import {InstanceConfiguration} from '@app/api/Tables';
|
||||
import {DEFAULT_DECAY_CONSTANTS, DEFAULT_RENEWAL_CONSTANTS} from '@app/api/utils/AttachmentDecay';
|
||||
import {isJsonRecord} from '@app/api/utils/JsonBoundaryUtils';
|
||||
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
|
||||
import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';
|
||||
import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
|
||||
import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';
|
||||
import {
|
||||
InstanceConfigResponse,
|
||||
@@ -29,9 +33,9 @@ import {
|
||||
GatewayRolloutConfigSchema,
|
||||
} from '@fluxer/schema/src/domains/admin/GatewayRolloutSchemas';
|
||||
import {
|
||||
type ScreenShareDeliveryConfig,
|
||||
ScreenShareDeliveryConfigSchema,
|
||||
} from '@fluxer/schema/src/domains/admin/ScreenShareDeliverySchemas';
|
||||
type PushServiceDeliveryConfig,
|
||||
PushServiceDeliveryConfigSchema,
|
||||
} from '@fluxer/schema/src/domains/admin/PushServiceDeliverySchemas';
|
||||
import {
|
||||
type VoiceNoiseSuppressionConfig,
|
||||
VoiceNoiseSuppressionConfigSchema,
|
||||
@@ -58,7 +62,7 @@ import {z} from 'zod';
|
||||
|
||||
const GATEWAY_ROLLOUT_CONFIG_KEY = 'gateway_rollout_config';
|
||||
const VOICE_NOISE_SUPPRESSION_CONFIG_KEY = 'voice_noise_suppression_config';
|
||||
const SCREEN_SHARE_DELIVERY_CONFIG_KEY = 'screen_share_delivery_config';
|
||||
const PUSH_SERVICE_DELIVERY_CONFIG_KEY = 'push_service_delivery_config';
|
||||
const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';
|
||||
const REGISTRATION_CONFIG_KEY = 'registration_config';
|
||||
const REGISTRATION_URLS_KEY = 'registration_urls';
|
||||
@@ -72,6 +76,22 @@ const INSTANCE_MEDIA_CONFIG_KEY = 'instance_media_config';
|
||||
export const INSTANCE_CONFIG_REFRESH_CHANNEL = 'instance-config-refresh';
|
||||
export const REGISTRATION_PENDING_APPROVAL_TRAIT = 'registration_pending_approval';
|
||||
export const REGISTRATION_REJECTED_TRAIT = 'registration_rejected';
|
||||
export const INSTANCE_CONFIG_WRITE_ATTEMPTS = 5;
|
||||
|
||||
export class InstanceConfigWriteConflictError extends ConflictError {
|
||||
constructor(key: string) {
|
||||
super({
|
||||
code: APIErrorCodes.CONFLICT,
|
||||
message: `Instance config "${key}" changed concurrently on all ${INSTANCE_CONFIG_WRITE_ATTEMPTS} write attempts. Nothing was written. Retry the change.`,
|
||||
});
|
||||
this.name = 'InstanceConfigWriteConflictError';
|
||||
}
|
||||
}
|
||||
|
||||
interface StoredValueUpdate<T> {
|
||||
value: string | null;
|
||||
result: T;
|
||||
}
|
||||
|
||||
export type InstanceRegistrationConfig = InstanceRegistration;
|
||||
|
||||
@@ -277,6 +297,11 @@ export interface InstanceRegistrationUrl extends RegistrationUrlResponse {
|
||||
type InstanceRegistrationUrlPublic = RegistrationUrlResponse;
|
||||
type InstancePendingRegistration = PendingRegistrationResponse;
|
||||
|
||||
export interface RegistrationUrlClaim {
|
||||
registration_url_id: string;
|
||||
user_id: string;
|
||||
}
|
||||
|
||||
const DEFAULT_REGISTRATION_CONFIG: InstanceRegistrationConfig = {
|
||||
mode: 'open',
|
||||
admin_registration_urls_enabled: true,
|
||||
@@ -344,7 +369,7 @@ type StoredConfigSection =
|
||||
| 'app public'
|
||||
| 'gateway rollout'
|
||||
| 'voice noise suppression'
|
||||
| 'screen share delivery'
|
||||
| 'push service delivery'
|
||||
| 'experiment delivery'
|
||||
| 'instance policy'
|
||||
| 'integrations'
|
||||
@@ -483,8 +508,8 @@ function parseStoredVoiceNoiseSuppressionConfig(raw: string | null): VoiceNoiseS
|
||||
return parseStoredConfigOrDefault(VoiceNoiseSuppressionConfigSchema, raw, 'voice noise suppression');
|
||||
}
|
||||
|
||||
function parseStoredScreenShareDeliveryConfig(raw: string | null): ScreenShareDeliveryConfig {
|
||||
return parseStoredConfigOrDefault(ScreenShareDeliveryConfigSchema, raw, 'screen share delivery');
|
||||
function parseStoredPushServiceDeliveryConfig(raw: string | null): PushServiceDeliveryConfig {
|
||||
return parseStoredConfigOrDefault(PushServiceDeliveryConfigSchema, raw, 'push service delivery');
|
||||
}
|
||||
|
||||
function parseStoredExperimentDeliveryConfig(raw: string | null): ExperimentDeliveryConfig {
|
||||
@@ -910,6 +935,75 @@ function parseStoredSsoAllowedEmailDomains(raw: string | undefined, log = false)
|
||||
return Array.from(domains).slice(0, MAX_SSO_ALLOWED_DOMAINS);
|
||||
}
|
||||
|
||||
function readStoredSsoConfig(
|
||||
configs: ReadonlyMap<string, string>,
|
||||
options?: {includeSecret?: boolean},
|
||||
): InstanceSsoConfig {
|
||||
const flags = readStoredSsoFlags(configs);
|
||||
const read = (key: string): string | null => {
|
||||
const v = configs.get(key);
|
||||
if (!v) return null;
|
||||
const trimmed = v.trim();
|
||||
return trimmed.length === 0 ? null : trimmed;
|
||||
};
|
||||
const allowedDomains = parseStoredSsoAllowedEmailDomains(configs.get('sso_allowed_domains'));
|
||||
const clientSecret = read('sso_client_secret');
|
||||
return {
|
||||
...flags,
|
||||
displayName: read('sso_display_name'),
|
||||
issuer: read('sso_issuer'),
|
||||
authorizationUrl: read('sso_authorization_url'),
|
||||
tokenUrl: read('sso_token_url'),
|
||||
userInfoUrl: read('sso_userinfo_url'),
|
||||
jwksUrl: read('sso_jwks_url'),
|
||||
clientId: read('sso_client_id'),
|
||||
clientSecret: options?.includeSecret ? clientSecret : undefined,
|
||||
clientSecretSet: Boolean(clientSecret),
|
||||
scope: read('sso_scope'),
|
||||
allowedEmailDomains: allowedDomains,
|
||||
redirectUri: null,
|
||||
};
|
||||
}
|
||||
|
||||
interface SsoRowWrite {
|
||||
key: string;
|
||||
value: string | undefined;
|
||||
unset: string;
|
||||
}
|
||||
|
||||
function ssoRow<T>(key: string, value: T | undefined, current: T, format: (value: T) => string): SsoRowWrite {
|
||||
return {key, value: value === undefined ? undefined : format(value), unset: format(current)};
|
||||
}
|
||||
|
||||
function nextSsoRowValue(row: SsoRowWrite, raw: string | null): string | null {
|
||||
const value = row.value ?? raw ?? row.unset;
|
||||
return value === raw ? null : value;
|
||||
}
|
||||
|
||||
function formatSsoBoolean(value: boolean): string {
|
||||
return value ? 'true' : 'false';
|
||||
}
|
||||
|
||||
function formatSsoString(value: string | null): string {
|
||||
return value ?? '';
|
||||
}
|
||||
|
||||
function formatSsoDomains(value: Array<string>): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function normalizeSsoAllowedEmailDomainsForWrite(domains: Array<string>, enabled: boolean): Array<string> {
|
||||
try {
|
||||
return normalizeSsoAllowedEmailDomains(domains);
|
||||
} catch (error) {
|
||||
if (enabled) {
|
||||
throw error;
|
||||
}
|
||||
Logger.warn({error}, 'Clearing invalid SSO allowed domain config while SSO is disabled');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export class InstanceConfigRepository {
|
||||
private readonly kvClient: IKVProvider | null;
|
||||
private configCache: InstanceConfigCache;
|
||||
@@ -993,6 +1087,57 @@ export class InstanceConfigRepository {
|
||||
);
|
||||
}
|
||||
|
||||
private async updateStoredConfig<T>(key: string, next: (raw: string | null) => T): Promise<T> {
|
||||
const cache = this.configCache;
|
||||
const {result} = await this.compareAndSetStoredValue(cache, key, (raw) => {
|
||||
const config = next(raw);
|
||||
return {value: JSON.stringify(config), result: config};
|
||||
});
|
||||
await this.publishRefresh(cache.sourceId);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async compareAndSetStoredValue<T>(
|
||||
cache: InstanceConfigCache,
|
||||
key: string,
|
||||
next: (raw: string | null) => StoredValueUpdate<T>,
|
||||
): Promise<{result: T; written: boolean}> {
|
||||
await cache.getSnapshot();
|
||||
for (let attempt = 0; attempt < INSTANCE_CONFIG_WRITE_ATTEMPTS; attempt++) {
|
||||
cache.assertActive();
|
||||
const current = await this.fetchConfigForWrite(key);
|
||||
cache.assertActive();
|
||||
const {value, result} = next(current);
|
||||
if (value === null) return {result, written: false};
|
||||
if (await executeConditional(this.compareAndSetConfig(key, current, value))) {
|
||||
cache.update(key, value);
|
||||
return {result, written: true};
|
||||
}
|
||||
}
|
||||
Logger.error(
|
||||
{key, attempts: INSTANCE_CONFIG_WRITE_ATTEMPTS},
|
||||
'Instance config write lost to a concurrent write on every attempt',
|
||||
);
|
||||
throw new InstanceConfigWriteConflictError(key);
|
||||
}
|
||||
|
||||
private compareAndSetConfig(key: string, current: string | null, value: string): PreparedQuery {
|
||||
const updatedAt = new Date();
|
||||
if (current === null) {
|
||||
return InstanceConfiguration.insertIfNotExists({key, value, updated_at: updatedAt});
|
||||
}
|
||||
return InstanceConfiguration.conditionalPatchByPk(
|
||||
{key},
|
||||
{value: Db.set(value), updated_at: Db.set(updatedAt)},
|
||||
{value: current},
|
||||
);
|
||||
}
|
||||
|
||||
private async fetchConfigForWrite(key: string): Promise<string | null> {
|
||||
const [row] = await fetchMany<InstanceConfigurationRow>(FETCH_CONFIG_QUERY, {key}, {consistency: 'serial'});
|
||||
return row?.value ?? null;
|
||||
}
|
||||
|
||||
private async fetchConfigFromDatabase(key: string): Promise<string | null> {
|
||||
const row = await fetchOne<InstanceConfigurationRow>(FETCH_CONFIG_QUERY, {key});
|
||||
return row?.value ?? null;
|
||||
@@ -1014,7 +1159,7 @@ export class InstanceConfigRepository {
|
||||
parseStoredGatewayRolloutConfig(snapshot.get(GATEWAY_ROLLOUT_CONFIG_KEY) ?? null),
|
||||
);
|
||||
parseStoredVoiceNoiseSuppressionConfig(snapshot.get(VOICE_NOISE_SUPPRESSION_CONFIG_KEY) ?? null);
|
||||
parseStoredScreenShareDeliveryConfig(snapshot.get(SCREEN_SHARE_DELIVERY_CONFIG_KEY) ?? null);
|
||||
parseStoredPushServiceDeliveryConfig(snapshot.get(PUSH_SERVICE_DELIVERY_CONFIG_KEY) ?? null);
|
||||
parseStoredExperimentDeliveryConfig(snapshot.get(EXPERIMENT_DELIVERY_CONFIG_KEY) ?? null);
|
||||
const policy = parseStoredInstancePolicyConfig(snapshot.get(INSTANCE_POLICY_CONFIG_KEY) ?? null);
|
||||
checkStoredConfig('registration', () =>
|
||||
@@ -1082,8 +1227,12 @@ export class InstanceConfigRepository {
|
||||
return parseStoredGatewayRolloutConfig(raw);
|
||||
}
|
||||
|
||||
async setGatewayRolloutConfig(config: GatewayRolloutConfig): Promise<void> {
|
||||
await this.setConfig(GATEWAY_ROLLOUT_CONFIG_KEY, JSON.stringify(decodeGatewayRolloutConfig(config)));
|
||||
updateGatewayRolloutConfig(
|
||||
update: (current: GatewayRolloutConfig) => GatewayRolloutConfig,
|
||||
): Promise<GatewayRolloutConfig> {
|
||||
return this.updateStoredConfig(GATEWAY_ROLLOUT_CONFIG_KEY, (raw) =>
|
||||
decodeGatewayRolloutConfig(update(parseStoredGatewayRolloutConfig(raw))),
|
||||
);
|
||||
}
|
||||
|
||||
async getVoiceNoiseSuppressionConfig(): Promise<VoiceNoiseSuppressionConfig> {
|
||||
@@ -1092,18 +1241,36 @@ export class InstanceConfigRepository {
|
||||
}
|
||||
|
||||
async setVoiceNoiseSuppressionConfig(config: VoiceNoiseSuppressionConfig): Promise<void> {
|
||||
const validated = validateStoredConfig(VoiceNoiseSuppressionConfigSchema, config, 'voice noise suppression');
|
||||
await this.setConfig(VOICE_NOISE_SUPPRESSION_CONFIG_KEY, JSON.stringify(validated));
|
||||
await this.updateVoiceNoiseSuppressionConfig(() => config);
|
||||
}
|
||||
|
||||
async getScreenShareDeliveryConfig(): Promise<ScreenShareDeliveryConfig> {
|
||||
const raw = await this.getConfig(SCREEN_SHARE_DELIVERY_CONFIG_KEY);
|
||||
return parseStoredScreenShareDeliveryConfig(raw);
|
||||
updateVoiceNoiseSuppressionConfig(
|
||||
update: (current: VoiceNoiseSuppressionConfig) => VoiceNoiseSuppressionConfig,
|
||||
): Promise<VoiceNoiseSuppressionConfig> {
|
||||
return this.updateStoredConfig(VOICE_NOISE_SUPPRESSION_CONFIG_KEY, (raw) =>
|
||||
validateStoredConfig(
|
||||
VoiceNoiseSuppressionConfigSchema,
|
||||
update(parseStoredVoiceNoiseSuppressionConfig(raw)),
|
||||
'voice noise suppression',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async setScreenShareDeliveryConfig(config: ScreenShareDeliveryConfig): Promise<void> {
|
||||
const validated = validateStoredConfig(ScreenShareDeliveryConfigSchema, config, 'screen share delivery');
|
||||
await this.setConfig(SCREEN_SHARE_DELIVERY_CONFIG_KEY, JSON.stringify(validated));
|
||||
async getPushServiceDeliveryConfig(): Promise<PushServiceDeliveryConfig> {
|
||||
const raw = await this.getConfig(PUSH_SERVICE_DELIVERY_CONFIG_KEY);
|
||||
return parseStoredPushServiceDeliveryConfig(raw);
|
||||
}
|
||||
|
||||
updatePushServiceDeliveryConfig(
|
||||
update: (current: PushServiceDeliveryConfig) => PushServiceDeliveryConfig,
|
||||
): Promise<PushServiceDeliveryConfig> {
|
||||
return this.updateStoredConfig(PUSH_SERVICE_DELIVERY_CONFIG_KEY, (raw) =>
|
||||
validateStoredConfig(
|
||||
PushServiceDeliveryConfigSchema,
|
||||
update(parseStoredPushServiceDeliveryConfig(raw)),
|
||||
'push service delivery',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async getExperimentDeliveryConfig(): Promise<ExperimentDeliveryConfig> {
|
||||
@@ -1112,8 +1279,19 @@ export class InstanceConfigRepository {
|
||||
}
|
||||
|
||||
async setExperimentDeliveryConfig(config: ExperimentDeliveryConfig): Promise<void> {
|
||||
const validated = validateStoredConfig(ExperimentDeliveryConfigSchema, config, 'experiment delivery');
|
||||
await this.setConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, JSON.stringify(validated));
|
||||
await this.updateExperimentDeliveryConfig(() => config);
|
||||
}
|
||||
|
||||
updateExperimentDeliveryConfig(
|
||||
update: (current: ExperimentDeliveryConfig) => ExperimentDeliveryConfig,
|
||||
): Promise<ExperimentDeliveryConfig> {
|
||||
return this.updateStoredConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, (raw) =>
|
||||
validateStoredConfig(
|
||||
ExperimentDeliveryConfigSchema,
|
||||
update(parseStoredExperimentDeliveryConfig(raw)),
|
||||
'experiment delivery',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async readLimitConfigInputs(): Promise<LimitConfigInputs> {
|
||||
@@ -1149,26 +1327,27 @@ export class InstanceConfigRepository {
|
||||
legal?: Partial<InstanceAppPublicConfig['legal']>;
|
||||
registration?: Partial<InstanceAppPublicConfig['registration']>;
|
||||
}): Promise<InstanceAppPublicConfig> {
|
||||
const current = await this.getAppPublicConfig();
|
||||
const next = decodeAppPublicConfig({
|
||||
branding: {
|
||||
...current.branding,
|
||||
...(config.branding ?? {}),
|
||||
},
|
||||
setup: {
|
||||
...current.setup,
|
||||
...(config.setup ?? {}),
|
||||
},
|
||||
legal: {
|
||||
...current.legal,
|
||||
...(config.legal ?? {}),
|
||||
},
|
||||
registration: {
|
||||
...current.registration,
|
||||
...(config.registration ?? {}),
|
||||
},
|
||||
const next = await this.updateStoredConfig(APP_PUBLIC_CONFIG_KEY, (raw) => {
|
||||
const current = parseStoredAppPublicConfig(raw);
|
||||
return decodeAppPublicConfig({
|
||||
branding: {
|
||||
...current.branding,
|
||||
...(config.branding ?? {}),
|
||||
},
|
||||
setup: {
|
||||
...current.setup,
|
||||
...(config.setup ?? {}),
|
||||
},
|
||||
legal: {
|
||||
...current.legal,
|
||||
...(config.legal ?? {}),
|
||||
},
|
||||
registration: {
|
||||
...current.registration,
|
||||
...(config.registration ?? {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
await this.setConfig(APP_PUBLIC_CONFIG_KEY, JSON.stringify(next));
|
||||
setCachedDateOfBirthCollection(next.registration.collect_date_of_birth);
|
||||
return next;
|
||||
}
|
||||
@@ -1188,10 +1367,21 @@ export class InstanceConfigRepository {
|
||||
return parseStoredInstancePolicyConfig(raw);
|
||||
}
|
||||
|
||||
async setInstancePolicyConfig(config: Partial<InstancePolicyConfig>): Promise<InstancePolicyConfig> {
|
||||
const current = await this.readStoredInstancePolicyConfig();
|
||||
const next = decodeInstancePolicyConfig({...current, ...config});
|
||||
await this.setConfig(INSTANCE_POLICY_CONFIG_KEY, JSON.stringify(next));
|
||||
setInstancePolicyConfig(config: Partial<InstancePolicyConfig>): Promise<InstancePolicyConfig> {
|
||||
return this.updateInstancePolicyConfig(() => config);
|
||||
}
|
||||
|
||||
async updateInstancePolicyConfig(
|
||||
plan: (current: InstancePolicyConfig) => Partial<InstancePolicyConfig>,
|
||||
): Promise<InstancePolicyConfig> {
|
||||
const cache = this.configCache;
|
||||
const {result: next, written} = await this.compareAndSetStoredValue(cache, INSTANCE_POLICY_CONFIG_KEY, (raw) => {
|
||||
const current = parseStoredInstancePolicyConfig(raw);
|
||||
const patch = plan(current);
|
||||
const config = decodeInstancePolicyConfig({...current, ...patch});
|
||||
return {value: Object.keys(patch).length === 0 ? null : JSON.stringify(config), result: config};
|
||||
});
|
||||
if (written) await this.publishRefresh(cache.sourceId);
|
||||
setCachedDeferredPhoneGateEnabled(resolveDeferredPhoneGateEnabled(next));
|
||||
return next;
|
||||
}
|
||||
@@ -1201,37 +1391,37 @@ export class InstanceConfigRepository {
|
||||
return parseStoredInstanceIntegrationsConfig(raw);
|
||||
}
|
||||
|
||||
async setInstanceIntegrationsConfig(config: InstanceIntegrationsConfigPatch): Promise<InstanceIntegrationsConfig> {
|
||||
const current = await this.getInstanceIntegrationsConfig();
|
||||
const next = decodeInstanceIntegrationsConfig({
|
||||
gif: {
|
||||
...current.gif,
|
||||
...(config.gif ?? {}),
|
||||
},
|
||||
youtube: {
|
||||
...current.youtube,
|
||||
...(config.youtube ?? {}),
|
||||
},
|
||||
captcha: {
|
||||
...current.captcha,
|
||||
...(config.captcha ?? {}),
|
||||
},
|
||||
email: {
|
||||
...current.email,
|
||||
...(config.email ?? {}),
|
||||
smtp: {
|
||||
...current.email.smtp,
|
||||
...(config.email?.smtp ?? {}),
|
||||
setInstanceIntegrationsConfig(config: InstanceIntegrationsConfigPatch): Promise<InstanceIntegrationsConfig> {
|
||||
return this.updateStoredConfig(INSTANCE_INTEGRATIONS_CONFIG_KEY, (raw) => {
|
||||
const current = parseStoredInstanceIntegrationsConfig(raw);
|
||||
return decodeInstanceIntegrationsConfig({
|
||||
gif: {
|
||||
...current.gif,
|
||||
...(config.gif ?? {}),
|
||||
},
|
||||
},
|
||||
bluesky: {
|
||||
...current.bluesky,
|
||||
...(config.bluesky ?? {}),
|
||||
keys: config.bluesky?.keys ?? current.bluesky.keys,
|
||||
},
|
||||
youtube: {
|
||||
...current.youtube,
|
||||
...(config.youtube ?? {}),
|
||||
},
|
||||
captcha: {
|
||||
...current.captcha,
|
||||
...(config.captcha ?? {}),
|
||||
},
|
||||
email: {
|
||||
...current.email,
|
||||
...(config.email ?? {}),
|
||||
smtp: {
|
||||
...current.email.smtp,
|
||||
...(config.email?.smtp ?? {}),
|
||||
},
|
||||
},
|
||||
bluesky: {
|
||||
...current.bluesky,
|
||||
...(config.bluesky ?? {}),
|
||||
keys: config.bluesky?.keys ?? current.bluesky.keys,
|
||||
},
|
||||
});
|
||||
});
|
||||
await this.setConfig(INSTANCE_INTEGRATIONS_CONFIG_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
async getInstanceMediaConfig(): Promise<InstanceMediaConfig> {
|
||||
@@ -1239,16 +1429,16 @@ export class InstanceConfigRepository {
|
||||
return parseStoredInstanceMediaConfig(raw);
|
||||
}
|
||||
|
||||
async setInstanceMediaConfig(config: InstanceMediaConfigPatch): Promise<InstanceMediaConfig> {
|
||||
const current = await this.getInstanceMediaConfig();
|
||||
const next = decodeInstanceMediaConfig({
|
||||
attachment_decay: {
|
||||
...current.attachment_decay,
|
||||
...(config.attachment_decay ?? {}),
|
||||
},
|
||||
setInstanceMediaConfig(config: InstanceMediaConfigPatch): Promise<InstanceMediaConfig> {
|
||||
return this.updateStoredConfig(INSTANCE_MEDIA_CONFIG_KEY, (raw) => {
|
||||
const current = parseStoredInstanceMediaConfig(raw);
|
||||
return decodeInstanceMediaConfig({
|
||||
attachment_decay: {
|
||||
...current.attachment_decay,
|
||||
...(config.attachment_decay ?? {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
await this.setConfig(INSTANCE_MEDIA_CONFIG_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
async getEffectiveAttachmentDecayConfig(): Promise<InstanceAttachmentDecayEffectiveConfig> {
|
||||
@@ -1485,15 +1675,15 @@ export class InstanceConfigRepository {
|
||||
return parseStoredRegistrationConfig(raw);
|
||||
}
|
||||
|
||||
async setRegistrationConfig(config: Partial<InstanceRegistrationConfig>): Promise<InstanceRegistrationConfig> {
|
||||
const current = await this.getRegistrationConfig();
|
||||
const next = decodeRegistrationConfig({
|
||||
mode: config.mode ?? current.mode,
|
||||
admin_registration_urls_enabled:
|
||||
config.admin_registration_urls_enabled ?? current.admin_registration_urls_enabled,
|
||||
setRegistrationConfig(config: Partial<InstanceRegistrationConfig>): Promise<InstanceRegistrationConfig> {
|
||||
return this.updateStoredConfig(REGISTRATION_CONFIG_KEY, (raw) => {
|
||||
const current = parseStoredRegistrationConfig(raw);
|
||||
return decodeRegistrationConfig({
|
||||
mode: config.mode ?? current.mode,
|
||||
admin_registration_urls_enabled:
|
||||
config.admin_registration_urls_enabled ?? current.admin_registration_urls_enabled,
|
||||
});
|
||||
});
|
||||
await this.setConfig(REGISTRATION_CONFIG_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
async getRegistrationPublicConfig(): Promise<InstanceRegistrationConfig> {
|
||||
@@ -1534,16 +1724,20 @@ export class InstanceConfigRepository {
|
||||
last_used_at: null,
|
||||
last_used_by_user_id: null,
|
||||
};
|
||||
const registrationUrls = await this.getRegistrationUrls();
|
||||
await this.setRegistrationUrls([registrationUrl, ...registrationUrls]);
|
||||
await this.updateStoredConfig(REGISTRATION_URLS_KEY, (raw) =>
|
||||
validateStoredCollection(
|
||||
StoredRegistrationUrlSchema,
|
||||
[registrationUrl, ...parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs')],
|
||||
'registration URLs',
|
||||
),
|
||||
);
|
||||
return {registrationUrl: redactRegistrationUrl(registrationUrl), code};
|
||||
}
|
||||
|
||||
async revokeRegistrationUrl(id: string): Promise<void> {
|
||||
const now = new Date().toISOString();
|
||||
const registrationUrls = await this.getRegistrationUrls();
|
||||
await this.setRegistrationUrls(
|
||||
registrationUrls.map((registrationUrl) =>
|
||||
await this.updateStoredConfig(REGISTRATION_URLS_KEY, (raw) =>
|
||||
parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs').map((registrationUrl) =>
|
||||
registrationUrl.id === id && !registrationUrl.revoked_at
|
||||
? {...registrationUrl, revoked_at: now}
|
||||
: registrationUrl,
|
||||
@@ -1556,9 +1750,8 @@ export class InstanceConfigRepository {
|
||||
if (!normalizedCode) return null;
|
||||
const hash = this.hashRegistrationUrlCode(normalizedCode);
|
||||
const now = new Date();
|
||||
const registrationUrls = await this.getRegistrationUrls();
|
||||
return (
|
||||
registrationUrls.find(
|
||||
(await this.fetchRegistrationUrlDefinitions()).find(
|
||||
(registrationUrl) =>
|
||||
(registrationUrl.id === normalizedCode || registrationUrl.code_hash === hash) &&
|
||||
isRegistrationUrlUsable(registrationUrl, now),
|
||||
@@ -1566,21 +1759,68 @@ export class InstanceConfigRepository {
|
||||
);
|
||||
}
|
||||
|
||||
async recordRegistrationUrlUse(id: string, userId: string): Promise<void> {
|
||||
const now = new Date().toISOString();
|
||||
const registrationUrls = await this.getRegistrationUrls();
|
||||
await this.setRegistrationUrls(
|
||||
registrationUrls.map((registrationUrl) =>
|
||||
registrationUrl.id === id
|
||||
? {
|
||||
...registrationUrl,
|
||||
use_count: registrationUrl.use_count + 1,
|
||||
last_used_at: now,
|
||||
last_used_by_user_id: userId,
|
||||
}
|
||||
: registrationUrl,
|
||||
),
|
||||
);
|
||||
async claimRegistrationUrlUse(registrationUrlId: string, userId: string): Promise<RegistrationUrlClaim | null> {
|
||||
const cache = this.configCache;
|
||||
let claimed: {result: RegistrationUrlClaim | null; written: boolean};
|
||||
try {
|
||||
claimed = await this.compareAndSetStoredValue<RegistrationUrlClaim | null>(
|
||||
cache,
|
||||
REGISTRATION_URLS_KEY,
|
||||
(raw) => {
|
||||
const registrationUrls = parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs');
|
||||
const now = new Date();
|
||||
const claimable = registrationUrls.find(
|
||||
(registrationUrl) =>
|
||||
registrationUrl.id === registrationUrlId && isRegistrationUrlUsable(registrationUrl, now),
|
||||
);
|
||||
if (!claimable) return {value: null, result: null};
|
||||
const next = registrationUrls.map((registrationUrl) =>
|
||||
registrationUrl === claimable
|
||||
? {
|
||||
...registrationUrl,
|
||||
use_count: registrationUrl.use_count + 1,
|
||||
last_used_at: now.toISOString(),
|
||||
last_used_by_user_id: userId,
|
||||
}
|
||||
: registrationUrl,
|
||||
);
|
||||
return {
|
||||
value: JSON.stringify(validateStoredCollection(StoredRegistrationUrlSchema, next, 'registration URLs')),
|
||||
result: {registration_url_id: registrationUrlId, user_id: userId},
|
||||
};
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof InstanceConfigWriteConflictError) throw new ServiceUnavailableError();
|
||||
throw error;
|
||||
}
|
||||
if (claimed.written) await this.publishRefresh(cache.sourceId);
|
||||
return claimed.result;
|
||||
}
|
||||
|
||||
async releaseRegistrationUrlUse(claim: RegistrationUrlClaim): Promise<void> {
|
||||
const cache = this.configCache;
|
||||
try {
|
||||
const {written} = await this.compareAndSetStoredValue<null>(cache, REGISTRATION_URLS_KEY, (raw) => {
|
||||
const registrationUrls = parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs');
|
||||
const released = registrationUrls.find(
|
||||
(registrationUrl) => registrationUrl.id === claim.registration_url_id && registrationUrl.use_count > 0,
|
||||
);
|
||||
if (!released) return {value: null, result: null};
|
||||
const next = registrationUrls.map((registrationUrl) =>
|
||||
registrationUrl === released
|
||||
? {...registrationUrl, use_count: registrationUrl.use_count - 1}
|
||||
: registrationUrl,
|
||||
);
|
||||
return {value: JSON.stringify(next), result: null};
|
||||
});
|
||||
if (written) await this.publishRefresh(cache.sourceId);
|
||||
} catch (error) {
|
||||
Logger.warn(
|
||||
{registrationUrlId: claim.registration_url_id, userId: claim.user_id, error},
|
||||
'Releasing a registration URL use failed',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getPendingRegistrations(): Promise<Array<InstancePendingRegistration>> {
|
||||
@@ -1591,104 +1831,82 @@ export class InstanceConfigRepository {
|
||||
}
|
||||
|
||||
async addPendingRegistration(pendingRegistration: InstancePendingRegistration): Promise<void> {
|
||||
const pendingRegistrations = await this.getPendingRegistrations();
|
||||
const next = [
|
||||
pendingRegistration,
|
||||
...pendingRegistrations.filter((entry) => entry.user_id !== pendingRegistration.user_id),
|
||||
];
|
||||
await this.setPendingRegistrations(next);
|
||||
await this.updateStoredConfig(REGISTRATION_PENDING_APPROVALS_KEY, (raw) =>
|
||||
validateStoredCollection(
|
||||
StoredPendingRegistrationSchema,
|
||||
[
|
||||
pendingRegistration,
|
||||
...parseStoredCollection(StoredPendingRegistrationSchema, raw, 'pending registrations').filter(
|
||||
(entry) => entry.user_id !== pendingRegistration.user_id,
|
||||
),
|
||||
],
|
||||
'pending registrations',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async removePendingRegistration(userId: string): Promise<void> {
|
||||
const pendingRegistrations = await this.getPendingRegistrations();
|
||||
await this.setPendingRegistrations(pendingRegistrations.filter((entry) => entry.user_id !== userId));
|
||||
await this.updateStoredConfig(REGISTRATION_PENDING_APPROVALS_KEY, (raw) =>
|
||||
parseStoredCollection(StoredPendingRegistrationSchema, raw, 'pending registrations').filter(
|
||||
(entry) => entry.user_id !== userId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async getSsoConfig(options?: {includeSecret?: boolean}): Promise<InstanceSsoConfig> {
|
||||
const configs = await this.getAllConfigs();
|
||||
const flags = readStoredSsoFlags(configs);
|
||||
const read = (key: string): string | null => {
|
||||
const v = configs.get(key);
|
||||
if (!v) return null;
|
||||
const trimmed = v.trim();
|
||||
return trimmed.length === 0 ? null : trimmed;
|
||||
};
|
||||
const allowedDomains = parseStoredSsoAllowedEmailDomains(configs.get('sso_allowed_domains'));
|
||||
const clientSecret = read('sso_client_secret');
|
||||
return {
|
||||
...flags,
|
||||
displayName: read('sso_display_name'),
|
||||
issuer: read('sso_issuer'),
|
||||
authorizationUrl: read('sso_authorization_url'),
|
||||
tokenUrl: read('sso_token_url'),
|
||||
userInfoUrl: read('sso_userinfo_url'),
|
||||
jwksUrl: read('sso_jwks_url'),
|
||||
clientId: read('sso_client_id'),
|
||||
clientSecret: options?.includeSecret ? clientSecret : undefined,
|
||||
clientSecretSet: Boolean(clientSecret),
|
||||
scope: read('sso_scope'),
|
||||
allowedEmailDomains: allowedDomains,
|
||||
redirectUri: null,
|
||||
};
|
||||
return readStoredSsoConfig(await this.getAllConfigs(), options);
|
||||
}
|
||||
|
||||
async setSsoConfig(config: Partial<InstanceSsoConfig>): Promise<InstanceSsoConfig> {
|
||||
const current = await this.getSsoConfig({includeSecret: true});
|
||||
const definedConfig = Object.fromEntries(
|
||||
Object.entries(config).filter(([, value]) => value !== undefined),
|
||||
) as Partial<InstanceSsoConfig>;
|
||||
const next: InstanceSsoConfig = {
|
||||
...current,
|
||||
...definedConfig,
|
||||
clientSecret: config.clientSecret !== undefined ? config.clientSecret : current.clientSecret,
|
||||
};
|
||||
if (config.enabled === true && config.enforced === undefined && !current.enabled) {
|
||||
next.enforced = true;
|
||||
}
|
||||
let allowedEmailDomains: Array<string>;
|
||||
try {
|
||||
allowedEmailDomains = normalizeSsoAllowedEmailDomains(next.allowedEmailDomains);
|
||||
} catch (error) {
|
||||
if (next.enabled) {
|
||||
throw error;
|
||||
}
|
||||
Logger.warn({error}, 'Clearing invalid SSO allowed domain config while SSO is disabled');
|
||||
allowedEmailDomains = [];
|
||||
}
|
||||
const entries: Array<[string, string]> = [
|
||||
['sso_enabled', next.enabled ? 'true' : 'false'],
|
||||
['sso_enforced', next.enforced ? 'true' : 'false'],
|
||||
['sso_display_name', next.displayName ?? ''],
|
||||
['sso_issuer', next.issuer ?? ''],
|
||||
['sso_authorization_url', next.authorizationUrl ?? ''],
|
||||
['sso_token_url', next.tokenUrl ?? ''],
|
||||
['sso_userinfo_url', next.userInfoUrl ?? ''],
|
||||
['sso_jwks_url', next.jwksUrl ?? ''],
|
||||
['sso_client_id', next.clientId ?? ''],
|
||||
['sso_scope', next.scope ?? ''],
|
||||
['sso_allowed_domains', JSON.stringify(allowedEmailDomains)],
|
||||
['sso_auto_provision', next.autoProvision ? 'true' : 'false'],
|
||||
['sso_redirect_uri', ''],
|
||||
const configs = await this.getAllConfigs();
|
||||
const current = readStoredSsoConfig(configs, {includeSecret: true});
|
||||
const enabled = config.enabled ?? current.enabled;
|
||||
const allowedEmailDomains =
|
||||
config.allowedEmailDomains === undefined
|
||||
? undefined
|
||||
: normalizeSsoAllowedEmailDomainsForWrite(config.allowedEmailDomains, enabled);
|
||||
const rows: Array<SsoRowWrite> = [
|
||||
ssoRow('sso_enabled', config.enabled, current.enabled, formatSsoBoolean),
|
||||
ssoRow('sso_enforced', config.enforced, current.enforced, formatSsoBoolean),
|
||||
ssoRow('sso_display_name', config.displayName, current.displayName, formatSsoString),
|
||||
ssoRow('sso_issuer', config.issuer, current.issuer, formatSsoString),
|
||||
ssoRow('sso_authorization_url', config.authorizationUrl, current.authorizationUrl, formatSsoString),
|
||||
ssoRow('sso_token_url', config.tokenUrl, current.tokenUrl, formatSsoString),
|
||||
ssoRow('sso_userinfo_url', config.userInfoUrl, current.userInfoUrl, formatSsoString),
|
||||
ssoRow('sso_jwks_url', config.jwksUrl, current.jwksUrl, formatSsoString),
|
||||
ssoRow('sso_client_id', config.clientId, current.clientId, formatSsoString),
|
||||
ssoRow('sso_scope', config.scope, current.scope, formatSsoString),
|
||||
ssoRow('sso_allowed_domains', allowedEmailDomains, current.allowedEmailDomains, formatSsoDomains),
|
||||
ssoRow('sso_auto_provision', config.autoProvision, current.autoProvision, formatSsoBoolean),
|
||||
ssoRow('sso_redirect_uri', undefined, null, formatSsoString),
|
||||
];
|
||||
if (config.clientSecret !== undefined) {
|
||||
entries.push(['sso_client_secret', config.clientSecret ?? '']);
|
||||
rows.push(ssoRow('sso_client_secret', config.clientSecret, current.clientSecret ?? null, formatSsoString));
|
||||
}
|
||||
await this.setConfigs(entries);
|
||||
const cache = this.configCache;
|
||||
const results = await Promise.allSettled(
|
||||
rows
|
||||
.filter((row) => row.value !== undefined || !configs.has(row.key))
|
||||
.map((row) =>
|
||||
this.compareAndSetStoredValue(cache, row.key, (raw) => ({value: nextSsoRowValue(row, raw), result: null})),
|
||||
),
|
||||
);
|
||||
const errors: Array<unknown> = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []));
|
||||
if (results.some((result) => result.status === 'fulfilled' && result.value.written)) {
|
||||
try {
|
||||
await this.publishRefresh(cache.sourceId);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
if (errors.length === 1) throw errors[0];
|
||||
if (errors.length > 1) throw new AggregateError(errors, 'Failed to write or publish the SSO config');
|
||||
return this.getSsoConfig({includeSecret: true});
|
||||
}
|
||||
|
||||
private async setRegistrationUrls(registrationUrls: Array<InstanceRegistrationUrl>): Promise<void> {
|
||||
const validated = validateStoredCollection(StoredRegistrationUrlSchema, registrationUrls, 'registration URLs');
|
||||
await this.setConfig(REGISTRATION_URLS_KEY, JSON.stringify(validated));
|
||||
}
|
||||
|
||||
private async setPendingRegistrations(pendingRegistrations: Array<InstancePendingRegistration>): Promise<void> {
|
||||
const validated = validateStoredCollection(
|
||||
StoredPendingRegistrationSchema,
|
||||
pendingRegistrations,
|
||||
'pending registrations',
|
||||
);
|
||||
await this.setConfig(REGISTRATION_PENDING_APPROVALS_KEY, JSON.stringify(validated));
|
||||
private async fetchRegistrationUrlDefinitions(): Promise<Array<InstanceRegistrationUrl>> {
|
||||
const raw = await this.fetchConfigFromDatabase(REGISTRATION_URLS_KEY);
|
||||
return parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs');
|
||||
}
|
||||
|
||||
private hashRegistrationUrlCode(code: string): string {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type {PushServiceDeliveryConfig} from '@fluxer/schema/src/domains/admin/PushServiceDeliverySchemas';
|
||||
import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
export const PUSH_SERVICE_DELIVERY_CONFIG_NATS_SUBJECT = 'config.push.delivery';
|
||||
|
||||
interface PushServiceDeliveryConfigNatsMessage {
|
||||
type: 'push_service_delivery_config';
|
||||
config: PushServiceDeliveryConfig;
|
||||
}
|
||||
|
||||
export class PushServiceDeliveryConfigPublisher {
|
||||
constructor(private readonly connectionManager: INatsConnectionManager) {}
|
||||
|
||||
async publish(config: PushServiceDeliveryConfig): Promise<void> {
|
||||
if (this.connectionManager.isClosed()) {
|
||||
await this.connectionManager.connect();
|
||||
}
|
||||
const connection = this.connectionManager.getConnection();
|
||||
const message: PushServiceDeliveryConfigNatsMessage = {
|
||||
type: 'push_service_delivery_config',
|
||||
config,
|
||||
};
|
||||
connection.publish(PUSH_SERVICE_DELIVERY_CONFIG_NATS_SUBJECT, textEncoder.encode(JSON.stringify(message)));
|
||||
await connection.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {getKvMeta} from '@app/api/database/CassandraMetaRegistry';
|
||||
import type {CassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
|
||||
import type {CassandraParams, KvQueryMeta, PreparedQuery} from '@app/api/database/CassandraTypes';
|
||||
import type {InstanceConfigurationRow} from '@app/api/database/types/InstanceConfigTypes';
|
||||
import {InstanceConfiguration} from '@app/api/Tables';
|
||||
|
||||
type InstanceConfigWriteEvent = 'read' | 'write' | 'write rejected';
|
||||
|
||||
interface WriteGate {
|
||||
size: number;
|
||||
paused: Array<() => void>;
|
||||
}
|
||||
|
||||
const FETCH_ROW_QUERY = InstanceConfiguration.selectCql({
|
||||
where: InstanceConfiguration.where.eq('key'),
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
export class InstanceConfigWriteRaceExecutor implements CassandraQueryExecutorForTesting {
|
||||
readonly events: Array<InstanceConfigWriteEvent> = [];
|
||||
private watchedKey: string | null = null;
|
||||
private gate: WriteGate | null = null;
|
||||
private beforeEachWrite: (() => Promise<void>) | null = null;
|
||||
|
||||
constructor(private readonly base: CassandraQueryExecutorForTesting) {}
|
||||
|
||||
watch(key: string): void {
|
||||
this.watchedKey = key;
|
||||
this.events.length = 0;
|
||||
}
|
||||
|
||||
pauseWritesUntil(size: number): void {
|
||||
this.gate = {size, paused: []};
|
||||
}
|
||||
|
||||
competeBeforeEachWrite(write: () => Promise<void>): void {
|
||||
this.beforeEachWrite = write;
|
||||
}
|
||||
|
||||
async writeDirectly(key: string, value: string): Promise<void> {
|
||||
await this.base.executeQuery(InstanceConfiguration.upsertAll({key, value, updated_at: new Date()}));
|
||||
}
|
||||
|
||||
async readDirectly(key: string): Promise<string | null> {
|
||||
const [row] = await this.base.executeQuery<InstanceConfigurationRow>({cql: FETCH_ROW_QUERY, params: {key}});
|
||||
return row?.value ?? null;
|
||||
}
|
||||
|
||||
async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(
|
||||
query: PreparedQuery<P>,
|
||||
): Promise<Array<T>> {
|
||||
const meta = query.kvMeta ?? getKvMeta(query.cql);
|
||||
if (this.watchedKey === null || !this.isWatched(meta, query.params)) {
|
||||
return this.base.executeQuery<T, P>(query);
|
||||
}
|
||||
if (meta?.action === 'select') {
|
||||
this.events.push('read');
|
||||
return this.base.executeQuery<T, P>(query);
|
||||
}
|
||||
await this.passGate();
|
||||
await this.beforeEachWrite?.();
|
||||
const rows = await this.base.executeQuery<T, P>(query);
|
||||
const applied = (rows[0] as {'[applied]'?: unknown} | undefined)?.['[applied]'];
|
||||
this.events.push(applied === false ? 'write rejected' : 'write');
|
||||
return rows;
|
||||
}
|
||||
|
||||
executeBatch(queries: Array<{query: string; params: object; meta?: KvQueryMeta}>, atomic?: boolean): Promise<void> {
|
||||
return this.base.executeBatch(queries, atomic);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.base.reset?.();
|
||||
this.watchedKey = null;
|
||||
this.gate = null;
|
||||
this.beforeEachWrite = null;
|
||||
this.events.length = 0;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
await this.base.shutdown?.();
|
||||
}
|
||||
|
||||
private isWatched(meta: KvQueryMeta | null | undefined, params: CassandraParams): boolean {
|
||||
return meta?.table.name === InstanceConfiguration.name && params.key === this.watchedKey;
|
||||
}
|
||||
|
||||
private async passGate(): Promise<void> {
|
||||
const gate = this.gate;
|
||||
if (gate === null) return;
|
||||
await new Promise<void>((release) => {
|
||||
gate.paused.push(release);
|
||||
if (gate.paused.length < gate.size) return;
|
||||
this.gate = null;
|
||||
for (const release of gate.paused) release();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ interface RequireClientIpOptions {
|
||||
|
||||
const defaultExemptPaths: Array<string> = [
|
||||
'/_health',
|
||||
'/internal',
|
||||
'/webhooks/livekit',
|
||||
'/test',
|
||||
'/connections/bluesky/client-metadata.json',
|
||||
|
||||
@@ -51,6 +51,7 @@ import {createUsersServiceClient} from '@app/api/infrastructure/UsersServiceClie
|
||||
import {VirusScanService} from '@app/api/infrastructure/VirusScanService';
|
||||
import {GatewayRolloutConfigPublisher} from '@app/api/instance/GatewayRolloutConfigPublisher';
|
||||
import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
|
||||
import {PushServiceDeliveryConfigPublisher} from '@app/api/instance/PushServiceDeliveryConfigPublisher';
|
||||
import {InviteRepository} from '@app/api/invite/InviteRepository';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import {LimitConfigService} from '@app/api/limits/LimitConfigService';
|
||||
@@ -155,6 +156,18 @@ export const getGatewayRolloutConfigPublisher = singleton(
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const getPushServiceDeliveryConfigPublisher = singleton(
|
||||
() =>
|
||||
new PushServiceDeliveryConfigPublisher(
|
||||
new NatsConnectionManager({
|
||||
url: Config.nats.coreUrl,
|
||||
token: Config.nats.authToken || undefined,
|
||||
name: 'fluxer-api-push-service-delivery-config',
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const getVisionarySlotRepository = singleton(() => new VisionarySlotRepository());
|
||||
export const getCacheService: () => ICacheService = singleton(() => new KVCacheProvider({client: getKVClient()}));
|
||||
export const getRateLimitService = singleton(() => new RateLimitService(getKVClient()));
|
||||
|
||||
@@ -5,7 +5,7 @@ import {Logger} from '@app/api/Logger';
|
||||
import {hashAuthToken, recordAbuseSignal} from '@app/api/middleware/AbusiveIpAutoBanner';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import type {HonoEnv} from '@app/api/types/HonoEnv';
|
||||
import {requireRequestClientIp} from '@app/api/utils/RequestClientIp';
|
||||
import {getRequestClientIp} from '@app/api/utils/RequestClientIp';
|
||||
import {stripApiPrefix} from '@app/api/utils/RequestPathUtils';
|
||||
import type {Context} from 'hono';
|
||||
import {createMiddleware} from 'hono/factory';
|
||||
@@ -60,7 +60,7 @@ function setUserInContext(ctx: Context<HonoEnv>, user: User, trackActivity: bool
|
||||
ctx.set('user', user);
|
||||
if (trackActivity) {
|
||||
const now = new Date();
|
||||
const ip = requireRequestClientIp(ctx);
|
||||
const ip = getRequestClientIp(ctx);
|
||||
const kvActivityTracker = ctx.get('kvActivityTracker');
|
||||
const userActivityBuffer = ctx.get('userActivityBuffer');
|
||||
userActivityBuffer.recordActivity(user.id, now, ip);
|
||||
@@ -77,7 +77,7 @@ export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
|
||||
}
|
||||
const rawAuthHeader = ctx.req.header('Authorization');
|
||||
const parsed = parseAuthHeader(rawAuthHeader);
|
||||
const resolvedClientIp = requireRequestClientIp(ctx);
|
||||
const resolvedClientIp = getRequestClientIp(ctx);
|
||||
ctx.set('oauthBearerToken', undefined);
|
||||
ctx.set('oauthBearerApplicationId', undefined);
|
||||
ctx.set('oauthBearerAllowed', false);
|
||||
|
||||
@@ -22,6 +22,7 @@ function createHarness(path = 'http://localhost/v1/messages'): Harness {
|
||||
return ctx.text('ok');
|
||||
});
|
||||
app.get('/_health', (ctx) => ctx.text('OK'));
|
||||
app.get('/internal/rpc', (ctx) => ctx.text('OK'));
|
||||
app.onError(AppErrorHandler);
|
||||
return {
|
||||
request: async (headers) => app.request(path, {headers}),
|
||||
@@ -80,6 +81,12 @@ describe('RequireClientIpMiddleware', () => {
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('leaves internal service to service calls alone', async () => {
|
||||
const harness = createHarness('http://localhost/internal/rpc');
|
||||
const response = await harness.request({});
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('passes every request through in test mode', async () => {
|
||||
Config.dev.testModeEnabled = true;
|
||||
const harness = createHarness();
|
||||
|
||||
@@ -17030,7 +17030,7 @@
|
||||
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
|
||||
}
|
||||
},
|
||||
"description": "Registers a mobile push device token for APNs, Firebase Cloud Messaging, or UnifiedPush. UnifiedPush registrations include the endpoint URL plus Web Push encryption keys.",
|
||||
"description": "Registers a mobile push device for APNs, Firebase Cloud Messaging, or UnifiedPush. A Web Push registration sends the endpoint URL with encryption_key and auth_secret. A raw registration sends the platform push token with no keys.",
|
||||
"security": [{"sessionToken": []}],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
@@ -22735,16 +22735,20 @@
|
||||
"properties": {
|
||||
"platform": {
|
||||
"description": "The mobile push notification platform",
|
||||
"x-enumNames": ["ANDROID_FCM", "IOS_APNS", "ANDROID_UNIFIED_PUSH"],
|
||||
"x-enumNames": ["ANDROID_FCM", "IOS_APNS", "IOS_APNS_VOIP", "ANDROID_UNIFIED_PUSH"],
|
||||
"x-enumDescriptions": [
|
||||
"Firebase Cloud Messaging (Android)",
|
||||
"Apple Push Notification Service (iOS)",
|
||||
"Apple PushKit VoIP push, used only to ring an incoming call (iOS)",
|
||||
"UnifiedPush (Android without Google services)"
|
||||
],
|
||||
"enum": ["android_fcm", "ios_apns", "android_unified_push"],
|
||||
"enum": ["android_fcm", "ios_apns", "ios_apns_voip", "android_unified_push"],
|
||||
"type": "string"
|
||||
},
|
||||
"token": {
|
||||
"description": "The Web Push endpoint URL or raw platform push token used at registration",
|
||||
"type": "string"
|
||||
},
|
||||
"token": {"description": "The platform-specific push notification token to unregister", "type": "string"},
|
||||
"app_id": {
|
||||
"description": "Client app channel or bundle mapping identifier, such as stable, beta, or canary",
|
||||
"type": "string"
|
||||
@@ -22799,16 +22803,20 @@
|
||||
"properties": {
|
||||
"platform": {
|
||||
"description": "The mobile push notification platform",
|
||||
"x-enumNames": ["ANDROID_FCM", "IOS_APNS", "ANDROID_UNIFIED_PUSH"],
|
||||
"x-enumNames": ["ANDROID_FCM", "IOS_APNS", "IOS_APNS_VOIP", "ANDROID_UNIFIED_PUSH"],
|
||||
"x-enumDescriptions": [
|
||||
"Firebase Cloud Messaging (Android)",
|
||||
"Apple Push Notification Service (iOS)",
|
||||
"Apple PushKit VoIP push, used only to ring an incoming call (iOS)",
|
||||
"UnifiedPush (Android without Google services)"
|
||||
],
|
||||
"enum": ["android_fcm", "ios_apns", "android_unified_push"],
|
||||
"enum": ["android_fcm", "ios_apns", "ios_apns_voip", "android_unified_push"],
|
||||
"type": "string"
|
||||
},
|
||||
"token": {
|
||||
"description": "The Web Push endpoint URL when encryption keys are supplied, otherwise the raw platform push token",
|
||||
"type": "string"
|
||||
},
|
||||
"token": {"description": "The platform-specific push notification token or endpoint URL", "type": "string"},
|
||||
"user_agent": {"description": "The user agent string identifying the device", "type": "string"},
|
||||
"app_id": {
|
||||
"description": "Client app channel or bundle mapping identifier, such as stable, beta, or canary",
|
||||
@@ -22825,11 +22833,11 @@
|
||||
"type": "string"
|
||||
},
|
||||
"encryption_key": {
|
||||
"description": "The P-256 ECDH public key for UnifiedPush encryption (base64url)",
|
||||
"description": "The P-256 ECDH public key for Web Push encryption (base64url)",
|
||||
"type": "string"
|
||||
},
|
||||
"auth_secret": {
|
||||
"description": "The authentication secret for UnifiedPush encryption (base64url)",
|
||||
"description": "The authentication secret for Web Push encryption (base64url)",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
@@ -27182,8 +27190,7 @@
|
||||
"assignments": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionAssignmentResponse"},
|
||||
"screen_share_delivery": {"$ref": "#/components/schemas/ScreenShareDeliveryAssignmentResponse"}
|
||||
"voice_noise_suppression": {"$ref": "#/components/schemas/VoiceNoiseSuppressionAssignmentResponse"}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -30687,12 +30694,6 @@
|
||||
"additionalProperties": false
|
||||
},
|
||||
"DonationCurrency": {"type": "string", "enum": ["usd", "eur", "brl", "inr", "pln", "try", "sek", "dkk", "nok"]},
|
||||
"ScreenShareDeliveryAssignmentResponse": {
|
||||
"type": "object",
|
||||
"properties": {"enabled": {"type": "boolean"}},
|
||||
"required": ["enabled"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"VoiceNoiseSuppressionAssignmentResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -204,9 +204,7 @@ function buildApnsPayload(payload: Record<string, unknown>): Record<string, unkn
|
||||
if (badge !== undefined) {
|
||||
aps.badge = badge;
|
||||
}
|
||||
if (imageUrl) {
|
||||
aps['mutable-content'] = 1;
|
||||
}
|
||||
aps['mutable-content'] = 1;
|
||||
return {
|
||||
...data,
|
||||
title,
|
||||
|
||||
@@ -139,7 +139,7 @@ describe('ApnsPushService', () => {
|
||||
notification: {title: 'Alice', body: 'Hello', icon: 'https://cdn.example/avatar.png'},
|
||||
});
|
||||
expect(payload.image_url).toBeUndefined();
|
||||
expect(payload.aps).not.toHaveProperty('mutable-content');
|
||||
expect(payload.aps).toHaveProperty('mutable-content', 1);
|
||||
expect(payload.author_avatar_url).toBe('https://cdn.example/avatar.png');
|
||||
});
|
||||
it('imports the APNs signing key once per PEM and rejects a truncated one every time', async () => {
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {Config} from '@app/api/Config';
|
||||
import {PHONE_REQUIREMENT_FLAGS, SuspiciousActivityFlags} from '@fluxer/constants/src/UserConstants';
|
||||
|
||||
const EMAIL_ONLY_EQUIVALENTS: ReadonlyArray<readonly [number, number]> = [
|
||||
[SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL_OR_VERIFIED_PHONE, SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL],
|
||||
[SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL_OR_REVERIFIED_PHONE, SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL],
|
||||
[
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL_OR_VERIFIED_PHONE,
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL,
|
||||
],
|
||||
[
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL_OR_REVERIFIED_PHONE,
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL,
|
||||
],
|
||||
];
|
||||
|
||||
const PHONE_OFFERING_FLAGS = EMAIL_ONLY_EQUIVALENTS.reduce((mask, [either]) => mask | either, PHONE_REQUIREMENT_FLAGS);
|
||||
|
||||
function withoutPhoneOfferingFlags(flagBits: number): number {
|
||||
return EMAIL_ONLY_EQUIVALENTS.reduce(
|
||||
(next, [either, emailOnly]) => ((flagBits & either) !== 0 ? next | emailOnly : next),
|
||||
flagBits & ~PHONE_OFFERING_FLAGS,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeCountryCode(countryCode: string | null | undefined): string | null {
|
||||
const trimmed = countryCode?.trim();
|
||||
@@ -17,6 +40,25 @@ export function countryRequiresInboundPhoneVerification(countryCode: string | nu
|
||||
return configuredCountrySet(Config.abusePolicy.inboundPhoneCountryCodes).has(normalized);
|
||||
}
|
||||
|
||||
export function phoneFlaggingAllowedForCountry(countryCode: string | null | undefined): boolean {
|
||||
const {enabled, exemptCountryCodes} = Config.abusePolicy.phoneFlagging;
|
||||
if (!enabled) return false;
|
||||
const normalized = normalizeCountryCode(countryCode);
|
||||
if (!normalized) return true;
|
||||
return !configuredCountrySet(exemptCountryCodes).has(normalized);
|
||||
}
|
||||
|
||||
export async function stripDisallowedPhoneFlags(
|
||||
flagBits: number,
|
||||
resolveCountryCode: () => Promise<string | null>,
|
||||
): Promise<number> {
|
||||
if ((flagBits & PHONE_OFFERING_FLAGS) === 0) return flagBits;
|
||||
const {enabled, exemptCountryCodes} = Config.abusePolicy.phoneFlagging;
|
||||
if (enabled && exemptCountryCodes.length === 0) return flagBits;
|
||||
if (enabled && phoneFlaggingAllowedForCountry(await resolveCountryCode())) return flagBits;
|
||||
return withoutPhoneOfferingFlags(flagBits);
|
||||
}
|
||||
|
||||
export function phoneRequiresInboundVerification(
|
||||
phone: string,
|
||||
prefixes: ReadonlyArray<string> = Config.abusePolicy.phoneVerification.inboundRequiredPrefixes,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {Config} from '@app/api/Config';
|
||||
import {phoneFlaggingAllowedForCountry, stripDisallowedPhoneFlags} from '@app/api/risk/AbusePolicy';
|
||||
import {SuspiciousActivityFlags} from '@fluxer/constants/src/UserConstants';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
const PHONE_AND_EMAIL =
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL |
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_PHONE |
|
||||
SuspiciousActivityFlags.REQUIRE_INBOUND_PHONE_VERIFICATION;
|
||||
|
||||
describe('phone flagging policy', () => {
|
||||
const original = {...Config.abusePolicy.phoneFlagging};
|
||||
|
||||
beforeEach(() => {
|
||||
Config.abusePolicy.phoneFlagging = {enabled: true, exemptCountryCodes: []};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Config.abusePolicy.phoneFlagging = original;
|
||||
});
|
||||
|
||||
it('keeps phone flags by default without resolving the country', async () => {
|
||||
const resolveCountryCode = vi.fn(async () => 'NG');
|
||||
expect(await stripDisallowedPhoneFlags(PHONE_AND_EMAIL, resolveCountryCode)).toBe(PHONE_AND_EMAIL);
|
||||
expect(resolveCountryCode).not.toHaveBeenCalled();
|
||||
expect(phoneFlaggingAllowedForCountry('NG')).toBe(true);
|
||||
});
|
||||
|
||||
it('strips only phone flags when disabled', async () => {
|
||||
Config.abusePolicy.phoneFlagging = {enabled: false, exemptCountryCodes: []};
|
||||
const resolveCountryCode = vi.fn(async () => 'NG');
|
||||
expect(await stripDisallowedPhoneFlags(PHONE_AND_EMAIL, resolveCountryCode)).toBe(
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL,
|
||||
);
|
||||
expect(resolveCountryCode).not.toHaveBeenCalled();
|
||||
expect(phoneFlaggingAllowedForCountry('NG')).toBe(false);
|
||||
expect(phoneFlaggingAllowedForCountry(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('strips phone flags for exempt countries only', async () => {
|
||||
Config.abusePolicy.phoneFlagging = {enabled: true, exemptCountryCodes: [' br', 'PT']};
|
||||
expect(await stripDisallowedPhoneFlags(PHONE_AND_EMAIL, async () => 'BR')).toBe(
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL,
|
||||
);
|
||||
expect(await stripDisallowedPhoneFlags(PHONE_AND_EMAIL, async () => 'ng')).toBe(PHONE_AND_EMAIL);
|
||||
expect(await stripDisallowedPhoneFlags(PHONE_AND_EMAIL, async () => null)).toBe(PHONE_AND_EMAIL);
|
||||
expect(phoneFlaggingAllowedForCountry('pt')).toBe(false);
|
||||
expect(phoneFlaggingAllowedForCountry('NG')).toBe(true);
|
||||
});
|
||||
|
||||
it('replaces email or phone flags with their email only equivalent', async () => {
|
||||
Config.abusePolicy.phoneFlagging = {enabled: false, exemptCountryCodes: []};
|
||||
expect(
|
||||
await stripDisallowedPhoneFlags(
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL_OR_VERIFIED_PHONE |
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL_OR_REVERIFIED_PHONE,
|
||||
async () => null,
|
||||
),
|
||||
).toBe(SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL);
|
||||
expect(
|
||||
await stripDisallowedPhoneFlags(
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL_OR_VERIFIED_PHONE |
|
||||
SuspiciousActivityFlags.REQUIRE_INBOUND_PHONE_VERIFICATION,
|
||||
async () => null,
|
||||
),
|
||||
).toBe(SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL);
|
||||
Config.abusePolicy.phoneFlagging = {enabled: true, exemptCountryCodes: ['BR']};
|
||||
expect(
|
||||
await stripDisallowedPhoneFlags(
|
||||
SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL_OR_REVERIFIED_PHONE,
|
||||
async () => 'BR',
|
||||
),
|
||||
).toBe(SuspiciousActivityFlags.REQUIRE_REVERIFIED_EMAIL);
|
||||
});
|
||||
|
||||
it('skips the country lookup when no phone flags are present', async () => {
|
||||
Config.abusePolicy.phoneFlagging = {enabled: true, exemptCountryCodes: ['BR']};
|
||||
const resolveCountryCode = vi.fn(async () => 'BR');
|
||||
expect(await stripDisallowedPhoneFlags(SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL, resolveCountryCode)).toBe(
|
||||
SuspiciousActivityFlags.REQUIRE_VERIFIED_EMAIL,
|
||||
);
|
||||
expect(resolveCountryCode).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -97,6 +97,7 @@ import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';
|
||||
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
|
||||
import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
|
||||
import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
|
||||
import {pushServiceDeliveryEnrols} from '@fluxer/schema/src/domains/admin/PushServiceDeliverySchemas';
|
||||
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
|
||||
import type {VoiceStateResponse} from '@fluxer/schema/src/domains/gateway/GatewaySchemas';
|
||||
import type {GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
|
||||
@@ -430,6 +431,13 @@ export class RpcService {
|
||||
}),
|
||||
};
|
||||
case 'send_apns_push': {
|
||||
const deliveryConfig = await this.instanceConfigRepository.getPushServiceDeliveryConfig();
|
||||
if (pushServiceDeliveryEnrols(deliveryConfig, request.user_id.toString())) {
|
||||
Logger.warn(
|
||||
{userId: request.user_id.toString(), configVersion: deliveryConfig.config_version},
|
||||
'push service delivery path mismatch',
|
||||
);
|
||||
}
|
||||
const result = await sendApnsPush({
|
||||
userId: request.user_id.toString(),
|
||||
subscriptionId: request.subscription_id,
|
||||
@@ -635,6 +643,13 @@ export class RpcService {
|
||||
data: {config: rolloutConfig},
|
||||
};
|
||||
}
|
||||
case 'get_push_service_delivery_config': {
|
||||
const config = await this.instanceConfigRepository.getPushServiceDeliveryConfig();
|
||||
return {
|
||||
type: 'get_push_service_delivery_config',
|
||||
data: {config},
|
||||
};
|
||||
}
|
||||
default: {
|
||||
const exhaustiveCheck: never = request;
|
||||
throw new Error(
|
||||
@@ -864,7 +879,7 @@ export class RpcService {
|
||||
if (!queueAllowed) {
|
||||
return;
|
||||
}
|
||||
await this.workerService.addJob('reconcileUserPayments', {userId: userIdString});
|
||||
await this.workerService.addJob('reconcileUserPayments', {userId: userIdString}, {skipLedger: true});
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.warn(
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import {countryRequiresInboundPhoneVerification} from '@app/api/risk/AbusePolicy';
|
||||
import {countryRequiresInboundPhoneVerification, phoneFlaggingAllowedForCountry} from '@app/api/risk/AbusePolicy';
|
||||
import {
|
||||
createRpcTimingNode,
|
||||
RpcTimingRecorder,
|
||||
@@ -311,6 +311,17 @@ export class RpcSessionStartService {
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!timeRpcStepSync(timingSteps, 'check_phone_flagging_allowed', () =>
|
||||
phoneFlaggingAllowedForCountry(geoipCountryIso),
|
||||
)
|
||||
) {
|
||||
Logger.info(
|
||||
{userId: user.id.toString(), countryIso: geoipCountryIso},
|
||||
'Skipping configured-country inbound phone requirement: phone flagging disabled for this country',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
timeRpcStepSync(timingSteps, 'check_not_suspicious_flag', () => (user.flags & UserFlags.NOT_SUSPICIOUS) !== 0n)
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {createTestUserWithPremium} from '@app/api/stripe/tests/StripeWebhookTestUtils';
|
||||
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder} from '@app/api/test/TestRequestBuilder';
|
||||
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
|
||||
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
|
||||
|
||||
describe('RpcService session payment reconciliation', () => {
|
||||
let harness: ApiTestHarness;
|
||||
beforeEach(async () => {
|
||||
harness = await createApiTestHarness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await harness?.shutdown();
|
||||
});
|
||||
test('queues payment reconciliation without a job record', async () => {
|
||||
const account = await createTestUserWithPremium(harness, UserPremiumTypes.SUBSCRIPTION, {
|
||||
stripeCustomerId: 'cus_rpc_session_reconcile',
|
||||
});
|
||||
const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
|
||||
try {
|
||||
await createBuilder(harness, '')
|
||||
.post('/test/rpc-session-init')
|
||||
.body({type: 'session', token: account.token, version: 1, ip: '127.0.0.1'})
|
||||
.expect(HTTP_STATUS.OK)
|
||||
.execute();
|
||||
await vi.waitFor(() =>
|
||||
expect(addJob).toHaveBeenCalledWith('reconcileUserPayments', {userId: account.userId}, {skipLedger: true}),
|
||||
);
|
||||
} finally {
|
||||
addJob.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -52,7 +52,8 @@ function snowflakeSeconds(snowflake: string): number {
|
||||
|
||||
function buildSort(sortBy: string, sortOrder: 'asc' | 'desc' | undefined): Array<string> | undefined {
|
||||
if (sortBy === 'relevance') return undefined;
|
||||
return [`${sortBy}:${sortOrder ?? 'desc'}`, 'id:desc'];
|
||||
const direction = sortOrder ?? 'desc';
|
||||
return [`${sortBy}:${direction}`, `id:${direction}`];
|
||||
}
|
||||
|
||||
function buildTimestampSort(filters: MessageSearchFilters | AuditLogSearchFilters): Array<string> | undefined {
|
||||
|
||||
@@ -117,7 +117,7 @@ describe('MeilisearchMessageAdapter', () => {
|
||||
'(guildId = "guild-1") AND ((channelId = "channel-\\"quoted\\"" OR channelId = "channel-2")) AND (mentionedUserIds = "user-1")',
|
||||
limit: 10,
|
||||
offset: 20,
|
||||
sort: ['createdAt:asc', 'id:desc'],
|
||||
sort: ['createdAt:asc', 'id:asc'],
|
||||
attributesToSearchOn: ['content', 'embedContent'],
|
||||
showRankingScore: false,
|
||||
},
|
||||
|
||||
@@ -19,6 +19,7 @@ import {GuildMemberRepository} from '@app/api/guild/repositories/GuildMemberRepo
|
||||
import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
|
||||
import {GuildRoleRepository} from '@app/api/guild/repositories/GuildRoleRepository';
|
||||
import {
|
||||
type CallCaller,
|
||||
type CallData,
|
||||
type GatewayChannelMention,
|
||||
type GatewayGuildMemoryStats,
|
||||
@@ -925,6 +926,7 @@ export class NoopGatewayService extends IGatewayService {
|
||||
_region: string,
|
||||
_ringing: Array<string>,
|
||||
_recipients: Array<string>,
|
||||
_caller?: CallCaller,
|
||||
): Promise<CallData> {
|
||||
return {
|
||||
channel_id: _channelId.toString(),
|
||||
@@ -940,7 +942,7 @@ export class NoopGatewayService extends IGatewayService {
|
||||
return true;
|
||||
}
|
||||
|
||||
async ringCallRecipients(_channelId: ChannelID, _recipients: Array<string>): Promise<boolean> {
|
||||
async ringCallRecipients(_channelId: ChannelID, _recipients: Array<string>, _caller?: CallCaller): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {Config} from '@app/api/Config';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import {setInjectedAccountPolicyEvaluator} from '@app/api/risk/AccountPolicyService';
|
||||
import {setCachedDeferredPhoneGateEnabled} from '@app/api/risk/DeferredPhoneGateCache';
|
||||
@@ -52,6 +53,20 @@ describe('deferred phone gate marker', () => {
|
||||
});
|
||||
expect(getRequiredActions(user)).toEqual(['REQUIRE_VERIFIED_PHONE']);
|
||||
});
|
||||
it('keeps a deferral suppressed when the gate reads off but phone flagging is disabled', () => {
|
||||
setCachedDeferredPhoneGateEnabled(false);
|
||||
const original = {...Config.abusePolicy.phoneFlagging};
|
||||
Config.abusePolicy.phoneFlagging = {enabled: false, exemptCountryCodes: []};
|
||||
try {
|
||||
const user = createUser({
|
||||
suspiciousActivityFlags: SuspiciousActivityFlags.REQUIRE_VERIFIED_PHONE | DEFERRED_PHONE_ON_COMMUNITY_JOIN,
|
||||
});
|
||||
expect(getRequiredActions(user)).toEqual([]);
|
||||
expect(getEffectiveSuspiciousFlags(user)).toBe(0);
|
||||
} finally {
|
||||
Config.abusePolicy.phoneFlagging = original;
|
||||
}
|
||||
});
|
||||
it('suppresses a deferred phone requirement so the account is not locked out', () => {
|
||||
const user = createUser({
|
||||
suspiciousActivityFlags: SuspiciousActivityFlags.REQUIRE_VERIFIED_PHONE | DEFERRED_PHONE_ON_COMMUNITY_JOIN,
|
||||
|
||||
@@ -134,7 +134,7 @@ function suppressDeferredPhoneFlags(rawFlags: number): number {
|
||||
if ((rawFlags & DEFERRED_PHONE_ON_COMMUNITY_JOIN) === 0) {
|
||||
return rawFlags;
|
||||
}
|
||||
if (getCachedDeferredPhoneGateEnabled() === false) {
|
||||
if (getCachedDeferredPhoneGateEnabled() === false && Config.abusePolicy.phoneFlagging.enabled) {
|
||||
return rawFlags & ~DEFERRED_PHONE_ON_COMMUNITY_JOIN;
|
||||
}
|
||||
return rawFlags & ~DEFERRABLE_PHONE_FLAGS;
|
||||
|
||||
@@ -957,7 +957,7 @@ export function UserAccountController(app: HonoApp) {
|
||||
security: ['bearerToken', 'sessionToken'],
|
||||
tags: ['Users'],
|
||||
description:
|
||||
'Registers a mobile push device token for APNs, Firebase Cloud Messaging, or UnifiedPush. UnifiedPush registrations include the endpoint URL plus Web Push encryption keys.',
|
||||
'Registers a mobile push device for APNs, Firebase Cloud Messaging, or UnifiedPush. A Web Push registration sends the endpoint URL with encryption_key and auth_secret. A raw registration sends the platform push token with no keys.',
|
||||
}),
|
||||
async (ctx) => {
|
||||
const authSession = ctx.get('authSession');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import type {UserID} from '@app/api/BrandedTypes';
|
||||
import {Db, type DbOp} from '@app/api/database/CassandraTypes';
|
||||
import type {UserRow} from '@app/api/database/types/UserTypes';
|
||||
import {Logger} from '@app/api/Logger';
|
||||
import {User} from '@app/api/models/User';
|
||||
import {
|
||||
UserDataRepository,
|
||||
@@ -96,7 +97,12 @@ export class UserAccountRepository {
|
||||
return updatedUser;
|
||||
} catch (error) {
|
||||
if (!dataCommitted && emailClaim) {
|
||||
await this.emailOwnershipRepo.abortEmailClaim(emailClaim);
|
||||
await this.emailOwnershipRepo.abortEmailClaim(emailClaim).catch((abortError: unknown) => {
|
||||
Logger.warn(
|
||||
{userId: userId.toString(), abortError},
|
||||
'Failed to abort the email claim of a user write that did not commit',
|
||||
);
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {Logger} from '@app/api/Logger';
|
||||
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
|
||||
import type {AuthSession} from '@app/api/models/AuthSession';
|
||||
import type {User} from '@app/api/models/User';
|
||||
import {stripDisallowedPhoneFlags} from '@app/api/risk/AbusePolicy';
|
||||
import {createAccountPolicyContactContext, type IAccountPolicyEvaluator} from '@app/api/risk/AccountPolicyEvaluator';
|
||||
import type {IRegistrationEventsRepository} from '@app/api/risk/adapters/VelocityAdapter';
|
||||
import type {IRiskHistoryRepository} from '@app/api/risk/HistoricalOutcomeRepository';
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
mapUserToPrivateResponse,
|
||||
mapUserToProfileResponse,
|
||||
} from '@app/api/user/UserMappers';
|
||||
import {lookupGeoip} from '@app/api/utils/IpUtils';
|
||||
import {DEFERRED_PHONE_ON_COMMUNITY_JOIN, imposePhoneRequirements} from '@fluxer/constants/src/UserConstants';
|
||||
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
|
||||
import {getCurrentTimeZoneOffsetMinutes} from '@fluxer/date_utils/src/TimeZoneUtils';
|
||||
@@ -302,7 +304,11 @@ export class UserAccountRequestService {
|
||||
action: emailSetRecommendedAction,
|
||||
},
|
||||
});
|
||||
nextSuspiciousFlags = imposePhoneRequirements(nextSuspiciousFlags, policyDecision.flagBits);
|
||||
const policyFlagBits = await stripDisallowedPhoneFlags(
|
||||
policyDecision.flagBits,
|
||||
async () => (await lookupGeoip(request)).countryCode,
|
||||
);
|
||||
nextSuspiciousFlags = imposePhoneRequirements(nextSuspiciousFlags, policyFlagBits);
|
||||
if (nextSuspiciousFlags !== currentSuspiciousFlags) {
|
||||
user = await this.userRepository.patchUpsert(
|
||||
user.id,
|
||||
|
||||
@@ -104,6 +104,33 @@ function assertPublicPushEndpoint(endpoint: string, fieldName: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function isPushEndpointUrl(token: string): boolean {
|
||||
const normalized = token.trim().toLowerCase();
|
||||
return normalized.startsWith('https://') || normalized.startsWith('http://');
|
||||
}
|
||||
|
||||
function resolveMobileWebPushKeys(device: RegisterMobileDeviceRequest): {p256dh: string; auth: string} | null {
|
||||
const p256dh = device.encryption_key;
|
||||
const auth = device.auth_secret;
|
||||
if (p256dh && auth) return {p256dh, auth};
|
||||
if (p256dh || auth) {
|
||||
throw InputValidationError.create(
|
||||
p256dh ? 'auth_secret' : 'encryption_key',
|
||||
'Web Push registrations require encryption_key and auth_secret',
|
||||
);
|
||||
}
|
||||
if (device.platform === 'android_unified_push' || device.platform === 'ios_apns_voip') {
|
||||
throw InputValidationError.create(
|
||||
'encryption_key',
|
||||
'Web Push registrations require encryption_key and auth_secret',
|
||||
);
|
||||
}
|
||||
if (isPushEndpointUrl(device.token)) {
|
||||
throw InputValidationError.create('token', 'Endpoint URL registrations require encryption_key and auth_secret');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeMobileAppId(appId: string | undefined): string {
|
||||
const normalized = appId?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : DEFAULT_MOBILE_APP_ID;
|
||||
@@ -114,7 +141,7 @@ function normalizeProviderEnvironment(
|
||||
environment: RegisterMobileDeviceRequest['provider_environment'],
|
||||
): string | null {
|
||||
if (environment) return environment;
|
||||
return platform === 'ios_apns' ? DEFAULT_APNS_PROVIDER_ENVIRONMENT : null;
|
||||
return platform === 'ios_apns' || platform === 'ios_apns_voip' ? DEFAULT_APNS_PROVIDER_ENVIRONMENT : null;
|
||||
}
|
||||
|
||||
const isUnreachableEntityError = (error: unknown): boolean =>
|
||||
@@ -400,7 +427,8 @@ export class UserContentService {
|
||||
|
||||
async registerMobileDevice(params: RegisterMobileDeviceParams): Promise<PushSubscription> {
|
||||
const {userId, authSessionIdHash, device} = params;
|
||||
if (device.platform === 'android_unified_push') {
|
||||
const webPushKeys = resolveMobileWebPushKeys(device);
|
||||
if (webPushKeys) {
|
||||
assertPublicPushEndpoint(device.token, 'token');
|
||||
}
|
||||
const appId = normalizeMobileAppId(device.app_id);
|
||||
@@ -411,8 +439,8 @@ export class UserContentService {
|
||||
subscription_id: subscriptionId,
|
||||
auth_session_id_hash: authSessionIdHash ?? null,
|
||||
endpoint: device.token,
|
||||
p256dh_key: device.platform === 'android_unified_push' ? (device.encryption_key ?? null) : null,
|
||||
auth_key: device.platform === 'android_unified_push' ? (device.auth_secret ?? null) : null,
|
||||
p256dh_key: webPushKeys?.p256dh ?? null,
|
||||
auth_key: webPushKeys?.auth ?? null,
|
||||
user_agent: device.user_agent ?? null,
|
||||
platform: device.platform,
|
||||
app_id: appId,
|
||||
|
||||
@@ -43,7 +43,10 @@ describe('HarvestDownloadToken', () => {
|
||||
|
||||
test('rejects a tampered signature', () => {
|
||||
const token = signHarvestDownloadToken(payload(), SECRET);
|
||||
expect(verifyHarvestDownloadToken(`${token.slice(0, -2)}xy`, SECRET)).toBeNull();
|
||||
const [encoded, signature] = token.split('.');
|
||||
const tampered = Buffer.from(signature as string, 'base64url');
|
||||
tampered[0] = (tampered[0] as number) ^ 0x01;
|
||||
expect(verifyHarvestDownloadToken(`${encoded}.${tampered.toString('base64url')}`, SECRET)).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects malformed input', () => {
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
loginAccount,
|
||||
logoutSpecificSessions,
|
||||
} from '@app/api/auth/tests/AuthTestUtils';
|
||||
import {createUserID} from '@app/api/BrandedTypes';
|
||||
import type {PushSubscription} from '@app/api/models/PushSubscription';
|
||||
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
|
||||
import {HTTP_STATUS} from '@app/api/test/TestConstants';
|
||||
import {createBuilder} from '@app/api/test/TestRequestBuilder';
|
||||
import {PushSubscriptionRepository} from '@app/api/user/repositories/PushSubscriptionRepository';
|
||||
import {
|
||||
deleteMobileDevice,
|
||||
deletePushSubscription,
|
||||
@@ -21,6 +24,15 @@ import {
|
||||
import type {AuthSessionResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';
|
||||
import {beforeEach, describe, expect, test} from 'vitest';
|
||||
|
||||
async function findStoredSubscription(userId: string, subscriptionId: string): Promise<PushSubscription> {
|
||||
const subscriptions = await new PushSubscriptionRepository().listPushSubscriptions(createUserID(BigInt(userId)));
|
||||
const subscription = subscriptions.find((entry) => entry.subscriptionId === subscriptionId);
|
||||
if (!subscription) {
|
||||
throw new Error(`Stored push subscription ${subscriptionId} not found`);
|
||||
}
|
||||
return subscription;
|
||||
}
|
||||
|
||||
describe('Push Subscription Lifecycle', () => {
|
||||
let harness: ApiTestHarness;
|
||||
beforeEach(async () => {
|
||||
@@ -144,6 +156,285 @@ describe('Push Subscription Lifecycle', () => {
|
||||
expect(mobileDevices.devices[0].device_id).toBe(registered.device_id);
|
||||
expect(mobileDevices.devices[0].platform).toBe('android_unified_push');
|
||||
});
|
||||
test('APNs Web Push registration stores the endpoint and encryption keys', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const endpoint = 'https://relay.example.com/apns/device-1';
|
||||
const registered = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: endpoint,
|
||||
encryption_key: 'relay-p256dh-key',
|
||||
auth_secret: 'relay-auth-secret',
|
||||
app_id: 'stable',
|
||||
});
|
||||
const subscription = await findStoredSubscription(account.userId, registered.device_id);
|
||||
expect(subscription.platform).toBe('ios_apns');
|
||||
expect(subscription.endpoint).toBe(endpoint);
|
||||
expect(subscription.p256dhKey).toBe('relay-p256dh-key');
|
||||
expect(subscription.authKey).toBe('relay-auth-secret');
|
||||
});
|
||||
test('FCM Web Push registration stores the endpoint and encryption keys', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const endpoint = 'https://relay.example.com/fcm/device-1';
|
||||
const registered = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'android_fcm',
|
||||
token: endpoint,
|
||||
encryption_key: 'fcm-relay-p256dh-key',
|
||||
auth_secret: 'fcm-relay-auth-secret',
|
||||
});
|
||||
const subscription = await findStoredSubscription(account.userId, registered.device_id);
|
||||
expect(subscription.platform).toBe('android_fcm');
|
||||
expect(subscription.endpoint).toBe(endpoint);
|
||||
expect(subscription.p256dhKey).toBe('fcm-relay-p256dh-key');
|
||||
expect(subscription.authKey).toBe('fcm-relay-auth-secret');
|
||||
});
|
||||
test('raw token registration stores the token without encryption keys', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const registered = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: '0123456789abcdef',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
const subscription = await findStoredSubscription(account.userId, registered.device_id);
|
||||
expect(subscription.platform).toBe('ios_apns');
|
||||
expect(subscription.endpoint).toBe('0123456789abcdef');
|
||||
expect(subscription.p256dhKey).toBeNull();
|
||||
expect(subscription.authKey).toBeNull();
|
||||
});
|
||||
test('Web Push and raw token registrations coexist for one platform', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const rawDevice = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'android_fcm',
|
||||
token: 'fcm-legacy-token',
|
||||
});
|
||||
const webPushDevice = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'android_fcm',
|
||||
token: 'https://relay.example.com/fcm/device-2',
|
||||
encryption_key: 'coexist-p256dh-key',
|
||||
auth_secret: 'coexist-auth-secret',
|
||||
});
|
||||
expect(rawDevice.device_id).not.toBe(webPushDevice.device_id);
|
||||
const rawSubscription = await findStoredSubscription(account.userId, rawDevice.device_id);
|
||||
const webPushSubscription = await findStoredSubscription(account.userId, webPushDevice.device_id);
|
||||
expect(rawSubscription.p256dhKey).toBeNull();
|
||||
expect(rawSubscription.authKey).toBeNull();
|
||||
expect(webPushSubscription.p256dhKey).toBe('coexist-p256dh-key');
|
||||
expect(webPushSubscription.authKey).toBe('coexist-auth-secret');
|
||||
const mobileDevices = await listMobileDevices(harness, account.token);
|
||||
expect(mobileDevices.devices).toHaveLength(2);
|
||||
});
|
||||
test('endpoint registration without encryption keys is rejected', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'ios_apns',
|
||||
token: 'https://relay.example.com/apns/no-keys',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
});
|
||||
test('endpoint registration with only one encryption key is rejected', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'android_fcm',
|
||||
token: 'https://relay.example.com/fcm/half-keys',
|
||||
encryption_key: 'half-p256dh-key',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
});
|
||||
test('raw token registration with encryption keys is rejected', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'ios_apns',
|
||||
token: '0123456789abcdef',
|
||||
encryption_key: 'raw-p256dh-key',
|
||||
auth_secret: 'raw-auth-secret',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
});
|
||||
test('Web Push registration rejects an endpoint that is not publicly routable', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const response = await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'ios_apns',
|
||||
token: 'https://127.0.0.1/apns/device',
|
||||
encryption_key: 'local-p256dh-key',
|
||||
auth_secret: 'local-auth-secret',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
expect(JSON.stringify(response)).toContain('URL_NOT_PUBLICLY_ROUTABLE');
|
||||
});
|
||||
test('unregister removes a Web Push mobile registration', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const endpoint = 'https://relay.example.com/apns/unregister';
|
||||
await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: endpoint,
|
||||
encryption_key: 'unregister-p256dh-key',
|
||||
auth_secret: 'unregister-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
await unregisterMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: endpoint,
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
const mobileDevices = await listMobileDevices(harness, account.token);
|
||||
expect(mobileDevices.devices).toHaveLength(0);
|
||||
});
|
||||
test('VoIP registration stores the PushKit endpoint and encryption keys', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const endpoint = 'https://relay.example.com/apns-voip/device-1';
|
||||
const registered = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: endpoint,
|
||||
encryption_key: 'voip-p256dh-key',
|
||||
auth_secret: 'voip-auth-secret',
|
||||
app_id: 'stable',
|
||||
});
|
||||
const subscription = await findStoredSubscription(account.userId, registered.device_id);
|
||||
expect(subscription.platform).toBe('ios_apns_voip');
|
||||
expect(subscription.endpoint).toBe(endpoint);
|
||||
expect(subscription.p256dhKey).toBe('voip-p256dh-key');
|
||||
expect(subscription.authKey).toBe('voip-auth-secret');
|
||||
});
|
||||
test('VoIP registration defaults to the production provider environment', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const registered = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: 'https://relay.example.com/apns-voip/default-environment',
|
||||
encryption_key: 'voip-default-environment-p256dh-key',
|
||||
auth_secret: 'voip-default-environment-auth-secret',
|
||||
});
|
||||
const subscription = await findStoredSubscription(account.userId, registered.device_id);
|
||||
expect(subscription.providerEnvironment).toBe('production');
|
||||
});
|
||||
test('VoIP registration without encryption keys is rejected', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'ios_apns_voip',
|
||||
token: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
});
|
||||
test('VoIP registration with only one encryption key is rejected', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await createBuilder(harness, account.token)
|
||||
.post('/users/@me/mobile-devices')
|
||||
.body({
|
||||
platform: 'ios_apns_voip',
|
||||
token: 'https://relay.example.com/apns-voip/half-keys',
|
||||
encryption_key: 'voip-half-p256dh-key',
|
||||
})
|
||||
.expect(HTTP_STATUS.BAD_REQUEST)
|
||||
.execute();
|
||||
});
|
||||
test('VoIP and standard APNs registrations coexist as separate devices', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const standard = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: 'https://relay.example.com/apns/paired-device',
|
||||
encryption_key: 'paired-apns-p256dh-key',
|
||||
auth_secret: 'paired-apns-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
const voip = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: 'https://relay.example.com/apns-voip/paired-device',
|
||||
encryption_key: 'paired-voip-p256dh-key',
|
||||
auth_secret: 'paired-voip-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
expect(voip.device_id).not.toBe(standard.device_id);
|
||||
const mobileDevices = await listMobileDevices(harness, account.token);
|
||||
const platforms = mobileDevices.devices.map((device) => device.platform).sort();
|
||||
expect(platforms).toEqual(['ios_apns', 'ios_apns_voip']);
|
||||
});
|
||||
test('platform alone separates device ids for one registration token', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const endpoint = 'https://relay.example.com/apns/shared-token';
|
||||
const standard = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: endpoint,
|
||||
encryption_key: 'shared-p256dh-key',
|
||||
auth_secret: 'shared-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
const voip = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: endpoint,
|
||||
encryption_key: 'shared-p256dh-key',
|
||||
auth_secret: 'shared-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
expect(voip.device_id).not.toBe(standard.device_id);
|
||||
});
|
||||
test('unregister removes only the named VoIP registration', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const voipEndpoint = 'https://relay.example.com/apns-voip/removed-device';
|
||||
const standard = await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns',
|
||||
token: 'https://relay.example.com/apns/kept-device',
|
||||
encryption_key: 'kept-p256dh-key',
|
||||
auth_secret: 'kept-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
await registerMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: voipEndpoint,
|
||||
encryption_key: 'removed-p256dh-key',
|
||||
auth_secret: 'removed-auth-secret',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
await unregisterMobileDevice(harness, account.token, {
|
||||
platform: 'ios_apns_voip',
|
||||
token: voipEndpoint,
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
});
|
||||
const mobileDevices = await listMobileDevices(harness, account.token);
|
||||
expect(mobileDevices.devices).toEqual([
|
||||
{
|
||||
device_id: standard.device_id,
|
||||
platform: 'ios_apns',
|
||||
app_id: 'stable',
|
||||
provider_environment: 'production',
|
||||
user_agent: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
test('mobile Web Push registrations stay out of the web push subscription list', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
await registerMobileDevice(harness, account.token, {
|
||||
platform: 'android_fcm',
|
||||
token: 'https://relay.example.com/fcm/separate',
|
||||
encryption_key: 'separate-p256dh-key',
|
||||
auth_secret: 'separate-auth-secret',
|
||||
});
|
||||
const webSubscriptions = await listPushSubscriptions(harness, account.token);
|
||||
const mobileDevices = await listMobileDevices(harness, account.token);
|
||||
expect(webSubscriptions.subscriptions).toHaveLength(0);
|
||||
expect(mobileDevices.devices).toHaveLength(1);
|
||||
});
|
||||
test('list subscriptions returns multiple subscriptions', async () => {
|
||||
const account = await createTestAccount(harness);
|
||||
const first = await subscribePush(harness, account.token, 'https://push.example.com/multi-1');
|
||||
|
||||
@@ -344,7 +344,7 @@ export async function registerMobileDevice(
|
||||
harness: ApiTestHarness,
|
||||
token: string,
|
||||
body: {
|
||||
platform: 'android_fcm' | 'ios_apns' | 'android_unified_push';
|
||||
platform: 'android_fcm' | 'ios_apns' | 'ios_apns_voip' | 'android_unified_push';
|
||||
token: string;
|
||||
user_agent?: string;
|
||||
app_id?: string;
|
||||
@@ -371,7 +371,7 @@ export async function unregisterMobileDevice(
|
||||
harness: ApiTestHarness,
|
||||
token: string,
|
||||
body: {
|
||||
platform: 'android_fcm' | 'ios_apns' | 'android_unified_push';
|
||||
platform: 'android_fcm' | 'ios_apns' | 'ios_apns_voip' | 'android_unified_push';
|
||||
token: string;
|
||||
app_id?: string;
|
||||
provider_environment?: 'production' | 'development';
|
||||
|
||||
@@ -5,13 +5,18 @@ import * as RegexUtils from '@app/api/utils/RegexUtils';
|
||||
|
||||
let _invitePattern: RegExp | null = null;
|
||||
|
||||
function getInviteEndpointBase(): string {
|
||||
const url = new URL(Config.endpoints.invite);
|
||||
return `${url.hostname}${url.pathname.replace(/\/+$/, '')}`;
|
||||
}
|
||||
|
||||
function getInvitePattern(): RegExp {
|
||||
if (!_invitePattern) {
|
||||
_invitePattern = new RegExp(
|
||||
[
|
||||
'(?:https?:\\/\\/)?',
|
||||
'(?:',
|
||||
`${RegexUtils.escapeRegex(Config.hosts.invite)}(?:\\/#)?\\/(?!invite\\/)([a-zA-Z0-9\\-]{2,32})(?![a-zA-Z0-9\\-])`,
|
||||
`${RegexUtils.escapeRegex(getInviteEndpointBase())}(?:\\/#)?\\/(?!invite\\/)([a-zA-Z0-9\\-]{2,32})(?![a-zA-Z0-9\\-])`,
|
||||
'|',
|
||||
`${RegexUtils.escapeRegex(new URL(Config.endpoints.webApp).hostname)}(?:\\/#)?\\/invite\\/([a-zA-Z0-9\\-]{2,32})(?![a-zA-Z0-9\\-])`,
|
||||
')',
|
||||
|
||||
@@ -8,24 +8,17 @@ import * as InviteUtils from '@app/api/utils/InviteUtils';
|
||||
import {URL_REGEX} from '@fluxer/constants/src/Core';
|
||||
import * as idna from 'idna-uts46-hx';
|
||||
|
||||
const MARKETING_PATH_PREFIXES = ['/channels/', '/theme/'];
|
||||
const CLIENT_ROUTE_PATH_PREFIXES = ['/channels/', '/theme/'];
|
||||
|
||||
interface ExcludedLinkBase {
|
||||
hostname: string;
|
||||
pathPrefix: string;
|
||||
}
|
||||
|
||||
function normalizeHostname(hostname: string | undefined) {
|
||||
return hostname?.trim().toLowerCase() || '';
|
||||
}
|
||||
|
||||
let _marketingHostname: string | null = null;
|
||||
|
||||
function getMarketingHostname() {
|
||||
if (!_marketingHostname) {
|
||||
_marketingHostname = normalizeHostname(Config.hosts.marketing);
|
||||
}
|
||||
return _marketingHostname;
|
||||
}
|
||||
|
||||
const isMarketingPath = (hostname: string, pathname: string) =>
|
||||
hostname === getMarketingHostname() && MARKETING_PATH_PREFIXES.some((prefix) => pathname.startsWith(prefix));
|
||||
|
||||
function getWebAppHostname() {
|
||||
try {
|
||||
return new URL(Config.endpoints.webApp).hostname;
|
||||
@@ -34,23 +27,32 @@ function getWebAppHostname() {
|
||||
}
|
||||
}
|
||||
|
||||
let _excludedHostnames: Set<string> | null = null;
|
||||
|
||||
function getExcludedHostnames(): Set<string> {
|
||||
if (!_excludedHostnames) {
|
||||
_excludedHostnames = new Set<string>();
|
||||
const addHostname = (hostname: string | undefined) => {
|
||||
const normalized = normalizeHostname(hostname);
|
||||
if (normalized) {
|
||||
_excludedHostnames!.add(normalized);
|
||||
}
|
||||
};
|
||||
addHostname(Config.hosts.invite);
|
||||
addHostname(Config.hosts.gift);
|
||||
Config.hosts.unfurlIgnored.forEach(addHostname);
|
||||
addHostname(getWebAppHostname());
|
||||
function endpointLinkBase(endpoint: string): ExcludedLinkBase | null {
|
||||
try {
|
||||
const url = new URL(endpoint);
|
||||
return {hostname: normalizeHostname(url.hostname), pathPrefix: `${url.pathname.replace(/\/+$/, '')}/`};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return _excludedHostnames;
|
||||
}
|
||||
|
||||
let _excludedLinkBases: Array<ExcludedLinkBase> | null = null;
|
||||
|
||||
function getExcludedLinkBases(): Array<ExcludedLinkBase> {
|
||||
if (!_excludedLinkBases) {
|
||||
const bases: Array<ExcludedLinkBase | null> = [
|
||||
...Config.hosts.unfurlIgnored.map((hostname) => ({hostname: normalizeHostname(hostname), pathPrefix: '/'})),
|
||||
endpointLinkBase(Config.endpoints.invite),
|
||||
endpointLinkBase(Config.endpoints.gift),
|
||||
];
|
||||
for (const hostname of [getWebAppHostname(), Config.hosts.marketing]) {
|
||||
for (const pathPrefix of CLIENT_ROUTE_PATH_PREFIXES) {
|
||||
bases.push({hostname: normalizeHostname(hostname), pathPrefix});
|
||||
}
|
||||
}
|
||||
_excludedLinkBases = bases.filter((base): base is ExcludedLinkBase => base !== null && base.hostname !== '');
|
||||
}
|
||||
return _excludedLinkBases;
|
||||
}
|
||||
|
||||
function idnaEncodeURL(url: string) {
|
||||
@@ -80,8 +82,9 @@ function isFluxerAppExcludedURL(url: string) {
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
const hostname = normalizeHostname(parsedUrl.hostname);
|
||||
const isMarketingPathMatch = isMarketingPath(hostname, parsedUrl.pathname);
|
||||
return isMarketingPathMatch || getExcludedHostnames().has(hostname);
|
||||
return getExcludedLinkBases().some(
|
||||
(base) => base.hostname === hostname && parsedUrl.pathname.startsWith(base.pathPrefix),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,6 @@ export interface InternalRoomOptions {
|
||||
|
||||
singlePeerConnection: boolean;
|
||||
subscriberVideoCodecExclusions?: Array<VideoCodec>;
|
||||
screenShareDelivery?: boolean;
|
||||
h264HardwareProfiles?: ReadonlySet<string>;
|
||||
dataStream?: RoomDataStreamOptions;
|
||||
}
|
||||
|
||||
@@ -73,66 +73,34 @@ describe('applyVideoStartBitrate', () => {
|
||||
}
|
||||
|
||||
it('adds a start bitrate to a non-SVC codec section', () => {
|
||||
for (const screenShareDelivery of [false, true]) {
|
||||
const media = videoMedia('camera-track', [
|
||||
{payload: 96, config: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f'},
|
||||
]);
|
||||
expect(applyVideoStartBitrate(media, 'camera-track', 'H264', 1000, false, screenShareDelivery)).toBe(96);
|
||||
expect(media.fmtp[0]?.config).toBe(
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f;x-google-start-bitrate=900',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('caps camera start bitrates but not screen share start bitrates while screen share delivery is off', () => {
|
||||
const camera = videoMedia('camera-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(camera, 'camera-track', 'H264', 3000);
|
||||
expect(camera.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=1000');
|
||||
|
||||
const screen = videoMedia('screen-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 6000, true);
|
||||
expect(screen.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=5400');
|
||||
const media = videoMedia('camera-track', [
|
||||
{payload: 96, config: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f'},
|
||||
]);
|
||||
expect(applyVideoStartBitrate(media, 'camera-track', 'H264', 1000, false)).toBe(96);
|
||||
expect(media.fmtp[0]?.config).toBe(
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f;x-google-start-bitrate=900',
|
||||
);
|
||||
});
|
||||
|
||||
it('caps camera and screen share start bitrates at their own ceilings', () => {
|
||||
const camera = videoMedia('camera-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(camera, 'camera-track', 'H264', 3000, false, true);
|
||||
applyVideoStartBitrate(camera, 'camera-track', 'H264', 3000, false);
|
||||
expect(camera.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=1000');
|
||||
|
||||
const screen = videoMedia('screen-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 6000, true, true);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 6000, true);
|
||||
expect(screen.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=1500');
|
||||
});
|
||||
|
||||
it('leaves a small screen share start bitrate on the floor while screen share delivery is off', () => {
|
||||
const screen = videoMedia('screen-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 300, true);
|
||||
expect(screen.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=270');
|
||||
});
|
||||
|
||||
it('keeps a screen share start bitrate above the frame dropper cliff', () => {
|
||||
const screen = videoMedia('screen-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 300, true, true);
|
||||
applyVideoStartBitrate(screen, 'screen-track', 'H264', 300, true);
|
||||
expect(screen.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=600');
|
||||
});
|
||||
|
||||
it('stamps only the lead payload type while screen share delivery is off', () => {
|
||||
const media = multiPayloadScreenMedia();
|
||||
expect(applyVideoStartBitrate(media, 'screen-track', 'H264', 6000, true)).toBe(116);
|
||||
expect(media.fmtp.find((fmtp) => fmtp.payload === 116)?.config).toBe(
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f;x-google-start-bitrate=5400',
|
||||
);
|
||||
expect(media.fmtp.find((fmtp) => fmtp.payload === 102)?.config).toBe(
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f',
|
||||
);
|
||||
expect(media.fmtp.find((fmtp) => fmtp.payload === 108)?.config).toBe(
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
|
||||
);
|
||||
});
|
||||
|
||||
it('stamps every payload type the codec is offered under, not only the lead one', () => {
|
||||
const media = multiPayloadScreenMedia();
|
||||
expect(applyVideoStartBitrate(media, 'screen-track', 'H264', 6000, true, true)).toBe(116);
|
||||
expect(applyVideoStartBitrate(media, 'screen-track', 'H264', 6000, true)).toBe(116);
|
||||
for (const fmtp of media.fmtp) {
|
||||
expect(fmtp.config).toContain('x-google-start-bitrate=1500');
|
||||
}
|
||||
@@ -140,47 +108,35 @@ describe('applyVideoStartBitrate', () => {
|
||||
});
|
||||
|
||||
it('only touches the fmtp line for the matching payload', () => {
|
||||
for (const screenShareDelivery of [false, true]) {
|
||||
const media = videoMedia(
|
||||
'screen-track',
|
||||
[
|
||||
{payload: 96, config: 'profile-level-id=42e01f'},
|
||||
{payload: 98, config: 'profile-id=0'},
|
||||
],
|
||||
[
|
||||
{payload: 96, codec: 'H264'},
|
||||
{payload: 98, codec: 'VP9'},
|
||||
],
|
||||
);
|
||||
applyVideoStartBitrate(media, 'screen-track', 'VP9', 1500, true, screenShareDelivery);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f');
|
||||
expect(media.fmtp[1]?.config).toBe('profile-id=0;x-google-start-bitrate=1350');
|
||||
}
|
||||
});
|
||||
|
||||
it('never appends a second start bitrate while screen share delivery is off', () => {
|
||||
const media = videoMedia('camera-track', [
|
||||
{payload: 96, config: 'profile-level-id=42e01f;x-google-start-bitrate=900'},
|
||||
]);
|
||||
applyVideoStartBitrate(media, 'camera-track', 'H264', 2000);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=900');
|
||||
const media = videoMedia(
|
||||
'screen-track',
|
||||
[
|
||||
{payload: 96, config: 'profile-level-id=42e01f'},
|
||||
{payload: 98, config: 'profile-id=0'},
|
||||
],
|
||||
[
|
||||
{payload: 96, codec: 'H264'},
|
||||
{payload: 98, codec: 'VP9'},
|
||||
],
|
||||
);
|
||||
applyVideoStartBitrate(media, 'screen-track', 'VP9', 1500, true);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f');
|
||||
expect(media.fmtp[1]?.config).toBe('profile-id=0;x-google-start-bitrate=1350');
|
||||
});
|
||||
|
||||
it('replaces a start bitrate an earlier offer wrote instead of keeping it', () => {
|
||||
const media = videoMedia('camera-track', [
|
||||
{payload: 96, config: 'profile-level-id=42e01f;x-google-start-bitrate=900'},
|
||||
]);
|
||||
applyVideoStartBitrate(media, 'camera-track', 'H264', 2000, false, true);
|
||||
applyVideoStartBitrate(media, 'camera-track', 'H264', 2000, false);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f;x-google-start-bitrate=1000');
|
||||
});
|
||||
|
||||
it('leaves other tracks and missing codecs alone', () => {
|
||||
for (const screenShareDelivery of [false, true]) {
|
||||
const media = videoMedia('camera-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
expect(applyVideoStartBitrate(media, 'other-track', 'H264', 2000, false, screenShareDelivery)).toBeUndefined();
|
||||
expect(applyVideoStartBitrate(media, 'camera-track', 'AV1', 2000, false, screenShareDelivery)).toBe(0);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f');
|
||||
}
|
||||
const media = videoMedia('camera-track', [{payload: 96, config: 'profile-level-id=42e01f'}]);
|
||||
expect(applyVideoStartBitrate(media, 'other-track', 'H264', 2000, false)).toBeUndefined();
|
||||
expect(applyVideoStartBitrate(media, 'camera-track', 'AV1', 2000, false)).toBe(0);
|
||||
expect(media.fmtp[0]?.config).toBe('profile-level-id=42e01f');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -49,7 +49,6 @@ export function applyVideoStartBitrate(
|
||||
codec: string,
|
||||
maxbr: number,
|
||||
isScreenShare = false,
|
||||
screenShareDelivery = false,
|
||||
): number | undefined {
|
||||
if (!media.msid?.includes(cid)) {
|
||||
return undefined;
|
||||
@@ -65,25 +64,10 @@ export function applyVideoStartBitrate(
|
||||
const calculatedStartBitrate = Math.round(maxbr * startBitrateMultiplier);
|
||||
let startBitrate = Math.min(calculatedStartBitrate, maxStartBitrateKbps);
|
||||
if (isScreenShare) {
|
||||
startBitrate = screenShareDelivery
|
||||
? Math.max(minScreenShareStartBitrateKbps, Math.min(calculatedStartBitrate, maxScreenShareStartBitrateKbps))
|
||||
: calculatedStartBitrate;
|
||||
}
|
||||
|
||||
if (!screenShareDelivery) {
|
||||
const codecPayload = codecPayloads[0];
|
||||
const fmtp = media.fmtp.find((entry) => entry.payload === codecPayload);
|
||||
if (fmtp) {
|
||||
if (!fmtp.config.includes(startBitrateParameter)) {
|
||||
fmtp.config += `;${startBitrateParameter}=${startBitrate}`;
|
||||
}
|
||||
} else {
|
||||
media.fmtp.push({
|
||||
payload: codecPayload,
|
||||
config: `${startBitrateParameter}=${startBitrate}`,
|
||||
});
|
||||
}
|
||||
return codecPayload;
|
||||
startBitrate = Math.max(
|
||||
minScreenShareStartBitrateKbps,
|
||||
Math.min(calculatedStartBitrate, maxScreenShareStartBitrateKbps),
|
||||
);
|
||||
}
|
||||
|
||||
for (const payload of codecPayloads) {
|
||||
@@ -143,8 +127,6 @@ export default class PCTransport extends (EventEmitter as new () => TypedEmitter
|
||||
|
||||
excludedVideoDecoderMimeTypes: Set<string> = new Set();
|
||||
|
||||
private screenShareDelivery: boolean;
|
||||
|
||||
onOffer?: (offer: RTCSessionDescriptionInit, offerId: number) => void;
|
||||
|
||||
onIceCandidate?: (candidate: RTCIceCandidate) => void;
|
||||
@@ -161,10 +143,9 @@ export default class PCTransport extends (EventEmitter as new () => TypedEmitter
|
||||
|
||||
onTrack?: (ev: RTCTrackEvent) => void;
|
||||
|
||||
constructor(config?: RTCConfiguration, loggerOptions: LoggerOptions = {}, screenShareDelivery: boolean = false) {
|
||||
constructor(config?: RTCConfiguration, loggerOptions: LoggerOptions = {}) {
|
||||
super();
|
||||
this.loggerOptions = loggerOptions;
|
||||
this.screenShareDelivery = screenShareDelivery;
|
||||
this.log = getLogger(loggerOptions.loggerName ?? LoggerNames.PCTransport, () => this.logContext);
|
||||
this.iceLog = getLogger(LoggerNames.ICE, () => this.logContext);
|
||||
this.config = config;
|
||||
@@ -412,7 +393,6 @@ export default class PCTransport extends (EventEmitter as new () => TypedEmitter
|
||||
trackbr.codec,
|
||||
trackbr.maxbr,
|
||||
trackbr.isScreenShare,
|
||||
this.screenShareDelivery,
|
||||
);
|
||||
if (codecPayload === undefined) {
|
||||
return false;
|
||||
@@ -471,10 +451,7 @@ export default class PCTransport extends (EventEmitter as new () => TypedEmitter
|
||||
for (const transceiver of this.getTransceivers()) {
|
||||
if (transceiver.receiver.track?.kind !== 'video') continue;
|
||||
if ((transceiver as {stopped?: boolean}).stopped) continue;
|
||||
const receives = this.screenShareDelivery
|
||||
? transceiver.direction === 'recvonly'
|
||||
: transceiver.direction === 'recvonly' || transceiver.direction === 'sendrecv';
|
||||
if (!receives) continue;
|
||||
if (transceiver.direction !== 'recvonly') continue;
|
||||
if (typeof transceiver.setCodecPreferences !== 'function') continue;
|
||||
try {
|
||||
transceiver.setCodecPreferences(allowed);
|
||||
|
||||
@@ -98,7 +98,6 @@ export class PCTransportManager {
|
||||
loggerOptions: LoggerOptions,
|
||||
rtcConfig?: RTCConfiguration,
|
||||
subscriberVideoCodecExclusions?: Array<VideoCodec>,
|
||||
screenShareDelivery: boolean = false,
|
||||
) {
|
||||
this.loggerOptions = loggerOptions;
|
||||
this.log = getLogger(loggerOptions.loggerName ?? LoggerNames.PCManager, () => this.logContext);
|
||||
@@ -106,10 +105,10 @@ export class PCTransportManager {
|
||||
|
||||
this.isPublisherConnectionRequired = mode !== 'subscriber-primary';
|
||||
this.isSubscriberConnectionRequired = mode === 'subscriber-primary';
|
||||
this.publisher = new PCTransport(rtcConfig, loggerOptions, screenShareDelivery);
|
||||
this.publisher = new PCTransport(rtcConfig, loggerOptions);
|
||||
this._mode = mode;
|
||||
if (mode !== 'publisher-only') {
|
||||
this.subscriber = new PCTransport(rtcConfig, loggerOptions, screenShareDelivery);
|
||||
this.subscriber = new PCTransport(rtcConfig, loggerOptions);
|
||||
this.subscriber.onConnectionStateChange = this.updateState;
|
||||
this.subscriber.onIceConnectionStateChange = this.updateState;
|
||||
this.subscriber.onSignalingStatechange = this.updateState;
|
||||
@@ -127,7 +126,7 @@ export class PCTransportManager {
|
||||
};
|
||||
}
|
||||
|
||||
const receivingTransport = screenShareDelivery ? (this.subscriber ?? this.publisher) : this.subscriber;
|
||||
const receivingTransport = this.subscriber ?? this.publisher;
|
||||
if (receivingTransport) {
|
||||
for (const codec of subscriberVideoCodecExclusions ?? []) {
|
||||
receivingTransport.excludedVideoDecoderMimeTypes.add(`video/${codec}`);
|
||||
|
||||
@@ -25,41 +25,20 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
const mainLine = 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f';
|
||||
const highLine = 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f';
|
||||
|
||||
it('keeps Main and Baseline ahead of Constrained Baseline while screen share delivery is off', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const baseline = codec('video/H264', baselineLine);
|
||||
const highProfile = codec('video/H264', highLine);
|
||||
const rtx = codec('video/rtx');
|
||||
const preferences = selectPublisherCodecPreferences('h264', [constrainedBaseline, rtx, baseline, highProfile]);
|
||||
expect(preferences).toEqual([highProfile, baseline, constrainedBaseline, rtx]);
|
||||
});
|
||||
|
||||
it('offers High first, then the one profile this server always registers, then the ones it registers nowhere', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const baseline = codec('video/H264', baselineLine);
|
||||
const highProfile = codec('video/H264', highLine);
|
||||
const rtx = codec('video/rtx');
|
||||
const preferences = selectPublisherCodecPreferences(
|
||||
'h264',
|
||||
[constrainedBaseline, rtx, baseline, highProfile],
|
||||
true,
|
||||
);
|
||||
const preferences = selectPublisherCodecPreferences('h264', [constrainedBaseline, rtx, baseline, highProfile]);
|
||||
expect(preferences).toEqual([highProfile, constrainedBaseline, baseline, rtx]);
|
||||
});
|
||||
|
||||
it('leads with Main and then Baseline while screen share delivery is off', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const mainProfile = codec('video/H264', mainLine);
|
||||
const baseline = codec('video/H264', baselineLine);
|
||||
const preferences = selectPublisherCodecPreferences('h264', [mainProfile, baseline, constrainedBaseline]);
|
||||
expect(preferences).toEqual([mainProfile, baseline, constrainedBaseline]);
|
||||
});
|
||||
|
||||
it('never leads with Main or Baseline, which this server registers nowhere and deletes from the answer', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const mainProfile = codec('video/H264', mainLine);
|
||||
const baseline = codec('video/H264', baselineLine);
|
||||
const preferences = selectPublisherCodecPreferences('h264', [mainProfile, baseline, constrainedBaseline], true);
|
||||
const preferences = selectPublisherCodecPreferences('h264', [mainProfile, baseline, constrainedBaseline]);
|
||||
expect(preferences).toEqual([constrainedBaseline, mainProfile, baseline]);
|
||||
});
|
||||
|
||||
@@ -75,21 +54,8 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
];
|
||||
}
|
||||
|
||||
it('sorts the capabilities Chromium reports by the old table while screen share delivery is off', () => {
|
||||
const preferences = selectPublisherCodecPreferences('h264', chromiumCapabilities());
|
||||
expect(preferences.map((entry) => entry.sdpFmtpLine)).toEqual([
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640034',
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f',
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f',
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
|
||||
'level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f',
|
||||
'level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f',
|
||||
'level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f',
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers High first out of the capabilities Chromium reports, so the only hardware profile this server registers wins', () => {
|
||||
const preferences = selectPublisherCodecPreferences('h264', chromiumCapabilities(), true);
|
||||
const preferences = selectPublisherCodecPreferences('h264', chromiumCapabilities());
|
||||
expect(preferences.map((entry) => entry.sdpFmtpLine)).toEqual([
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640034',
|
||||
'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
|
||||
@@ -116,7 +82,7 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
return {constrainedBaseline, mainProfile, highProfileLevel31, highProfileLevel51, constrainedHigh};
|
||||
}
|
||||
|
||||
it('ranks High, Constrained High, Main and Baseline above Constrained Baseline while screen share delivery is off', () => {
|
||||
it('ranks High and Constrained High above Constrained Baseline, whatever level each one reports', () => {
|
||||
const {constrainedBaseline, mainProfile, highProfileLevel31, highProfileLevel51, constrainedHigh} = levelSpread();
|
||||
const preferences = selectPublisherCodecPreferences('h264', [
|
||||
mainProfile,
|
||||
@@ -125,22 +91,6 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
constrainedHigh,
|
||||
constrainedBaseline,
|
||||
]);
|
||||
expect(preferences).toEqual([
|
||||
highProfileLevel31,
|
||||
highProfileLevel51,
|
||||
constrainedHigh,
|
||||
mainProfile,
|
||||
constrainedBaseline,
|
||||
]);
|
||||
});
|
||||
|
||||
it('ranks High and Constrained High above Constrained Baseline, whatever level each one reports', () => {
|
||||
const {constrainedBaseline, mainProfile, highProfileLevel31, highProfileLevel51, constrainedHigh} = levelSpread();
|
||||
const preferences = selectPublisherCodecPreferences(
|
||||
'h264',
|
||||
[mainProfile, highProfileLevel31, highProfileLevel51, constrainedHigh, constrainedBaseline],
|
||||
true,
|
||||
);
|
||||
expect(preferences).toEqual([
|
||||
highProfileLevel31,
|
||||
highProfileLevel51,
|
||||
@@ -150,7 +100,7 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('ranks packetization-mode=1 above packetization-mode=0 in both arms, which no hardware encoder takes', () => {
|
||||
it('ranks packetization-mode=1 above packetization-mode=0, which no hardware encoder takes', () => {
|
||||
const constrainedBaselineMode0 = codec(
|
||||
'video/H264',
|
||||
'level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f',
|
||||
@@ -167,7 +117,6 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
const capabilities = [highProfileMode0, constrainedBaselineMode0, constrainedBaselineMode1, highProfileMode1];
|
||||
const expected = [highProfileMode1, constrainedBaselineMode1, highProfileMode0, constrainedBaselineMode0];
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities)).toEqual(expected);
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, true)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('puts the chosen codec first and keeps every other codec in browser capability order', () => {
|
||||
@@ -175,7 +124,6 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
const vp8 = codec('video/VP8');
|
||||
const rtx = codec('video/rtx');
|
||||
expect(selectPublisherCodecPreferences('vp9', [vp8, rtx, vp9])).toEqual([vp9, vp8, rtx]);
|
||||
expect(selectPublisherCodecPreferences('vp9', [vp8, rtx, vp9], true)).toEqual([vp9, vp8, rtx]);
|
||||
});
|
||||
|
||||
it('keeps the other codecs so a later publication on the same connection can negotiate them', () => {
|
||||
@@ -192,7 +140,7 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const capabilities = [vp8, highProfile, constrainedBaseline];
|
||||
expect(selectPublisherCodecPreferences('vp8', capabilities)).toEqual([vp8, highProfile, constrainedBaseline]);
|
||||
expect(selectPublisherCodecPreferences('vp8', capabilities, true, new Set(['42e0']))).toEqual([
|
||||
expect(selectPublisherCodecPreferences('vp8', capabilities, new Set(['42e0']))).toEqual([
|
||||
vp8,
|
||||
constrainedBaseline,
|
||||
highProfile,
|
||||
@@ -203,25 +151,15 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
expect(selectPublisherCodecPreferences('av1', [codec('video/VP8'), codec('video/rtx')])).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores the profiles this host measured while screen share delivery is off', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const highProfile = codec('video/H264', highLine);
|
||||
const capabilities = [highProfile, constrainedBaseline];
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, false, new Set(['42e0']))).toEqual([
|
||||
highProfile,
|
||||
constrainedBaseline,
|
||||
]);
|
||||
});
|
||||
|
||||
it('only lets a profile this host encodes in hardware outrank Constrained Baseline', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const highProfile = codec('video/H264', highLine);
|
||||
const capabilities = [highProfile, constrainedBaseline];
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, true, new Set(['42e0']))).toEqual([
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, new Set(['42e0']))).toEqual([
|
||||
constrainedBaseline,
|
||||
highProfile,
|
||||
]);
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, true, new Set(['6400', '42e0']))).toEqual([
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, new Set(['6400', '42e0']))).toEqual([
|
||||
highProfile,
|
||||
constrainedBaseline,
|
||||
]);
|
||||
@@ -231,8 +169,8 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
const constrainedBaseline = codec('video/H264', constrainedBaselineLine);
|
||||
const highProfile = codec('video/H264', highLine);
|
||||
const capabilities = [constrainedBaseline, highProfile];
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, true)).toEqual([highProfile, constrainedBaseline]);
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, true, new Set())).toEqual([
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities)).toEqual([highProfile, constrainedBaseline]);
|
||||
expect(selectPublisherCodecPreferences('h264', capabilities, new Set())).toEqual([
|
||||
highProfile,
|
||||
constrainedBaseline,
|
||||
]);
|
||||
@@ -245,7 +183,7 @@ describe('selectPublisherCodecPreferences', () => {
|
||||
'level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=64001f',
|
||||
);
|
||||
expect(
|
||||
selectPublisherCodecPreferences('h264', [highProfileMode0, constrainedBaselineMode1], true, new Set(['6400'])),
|
||||
selectPublisherCodecPreferences('h264', [highProfileMode0, constrainedBaselineMode1], new Set(['6400'])),
|
||||
).toEqual([constrainedBaselineMode1, highProfileMode0]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -123,13 +123,6 @@ const videoCodecMimeTypes: Record<VideoCodec, Array<string>> = {
|
||||
vp8: ['video/vp8'],
|
||||
};
|
||||
const h264ProfileRanks = new Map([
|
||||
['6400', 0],
|
||||
['640c', 1],
|
||||
['4d00', 2],
|
||||
['4200', 3],
|
||||
['42e0', 4],
|
||||
]);
|
||||
const h264DeliveryProfileRanks = new Map([
|
||||
['6400', 0],
|
||||
['640c', 1],
|
||||
['42e0', 2],
|
||||
@@ -139,8 +132,7 @@ const h264DeliveryProfileRanks = new Map([
|
||||
const h264UnrankedProfileScore = 5;
|
||||
const h264MissingProfileScore = 6;
|
||||
const h264NonHardwareProfilePenalty = 8;
|
||||
const h264PacketizationMode0Score = 10;
|
||||
const h264DeliveryPacketizationMode0Score = 20;
|
||||
const h264PacketizationMode0Score = 20;
|
||||
type RtpCodecCapability = RTCRtpCapabilities['codecs'][number] & {sdpFmtpLine?: string};
|
||||
|
||||
enum PCState {
|
||||
@@ -523,7 +515,6 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit
|
||||
this.loggerOptions,
|
||||
rtcConfig,
|
||||
this.options.subscriberVideoCodecExclusions,
|
||||
this.options.screenShareDelivery ?? false,
|
||||
);
|
||||
} else {
|
||||
this.participantSid = joinResponse.participant?.sid;
|
||||
@@ -537,7 +528,6 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit
|
||||
this.loggerOptions,
|
||||
rtcConfig,
|
||||
this.options.subscriberVideoCodecExclusions,
|
||||
this.options.screenShareDelivery ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1062,12 +1052,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit
|
||||
if (typeof RTCRtpSender === 'undefined' || typeof RTCRtpSender.getCapabilities !== 'function') return;
|
||||
const capabilities = RTCRtpSender.getCapabilities('video');
|
||||
if (!capabilities) return;
|
||||
const preferences = selectPublisherCodecPreferences(
|
||||
codec,
|
||||
capabilities.codecs,
|
||||
this.options.screenShareDelivery ?? false,
|
||||
this.options.h264HardwareProfiles,
|
||||
);
|
||||
const preferences = selectPublisherCodecPreferences(codec, capabilities.codecs, this.options.h264HardwareProfiles);
|
||||
if (preferences.length === 0) {
|
||||
this.log.warn('sender cannot encode the requested codec, leaving the browser order in place', {
|
||||
...this.logContext,
|
||||
@@ -1843,33 +1828,27 @@ function getFmtpParameter(sdpFmtpLine: string | undefined, key: string): string
|
||||
|
||||
function getH264PublisherCodecScore(
|
||||
codec: RtpCodecCapability,
|
||||
screenShareDelivery: boolean,
|
||||
hardwareProfiles: ReadonlySet<string> | undefined,
|
||||
): number {
|
||||
const profileLevelId = getFmtpParameter(codec.sdpFmtpLine, 'profile-level-id');
|
||||
const packetizationMode = getFmtpParameter(codec.sdpFmtpLine, 'packetization-mode');
|
||||
const mode0Score = screenShareDelivery ? h264DeliveryPacketizationMode0Score : h264PacketizationMode0Score;
|
||||
const packetizationScore = packetizationMode === '1' ? 0 : mode0Score;
|
||||
const packetizationScore = packetizationMode === '1' ? 0 : h264PacketizationMode0Score;
|
||||
if (!profileLevelId) return packetizationScore + h264MissingProfileScore;
|
||||
const profile = profileLevelId.slice(0, 4);
|
||||
if (!screenShareDelivery) {
|
||||
return packetizationScore + (h264ProfileRanks.get(profile) ?? h264UnrankedProfileScore);
|
||||
}
|
||||
const isSoftwareOnly = hardwareProfiles !== undefined && hardwareProfiles.size > 0 && !hardwareProfiles.has(profile);
|
||||
const hardwareScore = isSoftwareOnly ? h264NonHardwareProfilePenalty : 0;
|
||||
return packetizationScore + hardwareScore + (h264DeliveryProfileRanks.get(profile) ?? h264UnrankedProfileScore);
|
||||
return packetizationScore + hardwareScore + (h264ProfileRanks.get(profile) ?? h264UnrankedProfileScore);
|
||||
}
|
||||
|
||||
function preferHardwareH264Codecs(
|
||||
codecs: ReadonlyArray<RtpCodecCapability>,
|
||||
screenShareDelivery: boolean,
|
||||
hardwareProfiles: ReadonlySet<string> | undefined,
|
||||
): Array<RtpCodecCapability> {
|
||||
return codecs
|
||||
.map((codec, index) => ({
|
||||
codec,
|
||||
index,
|
||||
score: getH264PublisherCodecScore(codec, screenShareDelivery, hardwareProfiles),
|
||||
score: getH264PublisherCodecScore(codec, hardwareProfiles),
|
||||
}))
|
||||
.sort((a, b) => a.score - b.score || a.index - b.index)
|
||||
.map((entry) => entry.codec);
|
||||
@@ -1878,17 +1857,15 @@ function preferHardwareH264Codecs(
|
||||
export function selectPublisherCodecPreferences(
|
||||
codec: VideoCodec,
|
||||
codecs: ReadonlyArray<RtpCodecCapability>,
|
||||
screenShareDelivery: boolean = false,
|
||||
h264HardwareProfiles?: ReadonlySet<string>,
|
||||
): Array<RtpCodecCapability> {
|
||||
const mimeTypes = new Set(videoCodecMimeTypes[codec]);
|
||||
const selected = codecs.filter((entry) => mimeTypes.has(entry.mimeType.toLowerCase()));
|
||||
if (selected.length === 0) return [];
|
||||
const preferred =
|
||||
codec === 'h264' ? preferHardwareH264Codecs(selected, screenShareDelivery, h264HardwareProfiles) : selected;
|
||||
const preferred = codec === 'h264' ? preferHardwareH264Codecs(selected, h264HardwareProfiles) : selected;
|
||||
const isH264 = (entry: RtpCodecCapability): boolean => entry.mimeType.toLowerCase() === 'video/h264';
|
||||
const remaining = codecs.filter((entry) => !mimeTypes.has(entry.mimeType.toLowerCase()));
|
||||
const rankedH264 = preferHardwareH264Codecs(remaining.filter(isH264), screenShareDelivery, h264HardwareProfiles);
|
||||
const rankedH264 = preferHardwareH264Codecs(remaining.filter(isH264), h264HardwareProfiles);
|
||||
let nextH264 = 0;
|
||||
const rest = remaining.map((entry) => (isH264(entry) ? rankedH264[nextH264++] : entry));
|
||||
return [...preferred, ...rest];
|
||||
|
||||
@@ -63,7 +63,6 @@ import {
|
||||
publishDefaults,
|
||||
roomConnectOptionDefaults,
|
||||
roomOptionDefaults,
|
||||
screenShareDeliveryPublishDefaults,
|
||||
videoDefaults,
|
||||
} from './defaults.ts';
|
||||
import {ConnectionError, ConnectionErrorReason, UnexpectedConnectionState, UnsupportedServer} from './errors.ts';
|
||||
@@ -228,7 +227,7 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
|
||||
...options?.videoCaptureDefaults,
|
||||
};
|
||||
this.options.publishDefaults = {
|
||||
...(this.options.screenShareDelivery ? screenShareDeliveryPublishDefaults : publishDefaults),
|
||||
...publishDefaults,
|
||||
...options?.publishDefaults,
|
||||
};
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {AudioPresets, BackupCodecPolicy, ScreenSharePresets, VideoPresets} from
|
||||
|
||||
export const defaultVideoCodec = 'h264';
|
||||
|
||||
export const screenShareDeliveryPublishDefaults: TrackPublishDefaults = {
|
||||
export const publishDefaults: TrackPublishDefaults = {
|
||||
audioPreset: AudioPresets.music,
|
||||
dtx: false,
|
||||
red: true,
|
||||
@@ -21,11 +21,6 @@ export const screenShareDeliveryPublishDefaults: TrackPublishDefaults = {
|
||||
preConnectBuffer: false,
|
||||
} as const;
|
||||
|
||||
export const publishDefaults: TrackPublishDefaults = {
|
||||
...screenShareDeliveryPublishDefaults,
|
||||
degradationPreference: 'maintain-resolution',
|
||||
};
|
||||
|
||||
export const audioDefaults: AudioCaptureOptions = {
|
||||
deviceId: {ideal: 'default'},
|
||||
autoGainControl: true,
|
||||
|
||||
@@ -814,7 +814,6 @@ export default class LocalParticipant extends Participant {
|
||||
...this.roomOptions.publishDefaults,
|
||||
...options,
|
||||
};
|
||||
track.screenShareDelivery = this.roomOptions.screenShareDelivery ?? false;
|
||||
const isStereoInput =
|
||||
('channelCount' in track.mediaStreamTrack.getSettings() &&
|
||||
track.mediaStreamTrack.getSettings().channelCount === 2) ||
|
||||
@@ -1788,7 +1787,7 @@ export default class LocalParticipant extends Participant {
|
||||
return;
|
||||
}
|
||||
let subscribedCodecs = update.subscribedCodecs;
|
||||
if (this.roomOptions.screenShareDelivery && hasSingleRidlessEncoding(pub.videoTrack)) {
|
||||
if (hasSingleRidlessEncoding(pub.videoTrack)) {
|
||||
subscribedCodecs = subscribedCodecs.filter((codec) => codec.qualities.some((quality) => quality.enabled));
|
||||
if (subscribedCodecs.length === 0) {
|
||||
return;
|
||||
|
||||
@@ -41,8 +41,6 @@ export default abstract class LocalTrack<TrackKind extends Track.Kind = Track.Ki
|
||||
|
||||
codec?: VideoCodec;
|
||||
|
||||
screenShareDelivery: boolean = false;
|
||||
|
||||
get constraints() {
|
||||
return this._constraints;
|
||||
}
|
||||
@@ -563,7 +561,7 @@ export default abstract class LocalTrack<TrackKind extends Track.Kind = Track.Ki
|
||||
);
|
||||
|
||||
private debouncedTrackMuteHandler = debounce(async () => {
|
||||
if (this.screenShareDelivery && this.source === Track.Source.ScreenShare) {
|
||||
if (this.source === Track.Source.ScreenShare) {
|
||||
this.log.debug('screen share capture went idle, keeping upstream published', this.logContext);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -433,6 +433,7 @@ export default () => {
|
||||
staticFilesPlugin({
|
||||
staticCdnEndpoint: normalizedStaticCdnEndpoint,
|
||||
fontsDir: path.join(MONOREPO_ROOT, 'packages', 'fonts'),
|
||||
wasmCratesDir: path.join(ROOT_DIR, 'rust'),
|
||||
}),
|
||||
new DefinePlugin({
|
||||
__FLUXER_PRECACHE_MANIFEST__: JSON.stringify([]),
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2026, Alexandre Bury
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,32 @@
|
||||
The auto-generated bindings are under the 3-clause BSD license:
|
||||
|
||||
BSD License
|
||||
|
||||
For Zstandard software
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name Facebook, nor Meta, nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,30 @@
|
||||
BSD License
|
||||
|
||||
For Zstandard software
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name Facebook, nor Meta, nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,12 @@
|
||||
# libfluxcore licenses
|
||||
|
||||
`libfluxcore_bg.wasm` is built from this crate and bundled into the app. It
|
||||
contains third-party code that keeps its upstream license.
|
||||
|
||||
| Component | Source | License |
|
||||
| --- | --- | --- |
|
||||
| Zstandard 1.5.7 | Vendored by the `zstd-sys` 2.1.0 crate | BSD-3-Clause, see `LICENSE-ZSTD.txt` (Zstandard is dual licensed, Fluxer uses it under BSD-3-Clause) |
|
||||
| `zstd-sys` 2.1.0 | Rust bindings, build script and WebAssembly libc shim | BSD-3-Clause, see `LICENSE-ZSTD-SYS.txt` |
|
||||
| `zstd` 0.14.0 | Rust wrapper | BSD-3-Clause, see `LICENSE-ZSTD-RS.txt` |
|
||||
|
||||
No Fluxer license notice grants rights to third-party trademarks or brand names.
|
||||
@@ -16,6 +16,22 @@ pub fn is_animated_image_bytes(input: &[u8]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn sniff_image_format_bytes(input: &[u8]) -> u8 {
|
||||
if is_png(input) {
|
||||
1
|
||||
} else if is_gif(input) {
|
||||
2
|
||||
} else if is_webp(input) {
|
||||
3
|
||||
} else if is_avif_file(input) {
|
||||
4
|
||||
} else if input.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||
5
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn is_gif(input: &[u8]) -> bool {
|
||||
input.starts_with(b"GIF89a") || input.starts_with(b"GIF87a")
|
||||
}
|
||||
@@ -35,7 +51,16 @@ fn is_avif_file(input: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
fn has_avif_anim(input: &[u8]) -> bool {
|
||||
is_avif_file(input) && &input[8..12] == b"avis"
|
||||
if !is_avif_file(input) {
|
||||
return false;
|
||||
}
|
||||
if &input[8..12] == b"avis" {
|
||||
return true;
|
||||
}
|
||||
let box_end = read_u32_be(input, 0).map_or(0, |size| (size as usize).min(input.len()));
|
||||
input
|
||||
.get(16..box_end)
|
||||
.is_some_and(|brands| brands.as_chunks::<4>().0.contains(b"avis"))
|
||||
}
|
||||
|
||||
fn has_apng_actl(input: &[u8]) -> bool {
|
||||
@@ -243,13 +268,53 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn detects_avif_sequence_brand() {
|
||||
let avif = b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00avis";
|
||||
assert!(!is_animated_image_bytes(avif));
|
||||
let still = b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00mif1miaf";
|
||||
assert!(!is_animated_image_bytes(still));
|
||||
|
||||
let avis = b"\x00\x00\x00\x18ftypavis\x00\x00\x00\x00avif";
|
||||
assert!(is_animated_image_bytes(avis));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_avis_among_compatible_brands() {
|
||||
let compat = b"\x00\x00\x00\x1cftypavif\x00\x00\x00\x00mif1avismsf1";
|
||||
assert!(is_animated_image_bytes(compat));
|
||||
|
||||
let outside_ftyp = b"\x00\x00\x00\x14ftypavif\x00\x00\x00\x00mif1avis";
|
||||
assert!(!is_animated_image_bytes(outside_ftyp));
|
||||
|
||||
let truncated = b"\x00\x00\x00\x40ftypavif\x00\x00\x00\x00mif1av";
|
||||
assert!(!is_animated_image_bytes(truncated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sniffs_image_formats_from_magic_bytes() {
|
||||
assert_eq!(sniff_image_format_bytes(b""), 0);
|
||||
assert_eq!(sniff_image_format_bytes(b"<svg xmlns"), 0);
|
||||
assert_eq!(
|
||||
sniff_image_format_bytes(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"),
|
||||
1
|
||||
);
|
||||
assert_eq!(sniff_image_format_bytes(b"GIF89a\x01\x00"), 2);
|
||||
assert_eq!(sniff_image_format_bytes(b"GIF87a\x01\x00"), 2);
|
||||
assert_eq!(sniff_image_format_bytes(b"RIFF\x04\0\0\0WEBPVP8 "), 3);
|
||||
assert_eq!(sniff_image_format_bytes(b"RIFF\x04\0\0\0WAVEfmt "), 0);
|
||||
assert_eq!(
|
||||
sniff_image_format_bytes(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
sniff_image_format_bytes(b"\x00\x00\x00\x18ftypavis\x00\x00\x00\x00"),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
sniff_image_format_bytes(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"),
|
||||
0
|
||||
);
|
||||
assert_eq!(sniff_image_format_bytes(b"\xff\xd8\xff\xe0\x00\x10JFIF"), 5);
|
||||
assert_eq!(sniff_image_format_bytes(b"\xff\xd8"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_chunks_without_panicking() {
|
||||
assert!(!is_animated_image_bytes(
|
||||
|
||||
@@ -5,8 +5,8 @@ mod rgba;
|
||||
mod zstd_frame;
|
||||
mod zstd_stream;
|
||||
|
||||
use formats::is_animated_image_bytes;
|
||||
use rgba::{TransformRequest, crop_rotate_rgba_alloc};
|
||||
use formats::{is_animated_image_bytes, sniff_image_format_bytes};
|
||||
use rgba::{TransformRequest, crop_rotate_rgba_alloc, crop_rotate_rgba_into};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
@@ -40,6 +40,39 @@ pub fn crop_rotate_rgba_raw(
|
||||
.map_err(|error| JsValue::from_str(error.message()))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn crop_rotate_rgba_into_buffer(
|
||||
input: &[u8],
|
||||
output: &mut [u8],
|
||||
src_width: u32,
|
||||
src_height: u32,
|
||||
x: u32,
|
||||
y: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
rotation_deg: u32,
|
||||
output_width: u32,
|
||||
output_height: u32,
|
||||
) -> Result<(), JsValue> {
|
||||
crop_rotate_rgba_into(
|
||||
input,
|
||||
output,
|
||||
TransformRequest {
|
||||
src_width,
|
||||
src_height,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
rotation_deg,
|
||||
resize_width: output_width,
|
||||
resize_height: output_height,
|
||||
},
|
||||
)
|
||||
.map_err(|error| JsValue::from_str(error.message()))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn decompress_zstd_frame(input: &[u8]) -> Result<Vec<u8>, JsValue> {
|
||||
zstd_frame::decompress(input).map_err(zstd_error_to_js)
|
||||
@@ -106,6 +139,11 @@ pub fn is_animated_image(input: &[u8]) -> bool {
|
||||
is_animated_image_bytes(input)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn sniff_image_format(input: &[u8]) -> u8 {
|
||||
sniff_image_format_bytes(input)
|
||||
}
|
||||
|
||||
fn optional_dimension_to_abi(value: Option<u32>) -> u32 {
|
||||
value.filter(|dimension| *dimension > 0).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ pub struct TransformRequest {
|
||||
pub enum TransformError {
|
||||
InvalidDimensions,
|
||||
InvalidRgbaLength,
|
||||
InvalidOutputLength,
|
||||
EmptyCrop,
|
||||
EmptyTarget,
|
||||
ImageTooLarge,
|
||||
@@ -33,6 +34,7 @@ impl TransformError {
|
||||
match self {
|
||||
Self::InvalidDimensions => "invalid RGBA dimensions",
|
||||
Self::InvalidRgbaLength => "RGBA input length does not match dimensions",
|
||||
Self::InvalidOutputLength => "RGBA output length does not match target dimensions",
|
||||
Self::EmptyCrop => "Crop area is empty",
|
||||
Self::EmptyTarget => "Target dimensions are empty",
|
||||
Self::ImageTooLarge => "Image is too large to crop",
|
||||
@@ -75,12 +77,7 @@ pub fn crop_rotate_rgba_alloc(
|
||||
input: &[u8],
|
||||
request: TransformRequest,
|
||||
) -> Result<Vec<u8>, TransformError> {
|
||||
let geometry = output_geometry(request)?;
|
||||
let expected_len = rgba_byte_len(request.src_width, request.src_height, 0)?;
|
||||
if input.len() != expected_len {
|
||||
return Err(TransformError::InvalidRgbaLength);
|
||||
}
|
||||
|
||||
let geometry = checked_geometry(input, request)?;
|
||||
let output_len = rgba_byte_len(
|
||||
geometry.target_width,
|
||||
geometry.target_height,
|
||||
@@ -89,8 +86,45 @@ pub fn crop_rotate_rgba_alloc(
|
||||
let mut output = try_zeroed_vec(output_len)?;
|
||||
write_u32_le(&mut output, 0, geometry.target_width);
|
||||
write_u32_le(&mut output, 4, geometry.target_height);
|
||||
write_transformed(
|
||||
input,
|
||||
&mut output[RGBA_RESULT_HEADER_BYTES..],
|
||||
request,
|
||||
geometry,
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
let dst = &mut output[RGBA_RESULT_HEADER_BYTES..];
|
||||
pub fn crop_rotate_rgba_into(
|
||||
input: &[u8],
|
||||
output: &mut [u8],
|
||||
request: TransformRequest,
|
||||
) -> Result<(), TransformError> {
|
||||
let geometry = checked_geometry(input, request)?;
|
||||
if output.len() != rgba_byte_len(geometry.target_width, geometry.target_height, 0)? {
|
||||
return Err(TransformError::InvalidOutputLength);
|
||||
}
|
||||
write_transformed(input, output, request, geometry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn checked_geometry(
|
||||
input: &[u8],
|
||||
request: TransformRequest,
|
||||
) -> Result<OutputGeometry, TransformError> {
|
||||
let geometry = output_geometry(request)?;
|
||||
if input.len() != rgba_byte_len(request.src_width, request.src_height, 0)? {
|
||||
return Err(TransformError::InvalidRgbaLength);
|
||||
}
|
||||
Ok(geometry)
|
||||
}
|
||||
|
||||
fn write_transformed(
|
||||
input: &[u8],
|
||||
dst: &mut [u8],
|
||||
request: TransformRequest,
|
||||
geometry: OutputGeometry,
|
||||
) {
|
||||
if geometry.target_width == geometry.base_width
|
||||
&& geometry.target_height == geometry.base_height
|
||||
{
|
||||
@@ -98,8 +132,6 @@ pub fn crop_rotate_rgba_alloc(
|
||||
} else {
|
||||
copy_rotated_with_nearest_resize(input, dst, request, geometry);
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn output_geometry(request: TransformRequest) -> Result<OutputGeometry, TransformError> {
|
||||
@@ -463,6 +495,30 @@ mod tests {
|
||||
assert!(crop_rotate_rgba_alloc(&rgba(&[1, 2, 3, 4]), empty_target).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_writes_the_same_pixels_as_alloc() {
|
||||
let input = rgba(&[1, 2, 3, 4, 5, 6]);
|
||||
for rotation_deg in [0, 90, 180, 270] {
|
||||
let mut transform = request(2, 3);
|
||||
transform.rotation_deg = rotation_deg;
|
||||
transform.resize_width = 5;
|
||||
transform.resize_height = 4;
|
||||
let expected = crop_rotate_rgba_alloc(&input, transform).unwrap();
|
||||
let mut output = vec![0xaa; 5 * 4 * RGBA_BYTES_PER_PIXEL];
|
||||
crop_rotate_rgba_into(&input, &mut output, transform).unwrap();
|
||||
assert_eq!(output, payload(&expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_rejects_an_output_of_the_wrong_length() {
|
||||
let mut output = vec![0; 3 * RGBA_BYTES_PER_PIXEL];
|
||||
assert_eq!(
|
||||
crop_rotate_rgba_into(&rgba(&[1, 2, 3, 4]), &mut output, request(2, 2)).unwrap_err(),
|
||||
TransformError::InvalidOutputLength
|
||||
);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn identity_transform_preserves_pixels(width in 1u32..16, height in 1u32..16) {
|
||||
|
||||
Generated
+160
@@ -0,0 +1,160 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "libfluxwebp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libwebp-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libwebp-sys"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b3a87b44e34d17161e4f17d92a463d596cb13825dcd1758ed18fd3a721e189c"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"glob",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.128"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.128"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.128"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.128"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "libfluxwebp"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
wasm-bindgen = "=0.2.128"
|
||||
libwebp-sys = {version = "=0.14.4", default-features = false}
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = "z"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
|
||||
[workspace]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) the libwebp-sys authors (XianYou, Kornel Lesiński and contributors)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,30 @@
|
||||
Copyright (c) 2010, Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# libfluxwebp licenses
|
||||
|
||||
`libfluxwebp_bg.wasm` and `libfluxwebp_simd_bg.wasm` are built from this crate
|
||||
and bundled into the app. They contain third-party code that keeps its upstream
|
||||
license.
|
||||
|
||||
| Component | Source | License |
|
||||
| --- | --- | --- |
|
||||
| libwebp 1.6.0 | Vendored by the `libwebp-sys` 0.14.4 crate | BSD-3-Clause, see `LICENSE-LIBWEBP.txt`, with the additional patent grant in `PATENTS-LIBWEBP.txt` |
|
||||
| `libwebp-sys` 0.14.4 | Rust bindings and build script | MIT, see `LICENSE-LIBWEBP-SYS.txt` |
|
||||
| `simd/xmmintrin.h`, `simd/emmintrin.h` | Emscripten 4.0.15 SSE compatibility headers | MIT or University of Illinois/NCSA, see `simd/LICENSE` |
|
||||
|
||||
The SIMD build compiles libwebp's SSE2 code paths through the Emscripten
|
||||
headers, unmodified. The headers in `shim/` and `src/shim.rs` are Fluxer code.
|
||||
|
||||
No Fluxer license notice grants rights to third-party trademarks or brand names.
|
||||
@@ -0,0 +1,23 @@
|
||||
Additional IP Rights Grant (Patents)
|
||||
------------------------------------
|
||||
|
||||
"These implementations" means the copyrightable works that implement the WebM
|
||||
codecs distributed by Google as part of the WebM Project.
|
||||
|
||||
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
|
||||
royalty-free, irrevocable (except as stated in this section) patent license to
|
||||
make, have made, use, offer to sell, sell, import, transfer, and otherwise
|
||||
run, modify and propagate the contents of these implementations of WebM, where
|
||||
such license applies only to those patent claims, both currently owned by
|
||||
Google and acquired in the future, licensable by Google that are necessarily
|
||||
infringed by these implementations of WebM. This grant does not include claims
|
||||
that would be infringed only as a consequence of further modification of these
|
||||
implementations. If you or your agent or exclusive licensee institute or order
|
||||
or agree to the institution of patent litigation or any other patent
|
||||
enforcement activity against any entity (including a cross-claim or
|
||||
counterclaim in a lawsuit) alleging that any of these implementations of WebM
|
||||
or any code incorporated within any of these implementations of WebM
|
||||
constitute direct or contributory patent infringement, or inducement of
|
||||
patent infringement, then any patent rights granted to you under this License
|
||||
for these implementations of WebM shall terminate as of the date such
|
||||
litigation is filed.
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
#ifndef FLUXWEBP_ASSERT_H
|
||||
#define FLUXWEBP_ASSERT_H
|
||||
#define assert(expr) ((void)0)
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user