├── .gitignore ├── tests ├── key ├── secret └── keysecret.yaml ├── .github ├── CODEOWNERS └── workflows │ ├── test.yaml │ ├── lint.yaml │ ├── docker.yaml │ └── release.yaml ├── LICENSE-COMMERCIAL ├── renovate.json ├── Dockerfile ├── go.mod ├── README.md ├── main.go ├── go.sum ├── LICENSE └── main_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | lk-jwt-service 3 | -------------------------------------------------------------------------------- /tests/key: -------------------------------------------------------------------------------- 1 | from_file_oquusheiheiw4Iegah8te3Vienguus5a 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @element-hq/element-call-reviewers 2 | -------------------------------------------------------------------------------- /tests/secret: -------------------------------------------------------------------------------- 1 | from_file_vohmahH3eeyieghohSh3kee8feuPhaim 2 | -------------------------------------------------------------------------------- /tests/keysecret.yaml: -------------------------------------------------------------------------------- 1 | keysecret_iethuB2LeLiNuishiaKeephei9jaatio: keysecret_xefaingo4oos6ohla9phiMieBu3ohJi2 2 | -------------------------------------------------------------------------------- /LICENSE-COMMERCIAL: -------------------------------------------------------------------------------- 1 | Licensees holding a valid commercial license with Element may use this 2 | software in accordance with the terms contained in a written agreement 3 | between you and Element. 4 | 5 | To purchase a commercial license please contact our sales team at 6 | licensing@element.io 7 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: [main] 7 | 8 | jobs: 9 | test: 10 | name: Testing 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: read 14 | steps: 15 | - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 16 | - name: Install Go 17 | uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 18 | with: 19 | go-version-file: go.mod 20 | - name: Test 21 | run: go test -timeout 30s 22 | -------------------------------------------------------------------------------- /.github/workflows/lint.yaml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | pull_request: {} 5 | push: 6 | branches: [main] 7 | jobs: 8 | lint: 9 | timeout-minutes: 5 10 | name: Linting 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 14 | - name: Install Go 15 | uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 16 | with: 17 | go-version-file: go.mod 18 | - name: golangci-lint 19 | uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0 20 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended", 5 | "schedule:monthly", 6 | "helpers:pinGitHubActionDigestsToSemver", 7 | ":enableVulnerabilityAlertsWithLabel(security)" 8 | ], 9 | "addLabels": ["dependencies"], 10 | "vulnerabilityAlerts": { 11 | "schedule": [ 12 | "at any time" 13 | ], 14 | "prHourlyLimit": 0, 15 | "minimumReleaseAge": null 16 | }, 17 | "packageRules": [ 18 | { 19 | "groupName": "GitHub Actions", 20 | "matchDepTypes": ["action"], 21 | "pinDigests": true 22 | } 23 | ], 24 | "minimumReleaseAge": "5 days" 25 | } 26 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Set the version to match that which is in go.mod 2 | ARG GO_VERSION="build-arg-must-be-provided" 3 | 4 | FROM --platform=${BUILDPLATFORM} golang:${GO_VERSION}-alpine AS builder 5 | 6 | WORKDIR /proj 7 | 8 | COPY go.mod ./ 9 | COPY go.sum ./ 10 | RUN go mod download 11 | 12 | COPY *.go ./ 13 | 14 | ARG TARGETOS TARGETARCH 15 | RUN GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o lk-jwt-service 16 | # set up nsswitch.conf for Go's "netgo" implementation 17 | # - https://github.com/golang/go/blob/go1.24.0/src/net/conf.go#L343 18 | RUN echo 'hosts: files dns' > /etc/nsswitch.conf 19 | 20 | FROM scratch 21 | 22 | COPY --from=builder /proj/lk-jwt-service /lk-jwt-service 23 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 24 | COPY --from=builder /etc/nsswitch.conf /etc/nsswitch.conf 25 | 26 | EXPOSE 8080 27 | 28 | CMD [ "/lk-jwt-service" ] 29 | -------------------------------------------------------------------------------- /.github/workflows/docker.yaml: -------------------------------------------------------------------------------- 1 | name: Build and publish Docker image 2 | 3 | on: 4 | push: 5 | 6 | env: 7 | REGISTRY: ghcr.io 8 | IMAGE_NAME: ${{ github.repository }} 9 | 10 | jobs: 11 | build-and-push-image: 12 | runs-on: ubuntu-latest 13 | permissions: 14 | contents: read 15 | packages: write 16 | 17 | steps: 18 | - name: Get current time 19 | id: current-time 20 | run: echo "unix_time=$(date +'%s')" >> $GITHUB_OUTPUT 21 | 22 | - name: Checkout repository 23 | uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 24 | 25 | - name: Log in to the Container registry 26 | uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0 27 | with: 28 | registry: ${{ env.REGISTRY }} 29 | username: ${{ github.actor }} 30 | password: ${{ secrets.GITHUB_TOKEN }} 31 | 32 | - name: Extract metadata (tags, labels) for Docker 33 | id: meta 34 | uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0 35 | with: 36 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 37 | tags: | 38 | type=sha,format=short,event=branch 39 | type=ref,event=pr 40 | type=semver,pattern={{version}} 41 | type=raw,value=latest-ci_${{steps.current-time.outputs.unix_time}},enable={{is_default_branch}} 42 | latest-ci 43 | 44 | - name: Set up Docker Buildx 45 | uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 46 | 47 | - name: Get go version 48 | run: echo "GO_VERSION=$(go mod edit -json | jq -r .Toolchain | sed "s,^go,,")" >> $GITHUB_ENV 49 | 50 | - name: Build and push Docker image 51 | uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 52 | with: 53 | context: . 54 | platforms: linux/amd64,linux/arm64 55 | push: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }} # only push on main branch or release tag 56 | provenance: mode=max 57 | sbom: true 58 | tags: ${{ steps.meta.outputs.tags }} 59 | labels: ${{ steps.meta.outputs.labels }} 60 | build-args: | 61 | GO_VERSION=${{ env.GO_VERSION }} 62 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: "Create draft release after tag" 2 | on: 3 | push: 4 | tags: ["v*"] 5 | permissions: 6 | contents: write 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | os: ["linux"] 14 | arch: ["amd64", "arm64"] 15 | steps: 16 | - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 17 | - uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 18 | with: 19 | go-version-file: go.mod 20 | - run: mkdir build 21 | - run: go build -trimpath -o build/lk-jwt-service_${{ matrix.os }}_${{ matrix.arch }} 22 | env: 23 | CGO_ENABLED: 0 24 | GOOS: ${{ matrix.os }} 25 | GOARCH: ${{ matrix.arch }} 26 | - name: "Upload binary as artifact" 27 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 28 | with: 29 | name: build-${{ matrix.os }}-${{ matrix.arch }} 30 | path: build/lk-jwt-service_${{ matrix.os }}_${{ matrix.arch }} 31 | if-no-files-found: error 32 | 33 | create-release: 34 | needs: ["build"] 35 | runs-on: ubuntu-latest 36 | steps: 37 | - name: "Extract version" 38 | run: echo "IMAGE_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV 39 | - name: "Fetch all binaries" 40 | uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 41 | with: 42 | path: build 43 | pattern: build-* 44 | merge-multiple: true 45 | - name: "Create release" 46 | uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1 47 | with: 48 | files: build/* 49 | fail_on_unmatched_files: true 50 | draft: true 51 | generate_release_notes: true 52 | body: | 53 | ## Docker image 54 | 55 | The service is available as a Docker image from the [GitHub Container Registry](https://github.com/element-hq/lk-jwt-service/pkgs/container/lk-jwt-service). 56 | 57 | ``` 58 | docker pull ghcr.io/element-hq/lk-jwt-service:${{env.IMAGE_VERSION}} 59 | ``` 60 | 61 | ## Precompiled binaries 62 | 63 | The service is available as static precompiled binaries for amd64 and arm64 on linux attached to this release below. 64 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module lk-jwt-service 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.25.3 6 | 7 | require ( 8 | github.com/golang-jwt/jwt/v5 v5.3.0 9 | github.com/livekit/protocol v1.34.0 10 | github.com/livekit/server-sdk-go/v2 v2.5.0 11 | github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 12 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250815065806-6697d93cbcba 13 | ) 14 | 15 | require ( 16 | buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.0-20241127180247-a33202765966.1 // indirect 17 | buf.build/go/protoyaml v0.3.1 // indirect 18 | cel.dev/expr v0.19.0 // indirect 19 | github.com/antlr4-go/antlr/v4 v4.13.0 // indirect 20 | github.com/benbjohnson/clock v1.3.5 // indirect 21 | github.com/bep/debounce v1.2.1 // indirect 22 | github.com/bufbuild/protovalidate-go v0.8.0 // indirect 23 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 24 | github.com/dennwc/iters v1.0.1 // indirect 25 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect 26 | github.com/frostbyte73/core v0.1.1 // indirect 27 | github.com/fsnotify/fsnotify v1.8.0 // indirect 28 | github.com/gammazero/deque v1.0.0 // indirect 29 | github.com/go-jose/go-jose/v3 v3.0.4 // indirect 30 | github.com/go-logr/logr v1.4.2 // indirect 31 | github.com/go-logr/stdr v1.2.2 // indirect 32 | github.com/google/cel-go v0.22.1 // indirect 33 | github.com/google/uuid v1.6.0 // indirect 34 | github.com/gorilla/websocket v1.5.3 // indirect 35 | github.com/hashicorp/go-set/v3 v3.0.0 // indirect 36 | github.com/jxskiss/base62 v1.1.0 // indirect 37 | github.com/klauspost/compress v1.17.11 // indirect 38 | github.com/klauspost/cpuid/v2 v2.2.7 // indirect 39 | github.com/kr/pretty v0.3.1 // indirect 40 | github.com/lithammer/shortuuid/v4 v4.2.0 // indirect 41 | github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 // indirect 42 | github.com/livekit/mediatransportutil v0.0.0-20241220010243-a2bdee945564 // indirect 43 | github.com/livekit/psrpc v0.6.1-0.20250205181828-a0beed2e4126 // indirect 44 | github.com/magefile/mage v1.15.0 // indirect 45 | github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 // indirect 46 | github.com/nats-io/nats.go v1.38.0 // indirect 47 | github.com/nats-io/nkeys v0.4.9 // indirect 48 | github.com/nats-io/nuid v1.0.1 // indirect 49 | github.com/oleiade/lane/v2 v2.0.0 // indirect 50 | github.com/pion/datachannel v1.5.10 // indirect 51 | github.com/pion/dtls/v3 v3.0.4 // indirect 52 | github.com/pion/ice/v4 v4.0.6 // indirect 53 | github.com/pion/interceptor v0.1.39 // indirect 54 | github.com/pion/logging v0.2.3 // indirect 55 | github.com/pion/mdns/v2 v2.0.7 // indirect 56 | github.com/pion/randutil v0.1.0 // indirect 57 | github.com/pion/rtcp v1.2.15 // indirect 58 | github.com/pion/rtp v1.8.18 // indirect 59 | github.com/pion/sctp v1.8.35 // indirect 60 | github.com/pion/sdp/v3 v3.0.10 // indirect 61 | github.com/pion/srtp/v3 v3.0.4 // indirect 62 | github.com/pion/stun/v3 v3.0.0 // indirect 63 | github.com/pion/transport/v3 v3.0.7 // indirect 64 | github.com/pion/turn/v4 v4.0.0 // indirect 65 | github.com/pion/webrtc/v4 v4.0.9 // indirect 66 | github.com/puzpuzpuz/xsync/v3 v3.5.0 // indirect 67 | github.com/redis/go-redis/v9 v9.7.3 // indirect 68 | github.com/sirupsen/logrus v1.9.3 // indirect 69 | github.com/stoewer/go-strcase v1.3.0 // indirect 70 | github.com/tidwall/gjson v1.18.0 // indirect 71 | github.com/tidwall/match v1.1.1 // indirect 72 | github.com/tidwall/pretty v1.2.1 // indirect 73 | github.com/tidwall/sjson v1.2.5 // indirect 74 | github.com/twitchtv/twirp v8.1.3+incompatible // indirect 75 | github.com/wlynxg/anet v0.0.5 // indirect 76 | github.com/zeebo/xxh3 v1.0.2 // indirect 77 | go.uber.org/atomic v1.11.0 // indirect 78 | go.uber.org/multierr v1.11.0 // indirect 79 | go.uber.org/zap v1.27.0 // indirect 80 | go.uber.org/zap/exp v0.3.0 // indirect 81 | golang.org/x/crypto v0.38.0 // indirect 82 | golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 // indirect 83 | golang.org/x/net v0.40.0 // indirect 84 | golang.org/x/sync v0.14.0 // indirect 85 | golang.org/x/sys v0.33.0 // indirect 86 | golang.org/x/text v0.25.0 // indirect 87 | google.golang.org/genproto/googleapis/api v0.0.0-20241202173237-19429a94021a // indirect 88 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489 // indirect 89 | google.golang.org/grpc v1.70.0 // indirect 90 | google.golang.org/protobuf v1.36.5 // indirect 91 | gopkg.in/yaml.v3 v3.0.1 // indirect 92 | ) 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🎥 MatrixRTC Authorization Service 2 | 3 | The **MatrixRTC Authorization Service** bridges Matrix and LiveKit, handling 4 | authentication and room creation when needed. 5 | 6 | ## 💡 TL;DR 7 | 8 | Matrix user wants to start or join a call? 9 | 10 | 👤 ➡️ Gets OpenID token ➡️ Sends it to the **MatrixRTC Authorization Service** ➡️ 11 | Receives LiveKit JWT ➡️ 12 | 13 | - **If full-access user** ➡️ Can trigger LiveKit room creation (if needed) ➡️ 14 | Joins the call 🎉 15 | - **If restricted user** ➡️ Can join existing rooms ➡️ Joins the call 🎉 16 | 17 | 📡 Once connected, the LiveKit SFU handles all real-time media routing so 18 | participants can see and hear each other. 19 | 20 | ## 🏗️ MatrixRTC Stack: Architecture Overview 21 | 22 |

23 | MatrixRTC Architecture 24 |

25 | 26 | ## 📌 When to Use 27 | 28 | This service is part of the **MatrixRTC stack** and is primarily used when the 29 | [LiveKit RTC backend (MSC4195)](https://github.com/matrix-org/matrix-spec-proposals/pull/4195) 30 | is in use. 31 | 32 | As outlined in the 33 | [Element Call Self-Hosting Guide](https://github.com/element-hq/element-call/blob/livekit/docs/self-hosting.md), 34 | you’ll also need: 35 | 36 | - A [LiveKit SFU](https://github.com/livekit/livekit) 37 | - MatrixRTC-compatible clients such as 38 | [Element Call](https://github.com/element-hq/element-call), which can run 39 | either: 40 | - As a standalone Single Page Application (SPA) or 41 | - Embedded for in-app calling 42 | 43 | ## ✨ What It Does 44 | 45 | 🔑 **Generates JWT tokens** for a given LiveKit identity and room derived from 46 | the Matrix user and Matrix room, allowing users to authenticate with the LiveKit 47 | SFU. 48 | 49 | 🛡️ **Manages user access levels** to ensure the proper and secure use of 50 | infrastructure: 51 | 52 | - **Full-access users** — Matrix users from homeservers in the same or related 53 | deployment as the MatrixRTC backend. Can trigger automatic LiveKit room 54 | creation if needed. 55 | - **Restricted users** — All other Matrix users. Can join existing LiveKit SFU 56 | rooms, but cannot auto-create new ones. 57 | 58 | 🏗️ **Auto-creates LiveKit rooms** for full-access users if they don’t already 59 | exist. 60 | 61 | > [!NOTE] 62 | > This setup ensures resources are used appropriately while still supporting 63 | > seamless cross-federation MatrixRTC sessions, e.g., video calls. Remote users 64 | > (not on the same deployment) can join existing rooms, but only full-access 65 | > (local) users can trigger room creation. The SFU selection algorithm and event 66 | > ordering ensure that conferences across Matrix federation remain fully 67 | > functional. 68 | 69 | ## 🗺️ How It Works — Token Exchange Flow 70 | 71 | ```mermaid 72 | sequenceDiagram 73 | participant U as 🧑 User 74 | participant M as 🏢 Matrix Homeserver 75 | participant A as 🔐 MatrixRTC Authorization Service 76 | participant L as 📡 LiveKit SFU 77 | 78 | U->>M: Requests OpenID token 79 | M-->>U: Returns OpenID token 80 | U->>A: Sends OpenID token & room request 81 | A->>M: Validates token via OpenID API 82 | M-->>A: Confirms user identity 83 | A->>A: Generates LiveKit JWT 84 | A->>L: (If full-access user) Create room if missing 85 | A-->>U: Returns LiveKit JWT 86 | U->>L: Connects to room using JWT 87 | ``` 88 | 89 | ## 🚀 Installation 90 | 91 | Releases are available 92 | **[here](https://github.com/element-hq/lk-jwt-service/releases)**. 93 | 94 | ### 🐳 From Docker Image 95 | 96 | ```shell 97 | docker run -e LIVEKIT_URL="ws://somewhere" -e LIVEKIT_KEY=devkey -e LIVEKIT_SECRET=secret -e LIVEKIT_FULL_ACCESS_HOMESERVERS=example.com -p 8080:8080 ghcr.io/element-hq/lk-jwt-service:0.3.0 98 | ``` 99 | 100 | ### 📦 From Release 101 | 102 | 1. Download & mark as executable (example is amd64, replace with arm64 if needed): 103 | 104 | ```shell 105 | wget https://github.com/element-hq/lk-jwt-service/releases/latest/download/lk-jwt-service_linux_amd64 106 | chmod +x lk-jwt-service_linux_amd64 107 | ``` 108 | 109 | 3. Run locally: 110 | 111 | ```shell 112 | LIVEKIT_URL="ws://somewhere" LIVEKIT_KEY=devkey LIVEKIT_SECRET=secret LIVEKIT_FULL_ACCESS_HOMESERVERS=example.com ./lk-jwt-service_linux_amd64 113 | ``` 114 | 115 | ## ⚙️ Configuration 116 | 117 | Set environment variables to configure the service: 118 | 119 | | Variable | Description | Required | Default | 120 | | --------------------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------- | ------- | 121 | | `LIVEKIT_URL` | WebSocket URL of the LiveKit SFU | ✅ Yes | | 122 | | `LIVEKIT_KEY` / `LIVEKIT_KEY_FROM_FILE` | API key or file path for LiveKit SFU | ✅ Yes | | 123 | | `LIVEKIT_SECRET` / `LIVEKIT_SECRET_FROM_FILE` | API secret or file path for LiveKit SFU | ✅ Yes | | 124 | | `LIVEKIT_KEY_FILE` | File path with `APIkey: secret` format | ⚠️ mutually exclusive with LIVEKIT_{KEY|SECRET} | | 125 | | `LIVEKIT_JWT_BIND` | Address to bind the server to | ❌ No, ⚠️ mutually exclusive with `LIVEKIT_JWT_PORT` | `:8080` | 126 | | `LIVEKIT_JWT_PORT` | ⚠️ Deprecated Port to bind the server to | ❌ No, ⚠️ mutually exclusive with `LIVEKIT_JWT_BIND` | | 127 | | `LIVEKIT_FULL_ACCESS_HOMESERVERS` | Comma-separated list of full-access homeservers (`*` for all) | ❌ No | `*` | 128 | 129 | > [!IMPORTANT] 130 | > By default, the LiveKit SFU auto-creates rooms for all users. To ensure proper 131 | > access control, update your LiveKit 132 | > [config.yaml](https://github.com/livekit/livekit/blob/7350e9933107ecdea4ada8f8bcb0d6ca78b3f8f7/config-sample.yaml#L170) 133 | > to **disable automatic room creation**. 134 | 135 | **LiveKit SFU config should include:** 136 | 137 | ```yaml 138 | room: 139 | auto_create: false 140 | ``` 141 | 142 | ## 🔒 Transport Layer Security (TLS) Setup Using a Reverse Proxy 143 | 144 | To properly secure the MatrixRTC Authorization Service, a reverse proxy is 145 | recommended. 146 | 147 | ### Example Caddy Config 148 | 149 | ```caddy 150 | matrix-rtc.domain.tld { 151 | bind xx.xx.xx.xx 152 | 153 | handle /livekit/jwt* { 154 | reverse_proxy localhost:8080 155 | } 156 | } 157 | ``` 158 | 159 | ### Example Nginx Config 160 | 161 | ```nginx 162 | server { 163 | listen 80; 164 | server_name matrix-rtc.domain.tld; 165 | 166 | # Redirect HTTP → HTTPS 167 | return 301 https://$host$request_uri; 168 | } 169 | 170 | server { 171 | listen 443 ssl; 172 | server_name matrix-rtc.domain.tld; 173 | 174 | # TLS certificate paths (replace with your own) 175 | ssl_certificate /etc/ssl/certs/matrix-rtc.crt; 176 | ssl_certificate_key /etc/ssl/private/matrix-rtc.key; 177 | 178 | # TLS settings (minimal) 179 | ssl_protocols TLSv1.2 TLSv1.3; 180 | ssl_ciphers HIGH:!aNULL:!MD5; 181 | 182 | location /livekit/jwt/ { 183 | proxy_pass http://localhost:8080/; 184 | proxy_set_header Host $host; 185 | proxy_set_header X-Real-IP $remote_addr; 186 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 187 | proxy_set_header X-Forwarded-Proto $scheme; 188 | } 189 | } 190 | ``` 191 | 192 | ## 📌 Do Not Forget to Update Your Matrix Site's `.well-known/matrix/client` 193 | 194 | For proper MatrixRTC functionality, you need to configure your site's 195 | `.well-known/matrix/client`. See the 196 | [Element Call self-hosting guide](https://github.com/element-hq/element-call/blob/livekit/docs/self-hosting.md#matrixrtc-backend-announcement) 197 | for reference. 198 | 199 | The following key must be included in 200 | `https://domain.tld/.well-known/matrix/client`: 201 | 202 | ```json 203 | "org.matrix.msc4143.rtc_foci": [ 204 | { 205 | "type": "livekit", 206 | "livekit_service_url": "https://matrix-rtc.domain.tld/livekit/jwt" 207 | } 208 | ] 209 | ``` 210 | 211 | ## 🧪 Development & Testing 212 | 213 | ### Disable TLS verification 214 | 215 | For testing and debugging (e.g. in the absence of trusted certificates while 216 | testing in a lab), you can disable TLS verification for the outgoing connection 217 | to the Matrix homeserver by setting the environment variable 218 | `LIVEKIT_INSECURE_SKIP_VERIFY_TLS` to `YES_I_KNOW_WHAT_I_AM_DOING`. 219 | 220 | ### 🛠️ Development Environment (Docker Compose) 221 | 222 | Based on the 223 | [Element Call GitHub repo](https://github.com/element-hq/element-call) 224 | 225 | The easiest way to spin up the full Matrix stack is by using the development 226 | environment provided by Element Call. For detailed instructions, see 227 | [Element Call Backend Setup](https://github.com/element-hq/element-call?tab=readme-ov-file#backend). 228 | 229 | > [!NOTE] 230 | > To ensure your local frontend works properly, you need to add certificate 231 | > exceptions in your browser for: 232 | > 233 | > - `https://localhost:3000` 234 | > - `https://matrix-rtc.m.localhost/livekit/jwt/healthz` 235 | > - `https://synapse.m.localhost/.well-known/matrix/client` 236 | > 237 | > You can do this either by adding the minimal m.localhost CA 238 | > ([dev_tls_m.localhost.crt](https://raw.githubusercontent.com/element-hq/element-call/refs/heads/livekit/backend/dev_tls_m.localhost.crt)) 239 | > to your browser’s trusted certificates, or by visiting each URL in your 240 | > browser and following the prompts to accept the exception. 241 | 242 | #### 🐳 Start MatrixRTC stack without the MatrixRTC Authorization Service 243 | 244 | ```sh 245 | git clone https://github.com/element-hq/element-call.git 246 | cd element-call 247 | docker-compose -f ./dev-backend-docker-compose.yml -f ./playwright-backend-docker-compose.override.yml up nginx livekit synapse redis 248 | ``` 249 | 250 | #### 🔑 Start the MatrixRTC Authorization Service locally 251 | 252 | ```sh 253 | git clone https://github.com/element-hq/lk-jwt-service 254 | cd lk-jwt-service 255 | LIVEKIT_INSECURE_SKIP_VERIFY_TLS="YES_I_KNOW_WHAT_I_AM_DOING" \ 256 | LIVEKIT_URL="wss://matrix-rtc.m.localhost/livekit/sfu" \ 257 | LIVEKIT_KEY=devkey \ 258 | LIVEKIT_SECRET=secret \ 259 | LIVEKIT_JWT_PORT=6080 \ 260 | LIVEKIT_FULL_ACCESS_HOMESERVERS=synapse.m.localhost \ 261 | ./lk-jwt-service 262 | ``` 263 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2025 Element Creations Ltd. 2 | // Copyright 2023 - 2025 New Vector Ltd. 3 | // 4 | // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial 5 | // Please see LICENSE files in the repository root for full details. 6 | 7 | package main 8 | 9 | import ( 10 | "context" 11 | "crypto/sha256" 12 | "crypto/tls" 13 | "encoding/json" 14 | "errors" 15 | "fmt" 16 | "io" 17 | "log" 18 | "net/http" 19 | "os" 20 | "slices" 21 | "strings" 22 | 23 | "time" 24 | 25 | "github.com/livekit/protocol/auth" 26 | "github.com/livekit/protocol/livekit" 27 | lksdk "github.com/livekit/server-sdk-go/v2" 28 | 29 | "github.com/matrix-org/gomatrix" 30 | "github.com/matrix-org/gomatrixserverlib/fclient" 31 | "github.com/matrix-org/gomatrixserverlib/spec" 32 | ) 33 | 34 | type Handler struct { 35 | key, secret, lkUrl string 36 | fullAccessHomeservers []string 37 | skipVerifyTLS bool 38 | } 39 | type Config struct { 40 | Key string 41 | Secret string 42 | LkUrl string 43 | SkipVerifyTLS bool 44 | FullAccessHomeservers []string 45 | LkJwtBind string 46 | } 47 | type MatrixRTCMemberType struct { 48 | ID string `json:"id"` 49 | ClaimedUserID string `json:"claimed_user_id"` 50 | ClaimedDeviceID string `json:"claimed_device_id"` 51 | } 52 | 53 | type OpenIDTokenType struct { 54 | AccessToken string `json:"access_token"` 55 | TokenType string `json:"token_type"` 56 | MatrixServerName string `json:"matrix_server_name"` 57 | ExpiresIn int `json:"expires_in"` 58 | } 59 | 60 | type LegacySFURequest struct { 61 | Room string `json:"room"` 62 | OpenIDToken OpenIDTokenType `json:"openid_token"` 63 | DeviceID string `json:"device_id"` 64 | } 65 | 66 | type SFURequest struct { 67 | RoomID string `json:"room_id"` 68 | SlotID string `json:"slot_id"` 69 | OpenIDToken OpenIDTokenType `json:"openid_token"` 70 | Member MatrixRTCMemberType `json:"member"` 71 | DelayedEventID string `json:"delayed_event_id"` 72 | } 73 | type SFUResponse struct { 74 | URL string `json:"url"` 75 | JWT string `json:"jwt"` 76 | } 77 | 78 | type MatrixErrorResponse struct { 79 | Status int 80 | ErrCode string 81 | Err string 82 | } 83 | 84 | type ValidatableSFURequest interface { 85 | Validate() error 86 | } 87 | 88 | func (e *MatrixErrorResponse) Error() string { 89 | return e.Err 90 | } 91 | 92 | func (r *SFURequest) Validate() error { 93 | if r.RoomID == "" || r.SlotID == "" { 94 | log.Printf("Missing room_id or slot_id: room_id='%s', slot_id='%s'", r.RoomID, r.SlotID) 95 | return &MatrixErrorResponse{ 96 | Status: http.StatusBadRequest, 97 | ErrCode: "M_BAD_JSON", 98 | Err: "The request body is missing `room_id` or `slot_id`", 99 | } 100 | } 101 | if r.Member.ID == "" || r.Member.ClaimedUserID == "" || r.Member.ClaimedDeviceID == "" { 102 | log.Printf("Missing member parameters: %+v", r.Member) 103 | return &MatrixErrorResponse{ 104 | Status: http.StatusBadRequest, 105 | ErrCode: "M_BAD_JSON", 106 | Err: "The request body `member` is missing a `id`, `claimed_user_id` or `claimed_device_id`", 107 | } 108 | } 109 | if r.OpenIDToken.AccessToken == "" || r.OpenIDToken.MatrixServerName == "" { 110 | log.Printf("Missing OpenID token parameters: %+v", r.OpenIDToken) 111 | return &MatrixErrorResponse{ 112 | Status: http.StatusBadRequest, 113 | ErrCode: "M_BAD_JSON", 114 | Err: "The request body `openid_token` is missing a `access_token` or `matrix_server_name`", 115 | } 116 | } 117 | return nil 118 | } 119 | 120 | func (r *LegacySFURequest) Validate() error { 121 | if r.Room == "" { 122 | return &MatrixErrorResponse{ 123 | Status: http.StatusBadRequest, 124 | ErrCode: "M_BAD_JSON", 125 | Err: "Missing room parameter", 126 | } 127 | } 128 | if r.OpenIDToken.AccessToken == "" || r.OpenIDToken.MatrixServerName == "" { 129 | return &MatrixErrorResponse{ 130 | Status: http.StatusBadRequest, 131 | ErrCode: "M_BAD_JSON", 132 | Err: "Missing OpenID token parameters", 133 | } 134 | } 135 | return nil 136 | } 137 | 138 | // writeMatrixError writes a Matrix-style error response to the HTTP response writer. 139 | func writeMatrixError(w http.ResponseWriter, status int, errCode string, errMsg string) { 140 | w.WriteHeader(status) 141 | if err := json.NewEncoder(w).Encode(gomatrix.RespError{ 142 | ErrCode: errCode, 143 | Err: errMsg, 144 | }); err != nil { 145 | log.Printf("failed to encode json error message! %v", err) 146 | } 147 | } 148 | 149 | func getJoinToken(apiKey, apiSecret, room, identity string) (string, error) { 150 | at := auth.NewAccessToken(apiKey, apiSecret) 151 | 152 | canPublish := true 153 | canSubscribe := true 154 | grant := &auth.VideoGrant{ 155 | RoomJoin: true, 156 | RoomCreate: false, 157 | CanPublish: &canPublish, 158 | CanSubscribe: &canSubscribe, 159 | Room: room, 160 | } 161 | 162 | at.SetVideoGrant(grant). 163 | SetIdentity(identity). 164 | SetValidFor(time.Hour) 165 | 166 | return at.ToJWT() 167 | } 168 | 169 | var exchangeOpenIdUserInfo = func( 170 | ctx context.Context, token OpenIDTokenType, skipVerifyTLS bool, 171 | ) (*fclient.UserInfo, error) { 172 | if token.AccessToken == "" || token.MatrixServerName == "" { 173 | return nil, errors.New("missing parameters in openid token") 174 | } 175 | 176 | if skipVerifyTLS { 177 | log.Printf("!!! WARNING !!! Skipping TLS verification for matrix client connection to %s", token.MatrixServerName) 178 | // Disable TLS verification on the default HTTP Transport for the well-known lookup 179 | http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} 180 | } 181 | client := fclient.NewClient(fclient.WithWellKnownSRVLookups(true), fclient.WithSkipVerify(skipVerifyTLS)) 182 | 183 | // validate the openid token by getting the user's ID 184 | userinfo, err := client.LookupUserInfo( 185 | ctx, spec.ServerName(token.MatrixServerName), token.AccessToken, 186 | ) 187 | if err != nil { 188 | log.Printf("Failed to look up user info: %v", err) 189 | return nil, errors.New("failed to look up user info") 190 | } 191 | return &userinfo, nil 192 | } 193 | 194 | func (h *Handler) isFullAccessUser(matrixServerName string) bool { 195 | // Grant full access if wildcard '*' is present as the only entry 196 | if len(h.fullAccessHomeservers) == 1 && h.fullAccessHomeservers[0] == "*" { 197 | return true 198 | } 199 | 200 | // Check if the matrixServerName is in the list of full-access homeservers 201 | return slices.Contains(h.fullAccessHomeservers, matrixServerName) 202 | } 203 | 204 | func (h *Handler) processLegacySFURequest(r *http.Request, req *LegacySFURequest) (*SFUResponse, error) { 205 | // Note LegacySFURequest has already been validated at this point 206 | 207 | userInfo, err := exchangeOpenIdUserInfo(r.Context(), req.OpenIDToken, h.skipVerifyTLS) 208 | if err != nil { 209 | return nil, &MatrixErrorResponse{ 210 | Status: http.StatusInternalServerError, 211 | ErrCode: "M_LOOKUP_FAILED", 212 | Err: "Failed to look up user info from homeserver", 213 | } 214 | } 215 | 216 | isFullAccessUser := h.isFullAccessUser(req.OpenIDToken.MatrixServerName) 217 | 218 | log.Printf( 219 | "Got Matrix user info for %s (%s)", 220 | userInfo.Sub, 221 | map[bool]string{true: "full access", false: "restricted access"}[isFullAccessUser], 222 | ) 223 | 224 | // TODO: is DeviceID required? If so then we should have validated at the start 225 | lkIdentity := userInfo.Sub + ":" + req.DeviceID 226 | token, err := getJoinToken(h.key, h.secret, req.Room, lkIdentity) 227 | if err != nil { 228 | return nil, &MatrixErrorResponse{ 229 | Status: http.StatusInternalServerError, 230 | ErrCode: "M_UNKNOWN", 231 | Err: "Internal Server Error", 232 | } 233 | } 234 | 235 | if isFullAccessUser { 236 | if err := createLiveKitRoom(r.Context(), h, req.Room, userInfo.Sub, lkIdentity); err != nil { 237 | return nil, &MatrixErrorResponse{ 238 | Status: http.StatusInternalServerError, 239 | ErrCode: "M_UNKNOWN", 240 | Err: "Unable to create room on SFU", 241 | } 242 | } 243 | } 244 | 245 | return &SFUResponse{URL: h.lkUrl, JWT: token}, nil 246 | } 247 | 248 | func (h *Handler) processSFURequest(r *http.Request, req *SFURequest) (*SFUResponse, error) { 249 | // Note SFURequest has already been validated at this point 250 | 251 | userInfo, err := exchangeOpenIdUserInfo(r.Context(), req.OpenIDToken, h.skipVerifyTLS) 252 | if err != nil { 253 | return nil, &MatrixErrorResponse{ 254 | Status: http.StatusUnauthorized, 255 | ErrCode: "M_UNAUTHORIZED", 256 | Err: "The request could not be authorised.", 257 | } 258 | } 259 | 260 | // Check if validated userInfo.Sub matches req.Member.ClaimedUserID 261 | if req.Member.ClaimedUserID != userInfo.Sub { 262 | log.Printf("Claimed user ID %s does not match token subject %s", req.Member.ClaimedUserID, userInfo.Sub) 263 | return nil, &MatrixErrorResponse{ 264 | Status: http.StatusUnauthorized, 265 | ErrCode: "M_UNAUTHORIZED", 266 | Err: "The request could not be authorised.", 267 | } 268 | } 269 | 270 | // Does the user belong to homeservers granted full access 271 | isFullAccessUser := h.isFullAccessUser(req.OpenIDToken.MatrixServerName) 272 | 273 | log.Printf( 274 | "Got Matrix user info for %s (%s)", 275 | userInfo.Sub, 276 | map[bool]string{true: "full access", false: "restricted access"}[isFullAccessUser], 277 | ) 278 | 279 | lkIdentity := req.Member.ID 280 | lkRoomAlias := fmt.Sprintf("%x", sha256.Sum256([]byte(req.RoomID + "|" + req.SlotID))) 281 | token, err := getJoinToken(h.key, h.secret, lkRoomAlias, lkIdentity) 282 | if err != nil { 283 | log.Printf("Error getting LiveKit token: %v", err) 284 | return nil, &MatrixErrorResponse{ 285 | Status: http.StatusInternalServerError, 286 | ErrCode: "M_UNKNOWN", 287 | Err: "Internal Server Error", 288 | } 289 | } 290 | 291 | if isFullAccessUser { 292 | if err := createLiveKitRoom(r.Context(), h, lkRoomAlias, userInfo.Sub, lkIdentity); err != nil { 293 | return nil, &MatrixErrorResponse{ 294 | Status: http.StatusInternalServerError, 295 | ErrCode: "M_UNKNOWN", 296 | Err: "Unable to create room on SFU", 297 | } 298 | } 299 | } 300 | 301 | return &SFUResponse{URL: h.lkUrl, JWT: token}, nil 302 | } 303 | 304 | var createLiveKitRoom = func(ctx context.Context, h *Handler, room, matrixUser, lkIdentity string) error { 305 | roomClient := lksdk.NewRoomServiceClient(h.lkUrl, h.key, h.secret) 306 | creationStart := time.Now().Unix() 307 | lkRoom, err := roomClient.CreateRoom( 308 | ctx, 309 | &livekit.CreateRoomRequest{ 310 | Name: room, 311 | EmptyTimeout: 5 * 60, // 5 Minutes to keep the room open if no one joins 312 | DepartureTimeout: 20, // number of seconds to keep the room after everyone leaves 313 | MaxParticipants: 0, // 0 == no limitation 314 | }, 315 | ) 316 | 317 | if err != nil { 318 | return fmt.Errorf("unable to create room %s: %w", room, err) 319 | } 320 | 321 | // Log the room creation time and the user info 322 | isNewRoom := lkRoom.GetCreationTime() >= creationStart && lkRoom.GetCreationTime() <= time.Now().Unix() 323 | log.Printf( 324 | "%s LiveKit room sid: %s (alias: %s) for full-access Matrix user %s (LiveKit identity: %s)", 325 | map[bool]string{true: "Created", false: "Using"}[isNewRoom], 326 | lkRoom.Sid, room, matrixUser, lkIdentity, 327 | ) 328 | 329 | return nil 330 | } 331 | 332 | func (h *Handler) prepareMux() *http.ServeMux { 333 | 334 | mux := http.NewServeMux() 335 | mux.HandleFunc("/sfu/get", h.handle_legacy) // TODO: This is deprecated and will be removed in future versions 336 | mux.HandleFunc("/get_token", h.handle) 337 | mux.HandleFunc("/healthz", h.healthcheck) 338 | 339 | return mux 340 | } 341 | 342 | func (h *Handler) healthcheck(w http.ResponseWriter, r *http.Request) { 343 | log.Printf("Health check from %s", r.RemoteAddr) 344 | 345 | if r.Method == "GET" { 346 | w.WriteHeader(http.StatusOK) 347 | return 348 | } else { 349 | w.WriteHeader(http.StatusMethodNotAllowed) 350 | } 351 | } 352 | 353 | // TODO: This is deprecated and will be removed in future versions 354 | func mapSFURequest(data *[]byte) (any, error) { 355 | requestTypes := []ValidatableSFURequest{&LegacySFURequest{}, &SFURequest{}} 356 | for _, req := range requestTypes { 357 | decoder := json.NewDecoder(strings.NewReader(string(*data))) 358 | decoder.DisallowUnknownFields() 359 | if err := decoder.Decode(req); err == nil { 360 | if err := req.Validate(); err != nil { 361 | return nil, err 362 | } 363 | return req, nil 364 | } 365 | } 366 | 367 | return nil, &MatrixErrorResponse{ 368 | Status: http.StatusBadRequest, 369 | ErrCode: "M_BAD_JSON", 370 | Err: "The request body was malformed, missing required fields, or contained invalid values (e.g. missing `room_id`, `slot_id`, or `openid_token`).", 371 | } 372 | } 373 | 374 | // TODO: This is deprecated and will be removed in future versions 375 | func (h *Handler) handle_legacy(w http.ResponseWriter, r *http.Request) { 376 | log.Printf("Request from %s at \"%s\"", r.RemoteAddr, r.Header.Get("Origin")) 377 | 378 | w.Header().Set("Content-Type", "application/json") 379 | 380 | // Set the CORS headers 381 | w.Header().Set("Access-Control-Allow-Origin", "*") 382 | w.Header().Set("Access-Control-Allow-Methods", "POST") 383 | w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token") 384 | 385 | switch r.Method { 386 | case "OPTIONS": 387 | // Handle preflight request (CORS) 388 | w.WriteHeader(http.StatusOK) 389 | return 390 | case "POST": 391 | // Read request body once for later JSON parsing 392 | body, err := io.ReadAll(r.Body) 393 | if err != nil { 394 | log.Printf("Error reading request body: %v", err) 395 | writeMatrixError(w, http.StatusBadRequest, "M_NOT_JSON", "Error reading request") 396 | return 397 | } 398 | 399 | var sfuAccessResponse *SFUResponse 400 | 401 | sfuAccessRequest, err := mapSFURequest(&body) 402 | if err != nil { 403 | matrixErr := &MatrixErrorResponse{} 404 | if errors.As(err, &matrixErr) { 405 | log.Printf("Error processing request: %v", matrixErr.Err) 406 | writeMatrixError(w, matrixErr.Status, matrixErr.ErrCode, matrixErr.Err) 407 | return 408 | } 409 | } 410 | 411 | switch sfuReq := sfuAccessRequest.(type) { 412 | case *SFURequest: 413 | log.Printf("Processing SFU request") 414 | sfuAccessResponse, err = h.processSFURequest(r, sfuReq) 415 | case *LegacySFURequest: 416 | log.Printf("Processing legacy SFU request") 417 | sfuAccessResponse, err = h.processLegacySFURequest(r, sfuReq) 418 | } 419 | 420 | if err != nil { 421 | matrixErr := &MatrixErrorResponse{} 422 | if errors.As(err, &matrixErr) { 423 | log.Printf("Error processing request: %v", matrixErr.Err) 424 | writeMatrixError(w, matrixErr.Status, matrixErr.ErrCode, matrixErr.Err) 425 | return 426 | } 427 | } 428 | 429 | if err := json.NewEncoder(w).Encode(&sfuAccessResponse); err != nil { 430 | log.Printf("failed to encode json response! %v", err) 431 | } 432 | default: 433 | w.WriteHeader(http.StatusMethodNotAllowed) 434 | } 435 | } 436 | 437 | func (h *Handler) handle(w http.ResponseWriter, r *http.Request) { 438 | log.Printf("Request from %s at \"%s\"", r.RemoteAddr, r.Header.Get("Origin")) 439 | 440 | w.Header().Set("Content-Type", "application/json") 441 | 442 | // Set the CORS headers 443 | w.Header().Set("Access-Control-Allow-Origin", "*") 444 | w.Header().Set("Access-Control-Allow-Methods", "POST") 445 | w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token") 446 | 447 | // Handle preflight request (CORS) 448 | switch r.Method { 449 | case "OPTIONS": 450 | w.WriteHeader(http.StatusOK) 451 | return 452 | case "POST": 453 | var sfuAccessRequest SFURequest 454 | 455 | decoder := json.NewDecoder(r.Body) 456 | decoder.DisallowUnknownFields() 457 | if err := decoder.Decode(&sfuAccessRequest); err == nil { 458 | if err := sfuAccessRequest.Validate(); err != nil { 459 | matrixErr := &MatrixErrorResponse{} 460 | if errors.As(err, &matrixErr) { 461 | log.Printf("Error processing request: %v", matrixErr.Err) 462 | writeMatrixError(w, matrixErr.Status, matrixErr.ErrCode, matrixErr.Err) 463 | return 464 | } 465 | } 466 | } else { 467 | log.Printf("Error reading request body: %v", err) 468 | writeMatrixError(w, http.StatusBadRequest, "M_NOT_JSON", "Error reading request") 469 | return 470 | } 471 | 472 | log.Printf("Processing SFU request") 473 | sfuAccessResponse, err := h.processSFURequest(r, &sfuAccessRequest) 474 | 475 | if err != nil { 476 | matrixErr := &MatrixErrorResponse{} 477 | if errors.As(err, &matrixErr) { 478 | log.Printf("Error processing request: %v", matrixErr.Err) 479 | writeMatrixError(w, matrixErr.Status, matrixErr.ErrCode, matrixErr.Err) 480 | return 481 | } 482 | } 483 | 484 | if err := json.NewEncoder(w).Encode(&sfuAccessResponse); err != nil { 485 | log.Printf("failed to encode json response! %v", err) 486 | } 487 | 488 | default: 489 | w.WriteHeader(http.StatusMethodNotAllowed) 490 | } 491 | } 492 | 493 | func readKeySecret() (string, string) { 494 | // We initialize keys & secrets from environment variables 495 | key := os.Getenv("LIVEKIT_KEY") 496 | secret := os.Getenv("LIVEKIT_SECRET") 497 | // We initialize potential key & secret path from environment variables 498 | keyPath := os.Getenv("LIVEKIT_KEY_FROM_FILE") 499 | secretPath := os.Getenv("LIVEKIT_SECRET_FROM_FILE") 500 | keySecretPath := os.Getenv("LIVEKIT_KEY_FILE") 501 | 502 | // If keySecretPath is set we read the file and split it into two parts 503 | // It takes over any other initialization 504 | if keySecretPath != "" { 505 | if keySecretBytes, err := os.ReadFile(keySecretPath); err != nil { 506 | log.Fatal(err) 507 | } else { 508 | keySecrets := strings.Split(string(keySecretBytes), ":") 509 | if len(keySecrets) != 2 { 510 | log.Fatalf("invalid key secret file format!") 511 | } 512 | log.Printf("Using LiveKit API key and API secret from LIVEKIT_KEY_FILE") 513 | key = keySecrets[0] 514 | secret = keySecrets[1] 515 | } 516 | } else { 517 | // If keySecretPath is not set, we try to read the key and secret from files 518 | // If those files are not set, we return the key & secret from the environment variables 519 | if keyPath != "" { 520 | if keyBytes, err := os.ReadFile(keyPath); err != nil { 521 | log.Fatal(err) 522 | } else { 523 | log.Printf("Using LiveKit API key from LIVEKIT_KEY_FROM_FILE") 524 | key = string(keyBytes) 525 | } 526 | } 527 | 528 | if secretPath != "" { 529 | if secretBytes, err := os.ReadFile(secretPath); err != nil { 530 | log.Fatal(err) 531 | } else { 532 | log.Printf("Using LiveKit API secret from LIVEKIT_SECRET_FROM_FILE") 533 | secret = string(secretBytes) 534 | } 535 | } 536 | 537 | } 538 | 539 | // remove white spaces, new lines and carriage returns 540 | // from key and secret 541 | return strings.Trim(key, " \r\n"), strings.Trim(secret, " \r\n") 542 | } 543 | 544 | func parseConfig() (*Config, error) { 545 | skipVerifyTLS := os.Getenv("LIVEKIT_INSECURE_SKIP_VERIFY_TLS") == "YES_I_KNOW_WHAT_I_AM_DOING" 546 | if skipVerifyTLS { 547 | log.Printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 548 | log.Printf("!!! WARNING !!! LIVEKIT_INSECURE_SKIP_VERIFY_TLS !!! WARNING !!!") 549 | log.Printf("!!! WARNING !!! Allow to skip invalid TLS certificates !!! WARNING !!!") 550 | log.Printf("!!! WARNING !!! Use only for testing or debugging !!! WARNING !!!") 551 | log.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 552 | } 553 | 554 | key, secret := readKeySecret() 555 | lkUrl := os.Getenv("LIVEKIT_URL") 556 | 557 | if key == "" || secret == "" || lkUrl == "" { 558 | return nil, fmt.Errorf("LIVEKIT_KEY[_FILE], LIVEKIT_SECRET[_FILE] and LIVEKIT_URL environment variables must be set") 559 | } 560 | 561 | fullAccessHomeservers := os.Getenv("LIVEKIT_FULL_ACCESS_HOMESERVERS") 562 | 563 | if len(fullAccessHomeservers) == 0 { 564 | localHomeservers := os.Getenv("LIVEKIT_LOCAL_HOMESERVERS") 565 | if len(localHomeservers) > 0 { 566 | log.Printf("!!! LIVEKIT_LOCAL_HOMESERVERS is deprecated, please use LIVEKIT_FULL_ACCESS_HOMESERVERS instead !!!") 567 | fullAccessHomeservers = localHomeservers 568 | } else { 569 | log.Printf("LIVEKIT_FULL_ACCESS_HOMESERVERS not set, defaulting to wildcard (*) for full access") 570 | fullAccessHomeservers = "*" 571 | } 572 | } 573 | 574 | lkJwtBind := os.Getenv("LIVEKIT_JWT_BIND") 575 | lkJwtPort := os.Getenv("LIVEKIT_JWT_PORT") 576 | 577 | if lkJwtBind == "" { 578 | if lkJwtPort == "" { 579 | lkJwtPort = "8080" 580 | } else { 581 | log.Printf("!!! LIVEKIT_JWT_PORT is deprecated, please use LIVEKIT_JWT_BIND instead !!!") 582 | } 583 | lkJwtBind = fmt.Sprintf(":%s", lkJwtPort) 584 | } else if lkJwtPort != "" { 585 | return nil, fmt.Errorf("LIVEKIT_JWT_BIND and LIVEKIT_JWT_PORT environment variables MUST NOT be set together") 586 | } 587 | 588 | return &Config{ 589 | Key: key, 590 | Secret: secret, 591 | LkUrl: lkUrl, 592 | SkipVerifyTLS: skipVerifyTLS, 593 | FullAccessHomeservers: strings.Fields(strings.ReplaceAll(fullAccessHomeservers, ",", " ")), 594 | LkJwtBind: lkJwtBind, 595 | }, nil 596 | } 597 | 598 | func main() { 599 | config, err := parseConfig() 600 | if err != nil { 601 | log.Fatal(err) 602 | } 603 | 604 | log.Printf("LIVEKIT_URL: %s, LIVEKIT_JWT_BIND: %s", config.LkUrl, config.LkJwtBind) 605 | log.Printf("LIVEKIT_FULL_ACCESS_HOMESERVERS: %v", config.FullAccessHomeservers) 606 | 607 | handler := &Handler{ 608 | key: config.Key, 609 | secret: config.Secret, 610 | lkUrl: config.LkUrl, 611 | skipVerifyTLS: config.SkipVerifyTLS, 612 | fullAccessHomeservers: config.FullAccessHomeservers, 613 | } 614 | 615 | log.Fatal(http.ListenAndServe(config.LkJwtBind, handler.prepareMux())) 616 | } 617 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.0-20241127180247-a33202765966.1 h1:ntAj16eF7AtUyzOOAFk5gvbAO52QmUKPKk7GmsIEORo= 2 | buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.0-20241127180247-a33202765966.1/go.mod h1:AxRT+qTj5PJCz2nyQzsR/qxAcveW5USRhJTt/edTO5w= 3 | buf.build/go/protoyaml v0.3.1 h1:ucyzE7DRnjX+mQ6AH4JzN0Kg50ByHHu+yrSKbgQn2D4= 4 | buf.build/go/protoyaml v0.3.1/go.mod h1:0TzNpFQDXhwbkXb/ajLvxIijqbve+vMQvWY/b3/Dzxg= 5 | cel.dev/expr v0.19.0 h1:lXuo+nDhpyJSpWxpPVi5cPUwzKb+dsdOiw6IreM5yt0= 6 | cel.dev/expr v0.19.0/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= 7 | dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= 8 | dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= 9 | github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= 10 | github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= 11 | github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= 12 | github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= 13 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= 14 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= 15 | github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8TVTI= 16 | github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= 17 | github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= 18 | github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= 19 | github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= 20 | github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0= 21 | github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= 22 | github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= 23 | github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= 24 | github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= 25 | github.com/bufbuild/protovalidate-go v0.8.0 h1:Xs3kCLCJ4tQiogJ0iOXm+ClKw/KviW3nLAryCGW2I3Y= 26 | github.com/bufbuild/protovalidate-go v0.8.0/go.mod h1:JPWZInGm2y2NBg3vKDKdDIkvDjyLv31J3hLH5GIFc/Q= 27 | github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= 28 | github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= 29 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= 30 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 31 | github.com/containerd/continuity v0.4.3 h1:6HVkalIp+2u1ZLH1J/pYX2oBVXlJZvh1X1A7bEZ9Su8= 32 | github.com/containerd/continuity v0.4.3/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= 33 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 34 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 35 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 36 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 37 | github.com/dennwc/iters v1.0.1 h1:XwMudE6xtS0ugEdum4HQ+iRi+5HSvaeKxJPM/VI3pJs= 38 | github.com/dennwc/iters v1.0.1/go.mod h1:M9KuuMBeyEXYTmB7EnI9SCyALFCmPWOIxn5W1L0CjGg= 39 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= 40 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= 41 | github.com/docker/cli v26.1.4+incompatible h1:I8PHdc0MtxEADqYJZvhBrW9bo8gawKwwenxRM7/rLu8= 42 | github.com/docker/cli v26.1.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= 43 | github.com/docker/docker v27.1.1+incompatible h1:hO/M4MtV36kzKldqnA37IWhebRA+LnqqcqDja6kVaKY= 44 | github.com/docker/docker v27.1.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= 45 | github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= 46 | github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= 47 | github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= 48 | github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= 49 | github.com/envoyproxy/protoc-gen-validate v1.1.0 h1:tntQDh69XqOCOZsDz0lVJQez/2L6Uu2PdjCQwWCJ3bM= 50 | github.com/envoyproxy/protoc-gen-validate v1.1.0/go.mod h1:sXRDRVmzEbkM7CVcM06s9shE/m23dg3wzjl0UWqJ2q4= 51 | github.com/frostbyte73/core v0.1.1 h1:ChhJOR7bAKOCPbA+lqDLE2cGKlCG5JXsDvvQr4YaJIA= 52 | github.com/frostbyte73/core v0.1.1/go.mod h1:mhfOtR+xWAvwXiwor7jnqPMnu4fxbv1F2MwZ0BEpzZo= 53 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= 54 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= 55 | github.com/gammazero/deque v1.0.0 h1:LTmimT8H7bXkkCy6gZX7zNLtkbz4NdS2z8LZuor3j34= 56 | github.com/gammazero/deque v1.0.0/go.mod h1:iflpYvtGfM3U8S8j+sZEKIak3SAKYpA5/SQewgfXDKo= 57 | github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= 58 | github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= 59 | github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= 60 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= 61 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 62 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= 63 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= 64 | github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= 65 | github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= 66 | github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= 67 | github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= 68 | github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= 69 | github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= 70 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 71 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 72 | github.com/google/cel-go v0.22.1 h1:AfVXx3chM2qwoSbM7Da8g8hX8OVSkBFwX+rz2+PcK40= 73 | github.com/google/cel-go v0.22.1/go.mod h1:BuznPXXfQDpXKWQ9sPW3TzlAJN5zzFe+i9tIs0yC4s8= 74 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 75 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 76 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 77 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= 78 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= 79 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 80 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 81 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 82 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 83 | github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= 84 | github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= 85 | github.com/hashicorp/go-set/v3 v3.0.0 h1:CaJBQvQCOWoftrBcDt7Nwgo0kdpmrKxar/x2o6pV9JA= 86 | github.com/hashicorp/go-set/v3 v3.0.0/go.mod h1:IEghM2MpE5IaNvL+D7X480dfNtxjRXZ6VMpK3C8s2ok= 87 | github.com/jxskiss/base62 v1.1.0 h1:A5zbF8v8WXx2xixnAKD2w+abC+sIzYJX+nxmhA6HWFw= 88 | github.com/jxskiss/base62 v1.1.0/go.mod h1:HhWAlUXvxKThfOlZbcuFzsqwtF5TcqS9ru3y5GfjWAc= 89 | github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= 90 | github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= 91 | github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= 92 | github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= 93 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 94 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 95 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 96 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 97 | github.com/lithammer/shortuuid/v4 v4.2.0 h1:LMFOzVB3996a7b8aBuEXxqOBflbfPQAiVzkIcHO0h8c= 98 | github.com/lithammer/shortuuid/v4 v4.2.0/go.mod h1:D5noHZ2oFw/YaKCfGy0YxyE7M0wMbezmMjPdhyEFe6Y= 99 | github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 h1:jm09419p0lqTkDaKb5iXdynYrzB84ErPPO4LbRASk58= 100 | github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= 101 | github.com/livekit/mediatransportutil v0.0.0-20241220010243-a2bdee945564 h1:GX7KF/V9ExmcfT/2Bdia8aROjkxrgx7WpyH7w9MB4J4= 102 | github.com/livekit/mediatransportutil v0.0.0-20241220010243-a2bdee945564/go.mod h1:36s+wwmU3O40IAhE+MjBWP3W71QRiEE9SfooSBvtBqY= 103 | github.com/livekit/protocol v1.34.0 h1:hbIXgNW+JPiTcGjzNg1XgQg3Wqa2R5dBhzuy+LLEIS4= 104 | github.com/livekit/protocol v1.34.0/go.mod h1:yXuQ7ucrLj91nbxL6/AHgtxdha1DGzLj1LkgvnT90So= 105 | github.com/livekit/psrpc v0.6.1-0.20250205181828-a0beed2e4126 h1:fzuYpAQbCid7ySPpQWWePfQOWUrs8x6dJ0T3Wl07n+Y= 106 | github.com/livekit/psrpc v0.6.1-0.20250205181828-a0beed2e4126/go.mod h1:X5WtEZ7OnEs72Fi5/J+i0on3964F1aynQpCalcgMqRo= 107 | github.com/livekit/server-sdk-go/v2 v2.5.0 h1:HCKm3f6PvefGp8emNC2mi9+9IXzBYrynuGbtUdp5u+w= 108 | github.com/livekit/server-sdk-go/v2 v2.5.0/go.mod h1:98/Sa+Wgb27ABwu0WYxLaMZaRfGljrrtoZDQ2xA4oVg= 109 | github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg= 110 | github.com/magefile/mage v1.15.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= 111 | github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 h1:kHKxCOLcHH8r4Fzarl4+Y3K5hjothkVW5z7T1dUM11U= 112 | github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530/go.mod h1:/gBX06Kw0exX1HrwmoBibFA98yBk/jxKpGVeyQbff+s= 113 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250619052822-904c8f04597e h1:SWediqisy1Eoumr06sjGaA6gt6gS4FtXe00VB6fSNZw= 114 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250619052822-904c8f04597e/go.mod h1:61LpEsWAroRfdVh2dnr6fQ+K3MmRgD5I35GVvF4FpXQ= 115 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250704071233-a234d6df21c7 h1:WAcUwx+ZCK8znn1etraC2JWTns3ppcH6/gVQLfrCAnI= 116 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250704071233-a234d6df21c7/go.mod h1:61LpEsWAroRfdVh2dnr6fQ+K3MmRgD5I35GVvF4FpXQ= 117 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250815065806-6697d93cbcba h1:vUUjTOXZ/bYdF/SmJPH8HZ/UTmvw+ldngFKVLElmn+I= 118 | github.com/matrix-org/gomatrixserverlib v0.0.0-20250815065806-6697d93cbcba/go.mod h1:b6KVfDjXjA5Q7vhpOaMqIhFYvu5BuFVZixlNeTV/CLc= 119 | github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y= 120 | github.com/matrix-org/util v0.0.0-20221111132719-399730281e66/go.mod h1:iBI1foelCqA09JJgPV0FYz4qA5dUXYOxMi57FxKBdd4= 121 | github.com/miekg/dns v1.1.66 h1:FeZXOS3VCVsKnEAd+wBkjMC3D2K+ww66Cq3VnCINuJE= 122 | github.com/miekg/dns v1.1.66/go.mod h1:jGFzBsSNbJw6z1HYut1RKBKHA9PBdxeHrZG8J+gC2WE= 123 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 124 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 125 | github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= 126 | github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= 127 | github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= 128 | github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= 129 | github.com/nats-io/nats.go v1.38.0 h1:A7P+g7Wjp4/NWqDOOP/K6hfhr54DvdDQUznt5JFg9XA= 130 | github.com/nats-io/nats.go v1.38.0/go.mod h1:IGUM++TwokGnXPs82/wCuiHS02/aKrdYUQkU8If6yjw= 131 | github.com/nats-io/nkeys v0.4.9 h1:qe9Faq2Gxwi6RZnZMXfmGMZkg3afLLOtrU+gDZJ35b0= 132 | github.com/nats-io/nkeys v0.4.9/go.mod h1:jcMqs+FLG+W5YO36OX6wFIFcmpdAns+w1Wm6D3I/evE= 133 | github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= 134 | github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= 135 | github.com/oleiade/lane/v2 v2.0.0 h1:XW/ex/Inr+bPkLd3O240xrFOhUkTd4Wy176+Gv0E3Qw= 136 | github.com/oleiade/lane/v2 v2.0.0/go.mod h1:i5FBPFAYSWCgLh58UkUGCChjcCzef/MI7PlQm2TKCeg= 137 | github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= 138 | github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= 139 | github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= 140 | github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= 141 | github.com/opencontainers/runc v1.1.13 h1:98S2srgG9vw0zWcDpFMn5TRrh8kLxa/5OFUstuUhmRs= 142 | github.com/opencontainers/runc v1.1.13/go.mod h1:R016aXacfp/gwQBYw2FDGa9m+n6atbLWrYY8hNMT/sA= 143 | github.com/ory/dockertest/v3 v3.11.0 h1:OiHcxKAvSDUwsEVh2BjxQQc/5EHz9n0va9awCtNGuyA= 144 | github.com/ory/dockertest/v3 v3.11.0/go.mod h1:VIPxS1gwT9NpPOrfD3rACs8Y9Z7yhzO4SB194iUDnUI= 145 | github.com/pion/datachannel v1.5.10 h1:ly0Q26K1i6ZkGf42W7D4hQYR90pZwzFOjTq5AuCKk4o= 146 | github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oLo8Rs4Py/M= 147 | github.com/pion/dtls/v3 v3.0.4 h1:44CZekewMzfrn9pmGrj5BNnTMDCFwr+6sLH+cCuLM7U= 148 | github.com/pion/dtls/v3 v3.0.4/go.mod h1:R373CsjxWqNPf6MEkfdy3aSe9niZvL/JaKlGeFphtMg= 149 | github.com/pion/ice/v4 v4.0.6 h1:jmM9HwI9lfetQV/39uD0nY4y++XZNPhvzIPCb8EwxUM= 150 | github.com/pion/ice/v4 v4.0.6/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw= 151 | github.com/pion/interceptor v0.1.39 h1:Y6k0bN9Y3Lg/Wb21JBWp480tohtns8ybJ037AGr9UuA= 152 | github.com/pion/interceptor v0.1.39/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic= 153 | github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI= 154 | github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90= 155 | github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM= 156 | github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA= 157 | github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= 158 | github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= 159 | github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo= 160 | github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0= 161 | github.com/pion/rtp v1.8.18 h1:yEAb4+4a8nkPCecWzQB6V/uEU18X1lQCGAQCjP+pyvU= 162 | github.com/pion/rtp v1.8.18/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk= 163 | github.com/pion/sctp v1.8.35 h1:qwtKvNK1Wc5tHMIYgTDJhfZk7vATGVHhXbUDfHbYwzA= 164 | github.com/pion/sctp v1.8.35/go.mod h1:EcXP8zCYVTRy3W9xtOF7wJm1L1aXfKRQzaM33SjQlzg= 165 | github.com/pion/sdp/v3 v3.0.10 h1:6MChLE/1xYB+CjumMw+gZ9ufp2DPApuVSnDT8t5MIgA= 166 | github.com/pion/sdp/v3 v3.0.10/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E= 167 | github.com/pion/srtp/v3 v3.0.4 h1:2Z6vDVxzrX3UHEgrUyIGM4rRouoC7v+NiF1IHtp9B5M= 168 | github.com/pion/srtp/v3 v3.0.4/go.mod h1:1Jx3FwDoxpRaTh1oRV8A/6G1BnFL+QI82eK4ms8EEJQ= 169 | github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw= 170 | github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU= 171 | github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0= 172 | github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo= 173 | github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM= 174 | github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA= 175 | github.com/pion/webrtc/v4 v4.0.9 h1:PyOYMRKJgfy0dzPcYtFD/4oW9zaw3Ze3oZzzbj2LV9E= 176 | github.com/pion/webrtc/v4 v4.0.9/go.mod h1:ViHLVaNpiuvaH8pdiuQxuA9awuE6KVzAXx3vVWilOck= 177 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 178 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 179 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 180 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 181 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 182 | github.com/puzpuzpuz/xsync/v3 v3.5.0 h1:i+cMcpEDY1BkNm7lPDkCtE4oElsYLn+EKF8kAu2vXT4= 183 | github.com/puzpuzpuz/xsync/v3 v3.5.0/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA= 184 | github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= 185 | github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= 186 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 187 | github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= 188 | github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= 189 | github.com/shoenig/test v1.7.0 h1:eWcHtTXa6QLnBvm0jgEabMRN/uJ4DMV3M8xUGgRkZmk= 190 | github.com/shoenig/test v1.7.0/go.mod h1:UxJ6u/x2v/TNs/LoLxBNJRV9DiwBBKYxXSyczsBHFoI= 191 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= 192 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= 193 | github.com/stoewer/go-strcase v1.3.0 h1:g0eASXYtp+yvN9fK8sH94oCIk0fau9uV1/ZdJ0AVEzs= 194 | github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= 195 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 196 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 197 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 198 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 199 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 200 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 201 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 202 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 203 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 204 | github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 205 | github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= 206 | github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 207 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= 208 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= 209 | github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 210 | github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= 211 | github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 212 | github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= 213 | github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= 214 | github.com/twitchtv/twirp v8.1.3+incompatible h1:+F4TdErPgSUbMZMwp13Q/KgDVuI7HJXP61mNV3/7iuU= 215 | github.com/twitchtv/twirp v8.1.3+incompatible/go.mod h1:RRJoFSAmTEh2weEqWtpPE3vFK5YBhA6bqp2l1kfCC5A= 216 | github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= 217 | github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= 218 | github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= 219 | github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= 220 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= 221 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= 222 | github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= 223 | github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= 224 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 225 | github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= 226 | github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= 227 | github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= 228 | github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= 229 | go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= 230 | go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= 231 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= 232 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= 233 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 234 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 235 | go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= 236 | go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= 237 | go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= 238 | go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= 239 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 240 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 241 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= 242 | golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= 243 | golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= 244 | golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 h1:qNgPs5exUA+G0C96DrPwNrvLSj7GT/9D+3WMWUcUg34= 245 | golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= 246 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 247 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 248 | golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= 249 | golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= 250 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 251 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 252 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 253 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 254 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 255 | golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY= 256 | golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= 257 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 258 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 259 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 260 | golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= 261 | golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= 262 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 263 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 264 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 265 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 266 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 267 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 268 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 269 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 270 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 271 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= 272 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 273 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 274 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 275 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 276 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= 277 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= 278 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 279 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 280 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 281 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 282 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 283 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 284 | golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= 285 | golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= 286 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 287 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 288 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 289 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 290 | golang.org/x/tools v0.33.0 h1:4qz2S3zmRxbGIhDIAgjxvFutSvH5EfnsYrRBj0UI0bc= 291 | golang.org/x/tools v0.33.0/go.mod h1:CIJMaWEY88juyUfo7UbgPqbC8rU2OqfAV1h2Qp0oMYI= 292 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 293 | google.golang.org/genproto/googleapis/api v0.0.0-20241202173237-19429a94021a h1:OAiGFfOiA0v9MRYsSidp3ubZaBnteRUyn3xB2ZQ5G/E= 294 | google.golang.org/genproto/googleapis/api v0.0.0-20241202173237-19429a94021a/go.mod h1:jehYqy3+AhJU9ve55aNOaSml7wUXjF9x6z2LcCfpAhY= 295 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489 h1:5bKytslY8ViY0Cj/ewmRtrWHW64bNF03cAatUUFCdFI= 296 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk= 297 | google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= 298 | google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= 299 | google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= 300 | google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 301 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 302 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 303 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 304 | gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY= 305 | gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0= 306 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 307 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 308 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 309 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 310 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 311 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | 634 | Copyright (C) {{ year }} {{ organization }} 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU Affero General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU Affero General Public License for more details. 645 | 646 | You should have received a copy of the GNU Affero General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper mail. 650 | 651 | If your software can interact with users remotely through a computer 652 | network, you should also make sure that it provides a way for users to 653 | get its source. For example, if your program is a web application, its 654 | interface could display a "Source" link that leads users to an archive 655 | of the code. There are many ways you could offer source, and different 656 | solutions will be better for different programs; see section 13 for the 657 | specific requirements. 658 | 659 | You should also get your employer (if you work as a programmer) or school, 660 | if any, to sign a "copyright disclaimer" for the program, if necessary. 661 | For more information on this, and how to apply and follow the GNU AGPL, see 662 | . 663 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2025 Element Creations Ltd. 2 | // Copyright 2025 New Vector Ltd. 3 | // 4 | // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial 5 | // Please see LICENSE files in the repository root for full details. 6 | 7 | package main 8 | 9 | import ( 10 | "bytes" 11 | "context" 12 | "crypto/sha256" 13 | "encoding/json" 14 | "errors" 15 | "fmt" 16 | "net/http" 17 | "net/http/httptest" 18 | "net/url" 19 | "os" 20 | "reflect" 21 | "runtime" 22 | "strings" 23 | "testing" 24 | 25 | "github.com/golang-jwt/jwt/v5" 26 | "github.com/matrix-org/gomatrix" 27 | "github.com/matrix-org/gomatrixserverlib/fclient" 28 | ) 29 | 30 | func TestHealthcheck(t *testing.T) { 31 | handler := &Handler{} 32 | req, err := http.NewRequest("GET", "/healthz", nil) 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | 37 | rr := httptest.NewRecorder() 38 | handler.prepareMux().ServeHTTP(rr, req) 39 | 40 | if status := rr.Code; status != http.StatusOK { 41 | t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) 42 | } 43 | } 44 | 45 | func TestHandleOptions(t *testing.T) { 46 | handler := &Handler{} 47 | req, err := http.NewRequest("OPTIONS", "/sfu/get", nil) 48 | if err != nil { 49 | t.Fatal(err) 50 | } 51 | 52 | rr := httptest.NewRecorder() 53 | handler.prepareMux().ServeHTTP(rr, req) 54 | 55 | if status := rr.Code; status != http.StatusOK { 56 | t.Errorf("handler returned wrong status code for OPTIONS: got %v want %v", status, http.StatusOK) 57 | } 58 | 59 | if accessControlAllowOrigin := rr.Header().Get("Access-Control-Allow-Origin"); accessControlAllowOrigin != "*" { 60 | t.Errorf("handler returned wrong Access-Control-Allow-Origin: got %v want %v", accessControlAllowOrigin, "*") 61 | } 62 | 63 | if accessControlAllowMethods := rr.Header().Get("Access-Control-Allow-Methods"); accessControlAllowMethods != "POST" { 64 | t.Errorf("handler returned wrong Access-Control-Allow-Methods: got %v want %v", accessControlAllowMethods, "POST") 65 | } 66 | } 67 | 68 | func TestHandlePostMissingParams(t *testing.T) { 69 | handler := &Handler{} 70 | 71 | testCases := []map[string]interface{}{ 72 | {}, 73 | { 74 | "room": "", 75 | }, 76 | } 77 | 78 | for _, testCase := range testCases { 79 | jsonBody, _ := json.Marshal(testCase) 80 | 81 | req, err := http.NewRequest("POST", "/sfu/get", bytes.NewBuffer(jsonBody)) 82 | if err != nil { 83 | t.Fatal(err) 84 | } 85 | 86 | rr := httptest.NewRecorder() 87 | handler.prepareMux().ServeHTTP(rr, req) 88 | 89 | if status := rr.Code; status != http.StatusBadRequest { 90 | t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) 91 | } 92 | 93 | var resp gomatrix.RespError 94 | err = json.NewDecoder(rr.Body).Decode(&resp) 95 | if err != nil { 96 | t.Errorf("failed to decode response body %v", err) 97 | } 98 | 99 | if resp.ErrCode != "M_BAD_JSON" { 100 | t.Errorf("unexpected error code: got %v want %v", resp.ErrCode, "M_BAD_JSON") 101 | } 102 | } 103 | } 104 | 105 | func TestHandlePost(t *testing.T) { 106 | handler := &Handler{ 107 | secret: "testSecret", 108 | key: "testKey", 109 | lkUrl: "wss://lk.local:8080/foo", 110 | fullAccessHomeservers: []string{"example.com"}, 111 | skipVerifyTLS: true, 112 | } 113 | 114 | var matrixServerName = "" 115 | 116 | testServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 117 | t.Log("Received request") 118 | // Inspect the request 119 | if r.URL.Path != "/_matrix/federation/v1/openid/userinfo" { 120 | t.Errorf("unexpected request path: got %v want %v", r.URL.Path, "/_matrix/federation/v1/openid/userinfo") 121 | } 122 | 123 | if accessToken := r.URL.Query().Get("access_token"); accessToken != "testAccessToken" { 124 | t.Errorf("unexpected access token: got %v want %v", accessToken, "testAccessToken") 125 | } 126 | 127 | // Mock response 128 | w.WriteHeader(http.StatusOK) 129 | w.Header().Set("Content-Type", "application/json") 130 | _, err := fmt.Fprintf(w, `{"sub": "@user:%s"}`, matrixServerName) 131 | if err != nil { 132 | t.Fatalf("failed to write response: %v", err) 133 | } 134 | })) 135 | defer testServer.Close() 136 | 137 | u, _ := url.Parse(testServer.URL) 138 | 139 | matrixServerName = u.Host 140 | 141 | testCase := map[string]interface{}{ 142 | "room_id": "!testRoom:example.com", 143 | "slot_id": "m.call#ROOM", 144 | "openid_token": map[string]interface{}{ 145 | "access_token": "testAccessToken", 146 | "token_type": "testTokenType", 147 | "matrix_server_name": u.Host, 148 | "expires_in": 3600, 149 | }, 150 | "member": map[string]interface{}{ 151 | "id": "member_test_id", 152 | "claimed_user_id": "@user:" + matrixServerName, 153 | "claimed_device_id": "testDevice", 154 | }, 155 | } 156 | 157 | jsonBody, _ := json.Marshal(testCase) 158 | 159 | req, err := http.NewRequest("POST", "/get_token", bytes.NewBuffer(jsonBody)) 160 | if err != nil { 161 | t.Fatal(err) 162 | } 163 | 164 | rr := httptest.NewRecorder() 165 | handler.prepareMux().ServeHTTP(rr, req) 166 | 167 | if status := rr.Code; status != http.StatusOK { 168 | t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) 169 | } 170 | 171 | if contentType := rr.Header().Get("Content-Type"); contentType != "application/json" { 172 | t.Errorf("handler returned wrong Content-Type: got %v want %v", contentType, "application/json") 173 | } 174 | 175 | var resp SFUResponse 176 | err = json.NewDecoder(rr.Body).Decode(&resp) 177 | if err != nil { 178 | t.Errorf("failed to decode response body %v", err) 179 | } 180 | 181 | if resp.URL != "wss://lk.local:8080/foo" { 182 | t.Errorf("unexpected URL: got %v want %v", resp.URL, "wss://lk.local:8080/foo") 183 | } 184 | 185 | if resp.JWT == "" { 186 | t.Error("expected JWT to be non-empty") 187 | } 188 | 189 | // parse JWT checking the shared secret 190 | token, err := jwt.Parse(resp.JWT, func(token *jwt.Token) (interface{}, error) { 191 | return []byte(handler.secret), nil 192 | }) 193 | 194 | if err != nil { 195 | t.Fatalf("failed to parse JWT: %v", err) 196 | } 197 | 198 | claims, ok := token.Claims.(jwt.MapClaims) 199 | 200 | if !ok || !token.Valid { 201 | t.Fatalf("failed to parse claims from JWT: %v", err) 202 | } 203 | 204 | if claims["sub"] != "member_test_id" { 205 | t.Errorf("unexpected sub: got %v want %v", claims["sub"], "member_test_id") 206 | } 207 | 208 | // should have permission for the room 209 | want_room := fmt.Sprintf("%x", sha256.Sum256([]byte("!testRoom:example.com" + "|" + "m.call#ROOM"))) 210 | if claims["video"].(map[string]interface{})["room"] != want_room { 211 | t.Errorf("unexpected room: got %v want %v", claims["video"].(map[string]interface{})["room"], want_room) 212 | } 213 | } 214 | 215 | func TestLegacyHandlePost(t *testing.T) { 216 | handler := &Handler{ 217 | secret: "testSecret", 218 | key: "testKey", 219 | lkUrl: "wss://lk.local:8080/foo", 220 | fullAccessHomeservers: []string{"example.com"}, 221 | skipVerifyTLS: true, 222 | } 223 | 224 | var matrixServerName = "" 225 | 226 | testServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 227 | t.Log("Received request") 228 | // Inspect the request 229 | if r.URL.Path != "/_matrix/federation/v1/openid/userinfo" { 230 | t.Errorf("unexpected request path: got %v want %v", r.URL.Path, "/_matrix/federation/v1/openid/userinfo") 231 | } 232 | 233 | if accessToken := r.URL.Query().Get("access_token"); accessToken != "testAccessToken" { 234 | t.Errorf("unexpected access token: got %v want %v", accessToken, "testAccessToken") 235 | } 236 | 237 | // Mock response 238 | w.WriteHeader(http.StatusOK) 239 | w.Header().Set("Content-Type", "application/json") 240 | _, err := fmt.Fprintf(w, `{"sub": "@user:%s"}`, matrixServerName) 241 | if err != nil { 242 | t.Fatalf("failed to write response: %v", err) 243 | } 244 | })) 245 | defer testServer.Close() 246 | 247 | u, _ := url.Parse(testServer.URL) 248 | 249 | matrixServerName = u.Host 250 | 251 | testCase := map[string]interface{}{ 252 | "room": "testRoom", 253 | "openid_token": map[string]interface{}{ 254 | "access_token": "testAccessToken", 255 | "token_type": "testTokenType", 256 | "matrix_server_name": u.Host, 257 | "expires_in": 3600, 258 | }, 259 | "device_id": "testDevice", 260 | } 261 | 262 | jsonBody, _ := json.Marshal(testCase) 263 | 264 | req, err := http.NewRequest("POST", "/sfu/get", bytes.NewBuffer(jsonBody)) 265 | if err != nil { 266 | t.Fatal(err) 267 | } 268 | 269 | rr := httptest.NewRecorder() 270 | handler.prepareMux().ServeHTTP(rr, req) 271 | 272 | if status := rr.Code; status != http.StatusOK { 273 | t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) 274 | } 275 | 276 | if contentType := rr.Header().Get("Content-Type"); contentType != "application/json" { 277 | t.Errorf("handler returned wrong Content-Type: got %v want %v", contentType, "application/json") 278 | } 279 | 280 | var resp SFUResponse 281 | err = json.NewDecoder(rr.Body).Decode(&resp) 282 | if err != nil { 283 | t.Errorf("failed to decode response body %v", err) 284 | } 285 | 286 | if resp.URL != "wss://lk.local:8080/foo" { 287 | t.Errorf("unexpected URL: got %v want %v", resp.URL, "wss://lk.local:8080/foo") 288 | } 289 | 290 | if resp.JWT == "" { 291 | t.Error("expected JWT to be non-empty") 292 | } 293 | 294 | // parse JWT checking the shared secret 295 | token, err := jwt.Parse(resp.JWT, func(token *jwt.Token) (interface{}, error) { 296 | return []byte(handler.secret), nil 297 | }) 298 | 299 | if err != nil { 300 | t.Fatalf("failed to parse JWT: %v", err) 301 | } 302 | 303 | claims, ok := token.Claims.(jwt.MapClaims) 304 | 305 | if !ok || !token.Valid { 306 | t.Fatalf("failed to parse claims from JWT: %v", err) 307 | } 308 | 309 | if claims["sub"] != "@user:"+matrixServerName+":testDevice" { 310 | t.Errorf("unexpected sub: got %v want %v", claims["sub"], "@user:"+matrixServerName+":testDevice") 311 | } 312 | 313 | // should have permission for the room 314 | if claims["video"].(map[string]interface{})["room"] != "testRoom" { 315 | t.Errorf("unexpected room: got %v want %v", claims["room"], "testRoom") 316 | } 317 | } 318 | 319 | func TestIsFullAccessUser(t *testing.T) { 320 | handler := &Handler{ 321 | secret: "testSecret", 322 | key: "testKey", 323 | lkUrl: "wss://lk.local:8080/foo", 324 | fullAccessHomeservers: []string{"example.com", "another.example.com"}, 325 | skipVerifyTLS: true, 326 | } 327 | 328 | // Test cases for full access users 329 | if handler.isFullAccessUser("example.com") { 330 | t.Log("User has full access") 331 | } else { 332 | t.Error("User has restricted access") 333 | } 334 | 335 | if handler.isFullAccessUser("another.example.com") { 336 | t.Log("User has full access") 337 | } else { 338 | t.Error("User has restricted access") 339 | } 340 | 341 | // Test cases for restricted access users 342 | if handler.isFullAccessUser("aanother.example.com") { 343 | t.Error("User has full access") 344 | } else { 345 | t.Log("User has restricted access") 346 | } 347 | 348 | if handler.isFullAccessUser("matrix.example.com") { 349 | t.Error("User has full access") 350 | } else { 351 | t.Log("User has restricted access") 352 | } 353 | 354 | // test wildcard access 355 | handler.fullAccessHomeservers = []string{"*"} 356 | if handler.isFullAccessUser("other.com") { 357 | t.Log("User has full access") 358 | } else { 359 | t.Error("User has restricted access") 360 | } 361 | } 362 | 363 | func TestGetJoinToken(t *testing.T) { 364 | apiKey := "testKey" 365 | apiSecret := "testSecret" 366 | room := "testRoom" 367 | identity := "testIdentity@example.com" 368 | 369 | tokenString, err := getJoinToken(apiKey, apiSecret, room, identity) 370 | if err != nil { 371 | t.Fatalf("unexpected error: %v", err) 372 | } 373 | 374 | if tokenString == "" { 375 | t.Error("expected token to be non-empty") 376 | } 377 | 378 | // parse JWT checking the shared secret 379 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 380 | return []byte(apiSecret), nil 381 | }) 382 | claims, ok := token.Claims.(jwt.MapClaims) 383 | 384 | if !ok || !token.Valid { 385 | t.Fatalf("failed to parse claims from JWT: %v", err) 386 | } 387 | 388 | claimRoomCreate := claims["video"].(map[string]interface{})["roomCreate"] 389 | if claimRoomCreate == nil { 390 | claimRoomCreate = false 391 | } 392 | 393 | if claimRoomCreate == true { 394 | t.Fatalf("roomCreate property needs to be false, since the lk-jwt-service creates the room") 395 | } 396 | } 397 | 398 | func TestReadKeySecret(t *testing.T) { 399 | testCases := []struct { 400 | name string 401 | env map[string]string 402 | expectedKey string 403 | expectedSecret string 404 | err bool 405 | }{ 406 | { 407 | name: "Read from env", 408 | env: map[string]string{ 409 | "LIVEKIT_KEY": "from_env_pheethiewixohp9eecheeGhuayeeph4l", 410 | "LIVEKIT_SECRET": "from_env_ahb8eiwae0viey7gee4ieNgahgeeQuie", 411 | }, 412 | expectedKey: "from_env_pheethiewixohp9eecheeGhuayeeph4l", 413 | expectedSecret: "from_env_ahb8eiwae0viey7gee4ieNgahgeeQuie", 414 | err: false, 415 | }, 416 | { 417 | name: "Read from livekit keysecret", 418 | env: map[string]string{ 419 | "LIVEKIT_KEY_FILE": "./tests/keysecret.yaml", 420 | }, 421 | expectedKey: "keysecret_iethuB2LeLiNuishiaKeephei9jaatio", 422 | expectedSecret: "keysecret_xefaingo4oos6ohla9phiMieBu3ohJi2", 423 | }, 424 | { 425 | name: "Read from file", 426 | env: map[string]string{ 427 | "LIVEKIT_KEY_FROM_FILE": "./tests/key", 428 | "LIVEKIT_SECRET_FROM_FILE": "./tests/secret", 429 | }, 430 | expectedKey: "from_file_oquusheiheiw4Iegah8te3Vienguus5a", 431 | expectedSecret: "from_file_vohmahH3eeyieghohSh3kee8feuPhaim", 432 | }, 433 | { 434 | name: "Read from file key only", 435 | env: map[string]string{ 436 | "LIVEKIT_KEY_FROM_FILE": "./tests/key", 437 | "LIVEKIT_SECRET": "from_env_ahb8eiwae0viey7gee4ieNgahgeeQuie", 438 | }, 439 | expectedKey: "from_file_oquusheiheiw4Iegah8te3Vienguus5a", 440 | expectedSecret: "from_env_ahb8eiwae0viey7gee4ieNgahgeeQuie", 441 | }, 442 | { 443 | name: "Read from file secret only", 444 | env: map[string]string{ 445 | "LIVEKIT_SECRET_FROM_FILE": "./tests/secret", 446 | "LIVEKIT_KEY": "from_env_qui8aiTopiekiechah9oocbeimeew2O", 447 | }, 448 | expectedKey: "from_env_qui8aiTopiekiechah9oocbeimeew2O", 449 | expectedSecret: "from_file_vohmahH3eeyieghohSh3kee8feuPhaim", 450 | }, 451 | { 452 | name: "Empty if secret no env", 453 | env: map[string]string{}, 454 | expectedKey: "", 455 | expectedSecret: "", 456 | }, 457 | } 458 | 459 | for _, tc := range testCases { 460 | t.Run(tc.name, func(t *testing.T) { 461 | for k, v := range tc.env { 462 | if err := os.Setenv(k, v); err != nil { 463 | t.Errorf("Failed to set environment variable %s: %v", k, err) 464 | } 465 | } 466 | 467 | key, secret := readKeySecret() 468 | if secret != tc.expectedSecret || key != tc.expectedKey { 469 | t.Errorf("Expected secret and key to be %s and %s but got %s and %s", 470 | tc.expectedSecret, 471 | tc.expectedKey, 472 | secret, 473 | key) 474 | } 475 | for k := range tc.env { 476 | if err := os.Unsetenv(k); err != nil { 477 | t.Errorf("Failed to unset environment variable %s: %v", k, err) 478 | } 479 | } 480 | }) 481 | } 482 | } 483 | 484 | func TestParseConfig(t *testing.T) { 485 | testCases := []struct { 486 | name string 487 | env map[string]string 488 | wantConfig *Config 489 | wantErrMsg string 490 | }{ 491 | { 492 | name: "Minimal valid config", 493 | env: map[string]string{ 494 | "LIVEKIT_KEY": "test_key", 495 | "LIVEKIT_SECRET": "test_secret", 496 | "LIVEKIT_URL": "wss://test.livekit.cloud", 497 | }, 498 | wantConfig: &Config{ 499 | Key: "test_key", 500 | Secret: "test_secret", 501 | LkUrl: "wss://test.livekit.cloud", 502 | SkipVerifyTLS: false, 503 | FullAccessHomeservers: []string{"*"}, 504 | LkJwtBind: ":8080", 505 | }, 506 | }, 507 | { 508 | name: "Full config with all options", 509 | env: map[string]string{ 510 | "LIVEKIT_KEY": "test_key", 511 | "LIVEKIT_SECRET": "test_secret", 512 | "LIVEKIT_URL": "wss://test.livekit.cloud", 513 | "LIVEKIT_FULL_ACCESS_HOMESERVERS": "example.com, test.com", 514 | "LIVEKIT_JWT_BIND": ":9090", 515 | "LIVEKIT_INSECURE_SKIP_VERIFY_TLS": "YES_I_KNOW_WHAT_I_AM_DOING", 516 | }, 517 | wantConfig: &Config{ 518 | Key: "test_key", 519 | Secret: "test_secret", 520 | LkUrl: "wss://test.livekit.cloud", 521 | SkipVerifyTLS: true, 522 | FullAccessHomeservers: []string{"example.com", "test.com"}, 523 | LkJwtBind: ":9090", 524 | }, 525 | }, 526 | { 527 | name: "Legacy port configuration", 528 | env: map[string]string{ 529 | "LIVEKIT_KEY": "test_key", 530 | "LIVEKIT_SECRET": "test_secret", 531 | "LIVEKIT_URL": "wss://test.livekit.cloud", 532 | "LIVEKIT_JWT_PORT": "9090", 533 | }, 534 | wantConfig: &Config{ 535 | Key: "test_key", 536 | Secret: "test_secret", 537 | LkUrl: "wss://test.livekit.cloud", 538 | SkipVerifyTLS: false, 539 | FullAccessHomeservers: []string{"*"}, 540 | LkJwtBind: ":9090", 541 | }, 542 | }, 543 | { 544 | name: "Legacy full-access homeservers configuration", 545 | env: map[string]string{ 546 | "LIVEKIT_KEY": "test_key", 547 | "LIVEKIT_SECRET": "test_secret", 548 | "LIVEKIT_URL": "wss://test.livekit.cloud", 549 | "LIVEKIT_LOCAL_HOMESERVERS": "legacy.com", 550 | }, 551 | wantConfig: &Config{ 552 | Key: "test_key", 553 | Secret: "test_secret", 554 | LkUrl: "wss://test.livekit.cloud", 555 | SkipVerifyTLS: false, 556 | FullAccessHomeservers: []string{"legacy.com"}, 557 | LkJwtBind: ":8080", 558 | }, 559 | }, 560 | { 561 | name: "Missing required config", 562 | env: map[string]string{ 563 | "LIVEKIT_KEY": "test_key", 564 | }, 565 | wantErrMsg: "LIVEKIT_KEY[_FILE], LIVEKIT_SECRET[_FILE] and LIVEKIT_URL environment variables must be set", 566 | }, 567 | { 568 | name: "Conflicting bind configuration", 569 | env: map[string]string{ 570 | "LIVEKIT_KEY": "test_key", 571 | "LIVEKIT_SECRET": "test_secret", 572 | "LIVEKIT_URL": "wss://test.livekit.cloud", 573 | "LIVEKIT_JWT_BIND": ":9090", 574 | "LIVEKIT_JWT_PORT": "8080", 575 | }, 576 | wantErrMsg: "LIVEKIT_JWT_BIND and LIVEKIT_JWT_PORT environment variables MUST NOT be set together", 577 | }, 578 | } 579 | 580 | for _, tc := range testCases { 581 | t.Run(tc.name, func(t *testing.T) { 582 | // Setup: set env variables 583 | for k, v := range tc.env { 584 | if err := os.Setenv(k, v); err != nil { 585 | t.Fatalf("Failed to set environment variable %s: %v", k, err) 586 | } 587 | } 588 | defer func() { 589 | // Cleanup: reset env variables after test 590 | for k := range tc.env { 591 | if err := os.Unsetenv(k); err != nil { 592 | t.Errorf("Failed to unset environment variable %s: %v", k, err) 593 | } 594 | } 595 | }() 596 | 597 | // parse config from env variables 598 | got, err := parseConfig() 599 | 600 | // Given error(s), check potential error messages 601 | if tc.wantErrMsg != "" { 602 | if err == nil { 603 | t.Errorf("parseConfig() error = nil, wantErr %q", tc.wantErrMsg) 604 | return 605 | } 606 | if err.Error() != tc.wantErrMsg { 607 | t.Errorf("parseConfig() error = %q, wantErr %q", err.Error(), tc.wantErrMsg) 608 | } 609 | return 610 | } 611 | 612 | // Given no error, check for unexpected error messages 613 | if err != nil { 614 | t.Errorf("parseConfig() unexpected error: %v", err) 615 | return 616 | } 617 | 618 | // Compare parsed (got) config with wanted config 619 | if got.Key != tc.wantConfig.Key { 620 | t.Errorf("Key = %q, want %q", got.Key, tc.wantConfig.Key) 621 | } 622 | if got.Secret != tc.wantConfig.Secret { 623 | t.Errorf("Secret = %q, want %q", got.Secret, tc.wantConfig.Secret) 624 | } 625 | if got.LkUrl != tc.wantConfig.LkUrl { 626 | t.Errorf("LkUrl = %q, want %q", got.LkUrl, tc.wantConfig.LkUrl) 627 | } 628 | if got.SkipVerifyTLS != tc.wantConfig.SkipVerifyTLS { 629 | t.Errorf("SkipVerifyTLS = %v, want %v", got.SkipVerifyTLS, tc.wantConfig.SkipVerifyTLS) 630 | } 631 | if !reflect.DeepEqual(got.FullAccessHomeservers, tc.wantConfig.FullAccessHomeservers) { 632 | t.Errorf("FullAccessHomeservers = %v, want %v", got.FullAccessHomeservers, tc.wantConfig.FullAccessHomeservers) 633 | } 634 | if got.LkJwtBind != tc.wantConfig.LkJwtBind { 635 | t.Errorf("JwtBind = %q, want %q", got.LkJwtBind, tc.wantConfig.LkJwtBind) 636 | } 637 | }) 638 | } 639 | } 640 | 641 | func TestMapSFURequest(t *testing.T) { 642 | testCases := []struct { 643 | name string 644 | input string 645 | want any 646 | wantErrCode string 647 | }{ 648 | { 649 | name: "Valid legacy request", 650 | input: `{ 651 | "room": "testRoom", 652 | "openid_token": { 653 | "access_token": "test_token", 654 | "token_type": "Bearer", 655 | "matrix_server_name": "example.com", 656 | "expires_in": 3600 657 | }, 658 | "device_id": "testDevice" 659 | }`, 660 | want: &LegacySFURequest{ 661 | Room: "testRoom", 662 | OpenIDToken: OpenIDTokenType{ 663 | AccessToken: "test_token", 664 | TokenType: "Bearer", 665 | MatrixServerName: "example.com", 666 | ExpiresIn: 3600, 667 | }, 668 | DeviceID: "testDevice", 669 | }, 670 | }, 671 | { 672 | name: "Valid Matrix2 request", 673 | input: `{ 674 | "room_id": "!testRoom:example.com", 675 | "slot_id": "123", 676 | "openid_token": { 677 | "access_token": "test_token", 678 | "token_type": "Bearer", 679 | "matrix_server_name": "example.com", 680 | "expires_in": 3600 681 | }, 682 | "member": { 683 | "id": "test_id", 684 | "claimed_user_id": "@test:example.com", 685 | "claimed_device_id": "testDevice" 686 | } 687 | }`, 688 | want: &SFURequest{ 689 | RoomID: "!testRoom:example.com", 690 | SlotID: "123", 691 | OpenIDToken: OpenIDTokenType{ 692 | AccessToken: "test_token", 693 | TokenType: "Bearer", 694 | MatrixServerName: "example.com", 695 | ExpiresIn: 3600, 696 | }, 697 | Member: MatrixRTCMemberType{ 698 | ID: "test_id", 699 | ClaimedUserID: "@test:example.com", 700 | ClaimedDeviceID: "testDevice", 701 | }, 702 | }, 703 | }, 704 | { 705 | name: "Invalid JSON", 706 | input: `{"invalid": json}`, 707 | want: nil, 708 | wantErrCode: "M_BAD_JSON", 709 | }, 710 | { 711 | name: "Empty request", 712 | input: `{}`, 713 | want: nil, 714 | wantErrCode: "M_BAD_JSON", 715 | }, 716 | { 717 | name: "Invalid legacy request with extra field", 718 | input: `{ 719 | "room": "testRoom", 720 | "openid_token": { 721 | "access_token": "test_token", 722 | "token_type": "Bearer", 723 | "matrix_server_name": "example.com", 724 | "expires_in": 3600 725 | }, 726 | "device_id": "testDevice", 727 | "extra_field": "should_fail" 728 | }`, 729 | want: nil, 730 | wantErrCode: "M_BAD_JSON", 731 | }, 732 | } 733 | 734 | for _, tc := range testCases { 735 | t.Run(tc.name, func(t *testing.T) { 736 | // Convert string to []byte for input 737 | input := []byte(tc.input) 738 | 739 | // Call mapSFURequest 740 | got, err := mapSFURequest(&input) 741 | 742 | // Check error cases 743 | if tc.wantErrCode != "" { 744 | matrixErr := &MatrixErrorResponse{} 745 | if !errors.As(err, &matrixErr) { 746 | t.Errorf("mapSFURequest() error = %v, want MatrixErrorResponse", err) 747 | return 748 | } 749 | if matrixErr.ErrCode != tc.wantErrCode { 750 | t.Errorf("mapSFURequest() error code = %v, want %v", matrixErr.ErrCode, tc.wantErrCode) 751 | } 752 | return 753 | } 754 | 755 | // Check success cases 756 | if err != nil { 757 | t.Errorf("mapSFURequest() unexpected error: %v", err) 758 | return 759 | } 760 | 761 | // Type-specific comparisons 762 | switch expected := tc.want.(type) { 763 | case *LegacySFURequest: 764 | actual, ok := got.(*LegacySFURequest) 765 | if !ok { 766 | t.Errorf("mapSFURequest() returned wrong type, got %T, want *LegacySFURequest", got) 767 | return 768 | } 769 | if !reflect.DeepEqual(actual, expected) { 770 | t.Errorf("mapSFURequest() = %+v, want %+v", actual, expected) 771 | } 772 | case *SFURequest: 773 | actual, ok := got.(*SFURequest) 774 | if !ok { 775 | t.Errorf("mapSFURequest() returned wrong type, got %T, want *SFURequest", got) 776 | return 777 | } 778 | if !reflect.DeepEqual(actual, expected) { 779 | t.Errorf("mapSFURequest() = %+v, want %+v", actual, expected) 780 | } 781 | } 782 | }) 783 | } 784 | } 785 | 786 | func TestMapSFURequestMemoryLeak(t *testing.T) { 787 | const iterations = 100000 788 | 789 | input := []byte(`{ 790 | "room_id": "!testRoom:example.com", 791 | "slot_id": "123", 792 | "openid_token": { 793 | "access_token": "test_token", 794 | "token_type": "Bearer", 795 | "matrix_server_name": "example.com", 796 | "expires_in": 3600 797 | }, 798 | "member": { 799 | "id": "test_id", 800 | "claimed_user_id": "@test:example.com", 801 | "claimed_device_id": "testDevice" 802 | } 803 | }`) 804 | 805 | // Force a garbage collection to start from a clean slate. 806 | var mStart, mEnd runtime.MemStats 807 | runtime.GC() 808 | runtime.ReadMemStats(&mStart) 809 | 810 | for i := 0; i < iterations; i++ { 811 | _, err := mapSFURequest(&input) 812 | if err != nil { 813 | t.Fatalf("unexpected error in mapSFURequest iteration %d: %v", i, err) 814 | } 815 | } 816 | 817 | // Force another GC to clear unreferenced memory 818 | runtime.GC() 819 | runtime.ReadMemStats(&mEnd) 820 | 821 | t.Logf("Start Alloc: %d bytes, End Alloc: %d bytes", mStart.Alloc, mEnd.Alloc) 822 | 823 | // Check that allocated heap hasn’t grown unboundedly 824 | if mEnd.Alloc > mStart.Alloc { 825 | allocDiff := mEnd.Alloc - mStart.Alloc 826 | t.Logf("Heap allocation growth after %d iterations: %d bytes", iterations, allocDiff) 827 | 828 | // Heuristic threshold: less than 100KB growth across 100k iterations is fine 829 | const leakThreshold uint64 = 100 * 1024 // 100KB 830 | if allocDiff > leakThreshold { 831 | t.Errorf("Potential memory leak: heap grew by %d bytes (> %d)", allocDiff, leakThreshold) 832 | } 833 | } 834 | } 835 | 836 | func TestProcessSFURequest(t *testing.T) { 837 | // mock createLiveKitRoom 838 | var called_createLiveKitRoom bool 839 | original_createLiveKitRoom := createLiveKitRoom 840 | createLiveKitRoom = func(ctx context.Context, h *Handler, room, matrixUser, lkIdentity string) error { 841 | called_createLiveKitRoom = true 842 | if room == "" { 843 | t.Error("expected room name passed into mock") 844 | } 845 | return nil 846 | } 847 | t.Cleanup(func() { createLiveKitRoom = original_createLiveKitRoom }) 848 | 849 | // mock OpenID lookup 850 | var failed_exchangeOpenIdUserInfo bool 851 | var exchangeOpenIdUserInfo_MatrixID string 852 | original_exchangeOpenIdUserInfo := exchangeOpenIdUserInfo 853 | exchangeOpenIdUserInfo = func(ctx context.Context, token OpenIDTokenType, skip bool) (*fclient.UserInfo, error) { 854 | if failed_exchangeOpenIdUserInfo { 855 | return nil, &MatrixErrorResponse{ 856 | Status: http.StatusUnauthorized, 857 | ErrCode: "M_UNAUTHORIZED", 858 | Err: "The request could not be authorised.", 859 | } 860 | } 861 | return &fclient.UserInfo{Sub: exchangeOpenIdUserInfo_MatrixID}, nil 862 | } 863 | t.Cleanup(func() { exchangeOpenIdUserInfo = original_exchangeOpenIdUserInfo }) 864 | 865 | type testCase struct { 866 | name string 867 | MatrixID string 868 | ClaimedMatrixID string 869 | getJoinTokenErr error 870 | expectJoinTokenError bool 871 | expectExchangeOpendIdError bool 872 | expectCreateRoomCall bool 873 | expectError bool 874 | exchangeErr error 875 | } 876 | 877 | tests := []testCase{ 878 | { 879 | name: "Full access user + all OK", 880 | MatrixID: "@user:example.com", 881 | ClaimedMatrixID: "@user:example.com", 882 | expectCreateRoomCall: true, 883 | expectError: false, 884 | }, 885 | { 886 | name: "Restricted user + all OK", 887 | MatrixID: "@user:otherdomain.com", 888 | ClaimedMatrixID: "@user:otherdomain.com", 889 | expectCreateRoomCall: false, 890 | expectError: false, 891 | }, 892 | { 893 | name: "Full access user but exchangeOpenIdUserInfo fails", 894 | MatrixID: "@user:example.com", 895 | ClaimedMatrixID: "@user:example.com", 896 | expectExchangeOpendIdError: true, 897 | exchangeErr: &MatrixErrorResponse{}, 898 | expectCreateRoomCall: false, 899 | expectError: true, 900 | }, 901 | { 902 | name: "Full access user but getJoinToken fails", 903 | MatrixID: "@user:example.com", 904 | ClaimedMatrixID: "@user:example.com", 905 | expectJoinTokenError: true, 906 | getJoinTokenErr: &MatrixErrorResponse{}, 907 | expectCreateRoomCall: false, 908 | expectError: true, 909 | }, 910 | { 911 | name: "Full access user but claimed_matrix_id fails", 912 | MatrixID: "@user:example.com", 913 | ClaimedMatrixID: "@user:faked.com", 914 | expectJoinTokenError: false, 915 | getJoinTokenErr: &MatrixErrorResponse{}, 916 | expectCreateRoomCall: false, 917 | expectError: true, 918 | }, 919 | } 920 | 921 | for _, tc := range tests { 922 | t.Run(tc.name, func(t *testing.T) { 923 | // --- mock createLiveKitRoom --- 924 | called_createLiveKitRoom = false 925 | failed_exchangeOpenIdUserInfo = tc.expectExchangeOpendIdError 926 | exchangeOpenIdUserInfo_MatrixID = tc.MatrixID 927 | 928 | handler := &Handler{ 929 | key: map[bool]string{true: "", false: "the_api_key"}[tc.expectJoinTokenError], 930 | secret: "secret", 931 | lkUrl: "wss://lk.local:8080/foo", 932 | fullAccessHomeservers: []string{"example.com"}, 933 | } 934 | 935 | req := &SFURequest{ 936 | RoomID: "!room:example.com", 937 | SlotID: "slot", 938 | OpenIDToken: OpenIDTokenType{ 939 | AccessToken: "token", 940 | MatrixServerName: strings.Split(tc.ClaimedMatrixID, ":")[1], 941 | }, 942 | Member: MatrixRTCMemberType{ 943 | ID: "device", 944 | ClaimedUserID: tc.ClaimedMatrixID, 945 | ClaimedDeviceID: "dev", 946 | }, 947 | } 948 | 949 | _, err := handler.processSFURequest(&http.Request{}, req) 950 | if tc.expectError && err == nil { 951 | t.Fatalf("expected error but got nil") 952 | } 953 | if !tc.expectError && err != nil { 954 | t.Fatalf("unexpected error: %v", err) 955 | } 956 | 957 | if called_createLiveKitRoom != tc.expectCreateRoomCall { 958 | t.Errorf("expected createLiveKitRoom called=%v, got %v", tc.expectCreateRoomCall, called_createLiveKitRoom) 959 | } 960 | 961 | }) 962 | } 963 | 964 | 965 | } 966 | 967 | func TestProcessLegacySFURequest(t *testing.T) { 968 | // mock createLiveKitRoom 969 | var called_createLiveKitRoom bool 970 | original_createLiveKitRoom := createLiveKitRoom 971 | createLiveKitRoom = func(ctx context.Context, h *Handler, room, matrixUser, lkIdentity string) error { 972 | called_createLiveKitRoom = true 973 | if room == "" { 974 | t.Error("expected room name passed into mock") 975 | } 976 | return nil 977 | } 978 | t.Cleanup(func() { createLiveKitRoom = original_createLiveKitRoom }) 979 | 980 | // mock OpenID lookup 981 | var failed_exchangeOpenIdUserInfo bool 982 | original_exchangeOpenIdUserInfo := exchangeOpenIdUserInfo 983 | exchangeOpenIdUserInfo = func(ctx context.Context, token OpenIDTokenType, skip bool) (*fclient.UserInfo, error) { 984 | if failed_exchangeOpenIdUserInfo { 985 | return nil, &MatrixErrorResponse{ 986 | Status: http.StatusUnauthorized, 987 | ErrCode: "M_UNAUTHORIZED", 988 | Err: "The request could not be authorised.", 989 | } 990 | } 991 | return &fclient.UserInfo{Sub: "@mock:example.com"}, nil 992 | } 993 | t.Cleanup(func() { exchangeOpenIdUserInfo = original_exchangeOpenIdUserInfo }) 994 | 995 | type testCase struct { 996 | name string 997 | MatrixID string 998 | getJoinTokenErr error 999 | expectJoinTokenError bool 1000 | expectExchangeOpendIdError bool 1001 | expectCreateRoomCall bool 1002 | expectError bool 1003 | exchangeErr error 1004 | } 1005 | 1006 | tests := []testCase{ 1007 | { 1008 | name: "Full access user + all OK", 1009 | MatrixID: "@user:example.com", 1010 | expectCreateRoomCall: true, 1011 | expectError: false, 1012 | }, 1013 | { 1014 | name: "Restricted user + all OK", 1015 | MatrixID: "@user:otherdomain.com", 1016 | expectCreateRoomCall: false, 1017 | expectError: false, 1018 | }, 1019 | { 1020 | name: "Full access user but exchangeOpenIdUserInfo fails", 1021 | MatrixID: "@user:example.com", 1022 | expectExchangeOpendIdError: true, 1023 | exchangeErr: &MatrixErrorResponse{}, 1024 | expectCreateRoomCall: false, 1025 | expectError: true, 1026 | }, 1027 | { 1028 | name: "Full access user but getJoinToken fails", 1029 | MatrixID: "@user:example.com", 1030 | expectJoinTokenError: true, 1031 | getJoinTokenErr: &MatrixErrorResponse{}, 1032 | expectCreateRoomCall: false, 1033 | expectError: true, 1034 | }, 1035 | } 1036 | 1037 | for _, tc := range tests { 1038 | t.Run(tc.name, func(t *testing.T) { 1039 | // --- mock createLiveKitRoom --- 1040 | called_createLiveKitRoom = false 1041 | failed_exchangeOpenIdUserInfo = tc.expectExchangeOpendIdError 1042 | 1043 | handler := &Handler{ 1044 | key: map[bool]string{true: "", false: "the_api_key"}[tc.expectJoinTokenError], 1045 | secret: "secret", 1046 | lkUrl: "wss://lk.local:8080/foo", 1047 | fullAccessHomeservers: []string{"example.com"}, 1048 | } 1049 | 1050 | req := &LegacySFURequest{ 1051 | Room: "!room:example.com", 1052 | OpenIDToken: OpenIDTokenType{ 1053 | AccessToken: "token", 1054 | MatrixServerName: strings.Split(tc.MatrixID, ":")[1], 1055 | }, 1056 | DeviceID: "dev", 1057 | } 1058 | 1059 | _, err := handler.processLegacySFURequest(&http.Request{}, req) 1060 | if tc.expectError && err == nil { 1061 | t.Fatalf("expected error but got nil") 1062 | } 1063 | if !tc.expectError && err != nil { 1064 | t.Fatalf("unexpected error: %v", err) 1065 | } 1066 | 1067 | if called_createLiveKitRoom != tc.expectCreateRoomCall { 1068 | t.Errorf("expected createLiveKitRoom called=%v, got %v", tc.expectCreateRoomCall, called_createLiveKitRoom) 1069 | } 1070 | 1071 | }) 1072 | } 1073 | 1074 | 1075 | } --------------------------------------------------------------------------------