Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(web): support setting display name via query param on registration (#5042)
John Costa952ed56a9e81
diff --git a/web/components/stores/ClientConfigStore.tsx b/web/components/stores/ClientConfigStore.tsxindex 7fd7a1293b..b175fba6c1 100644--- a/web/components/stores/ClientConfigStore.tsx+++ b/web/components/stores/ClientConfigStore.tsx@@ -15,6 +15,7 @@ import appStateModel, {metaForSnapshot,} from './application-state';import { setLocalStorage, getLocalStorage } from '../../utils/localStorage';+import { getDisplayNameFromQuery } from '../../utils/displayNameValidation';import {ConnectedClientInfoEvent,MessageType,@@ -404,7 +405,11 @@ export const ClientConfigStore: FC = () => {updateClientConfig();}- handleUserRegistration();+ // If the URL includes a ?displayname=xyz query param, use it as the+ // proposed display name when registering a new chat user (the server may+ // sanitize or override it). It has no effect if the visitor has+ // previously registered (an access token is already saved).+ handleUserRegistration(getDisplayNameFromQuery(window.location.search));if (hasHydratedStatus) {handleStatusChange(status);diff --git a/web/tests/displayNameValidation.test.ts b/web/tests/displayNameValidation.test.tsindex 0bb4fa72c2..7b7e77d854 100644--- a/web/tests/displayNameValidation.test.ts+++ b/web/tests/displayNameValidation.test.ts@@ -1,4 +1,8 @@-import { validateDisplayName, trimUnicodeWhitespace } from '../utils/displayNameValidation';+import {+ validateDisplayName,+ trimUnicodeWhitespace,+ getDisplayNameFromQuery,+} from '../utils/displayNameValidation';describe('Display Name Validation', () => {const currentName = 'CurrentUser';@@ -198,3 +202,54 @@ describe('Display Name Validation - Real-world test cases', () => {}});});++describe('getDisplayNameFromQuery', () => {+ test('should return the display name from the query string', () => {+ expect(getDisplayNameFromQuery('?displayname=gabe')).toBe('gabe');+ });++ test('should return undefined when the param is absent', () => {+ expect(getDisplayNameFromQuery('')).toBeUndefined();+ expect(getDisplayNameFromQuery('?')).toBeUndefined();+ expect(getDisplayNameFromQuery('?foo=bar')).toBeUndefined();+ });++ test('should return undefined when the param is empty', () => {+ expect(getDisplayNameFromQuery('?displayname=')).toBeUndefined();+ expect(getDisplayNameFromQuery('?displayname')).toBeUndefined();+ });++ test('should return undefined when the param is only whitespace', () => {+ expect(getDisplayNameFromQuery('?displayname=%20%20')).toBeUndefined();+ expect(getDisplayNameFromQuery('?displayname=%C2%A0')).toBeUndefined();+ });++ test('should decode URL-encoded values', () => {+ expect(getDisplayNameFromQuery('?displayname=g%20abe')).toBe('g abe');+ });++ test('should decode plus-encoded spaces', () => {+ expect(getDisplayNameFromQuery('?displayname=g+abe')).toBe('g abe');+ });++ test('should not throw on a malformed percent-encoding', () => {+ // URLSearchParams leaves an undecodable sequence as the literal.+ expect(getDisplayNameFromQuery('?displayname=%')).toBe('%');+ });++ test('should be case-sensitive about the param name', () => {+ expect(getDisplayNameFromQuery('?DISPLAYNAME=gabe')).toBeUndefined();+ });++ test('should work alongside other query params', () => {+ expect(getDisplayNameFromQuery('?foo=bar&displayname=gabe&baz=1')).toBe('gabe');+ });++ test('should use the first value when the param appears multiple times', () => {+ expect(getDisplayNameFromQuery('?displayname=gabe&displayname=other')).toBe('gabe');+ });++ test('should trim surrounding whitespace', () => {+ expect(getDisplayNameFromQuery('?displayname=%20gabe%20')).toBe('gabe');+ });+});diff --git a/web/utils/displayNameValidation.ts b/web/utils/displayNameValidation.tsindex 283633add5..a9cdeb7065 100644--- a/web/utils/displayNameValidation.ts+++ b/web/utils/displayNameValidation.ts@@ -31,6 +31,23 @@ export function trimUnicodeWhitespace(str: string): string {return str.replace(unicodeWhitespacePattern, '');}+/**+ * Extracts the `displayname` query parameter for use during initial chat+ * registration. The returned value has surrounding whitespace trimmed.+ * Returns undefined when the parameter is absent, empty, or whitespace-only+ * so callers fall back to a server-generated name.+ * @param search The query string, e.g. window.location.search+ */+export function getDisplayNameFromQuery(search: string): string | undefined {+ const name = new URLSearchParams(search).get('displayname');+ if (!name) {+ return undefined;+ }++ const trimmedName = trimUnicodeWhitespace(name);+ return trimmedName.length > 0 ? trimmedName : undefined;+}+export function validateDisplayName(name: string | undefined,currentName: string,diff --git a/webserver/handlers/chat.go b/webserver/handlers/chat.goindex c9942e89c0..744698a74c 100644--- a/webserver/handlers/chat.go+++ b/webserver/handlers/chat.go@@ -77,11 +77,19 @@ func (h *Handlers) RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Requif proposedNewDisplayName == "" && request.DisplayName != nil {proposedNewDisplayName = *request.DisplayName}- if proposedNewDisplayName == "" {- proposedNewDisplayName = h.generateDisplayName()- }+ // Sanitize before the empty check so a proposed name that sanitizes to+ // nothing (e.g. only HTML tags or whitespace) still falls back to a+ // generated name instead of failing registration.proposedNewDisplayName = utils.MakeSafeStringOfLength(proposedNewDisplayName, config.MaxChatDisplayNameLength)+ if proposedNewDisplayName == "" {+ proposedNewDisplayName = utils.MakeSafeStringOfLength(h.generateDisplayName(), config.MaxChatDisplayNameLength)+ }+ if proposedNewDisplayName == "" {+ // An admin-configured suggested username can itself sanitize to+ // empty; GeneratePhrase always yields a usable word-word name.+ proposedNewDisplayName = utils.MakeSafeStringOfLength(utils.GeneratePhrase(), config.MaxChatDisplayNameLength)+ }newUser, accessToken, err := h.userRepository.CreateAnonymousUser(proposedNewDisplayName)if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())diff --git a/webserver/handlers/chat_test.go b/webserver/handlers/chat_test.gonew file mode 100644index 0000000000..977c6039ed--- /dev/null+++ b/webserver/handlers/chat_test.go@@ -0,0 +1,66 @@+package handlers++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/owncast/owncast/config"+)++// A proposed display name that sanitizes to an empty string (e.g. only HTML+// tags) must fall back to a generated name instead of failing registration.+func TestRegisterAnonymousChatUserEmptyAfterSanitizationFallsBack(t *testing.T) {+ tests := []struct {+ name string+ body string+ headers map[string]string+ wantExactly string+ }{+ {name: "body display name of only HTML", body: `{"displayName": "<b></b>"}`},+ {name: "body display name of HTML around text keeps the text", body: `{"displayName": "<b>gabe</b>"}`, wantExactly: "gabe"},+ {name: "X-Forwarded-User of only HTML", body: `{}`, headers: map[string]string{"X-Forwarded-User": "<b></b>"}},+ {name: "body display name of only whitespace", body: `{"displayName": " "}`},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodPost, "/api/chat/register", strings.NewReader(tc.body))+ for k, v := range tc.headers {+ req.Header.Set(k, v)+ }+ w := httptest.NewRecorder()++ testHandlers.RegisterAnonymousChatUser(w, req)++ resp := w.Result()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("expected status 200, got %d", resp.StatusCode)+ }++ var response struct {+ ID string `json:"id"`+ AccessToken string `json:"accessToken"`+ DisplayName string `json:"displayName"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if response.DisplayName == "" {+ t.Error("expected a non-empty generated display name")+ }+ if utf8.RuneCountInString(response.DisplayName) > config.MaxChatDisplayNameLength {+ t.Errorf("display name %q exceeds max length %d", response.DisplayName, config.MaxChatDisplayNameLength)+ }+ if tc.wantExactly != "" && response.DisplayName != tc.wantExactly {+ t.Errorf("expected display name %q, got %q", tc.wantExactly, response.DisplayName)+ }+ if response.AccessToken == "" {+ t.Error("expected a non-empty access token")+ }+ })+ }+}diff --git a/webserver/handlers/handlers_test.go b/webserver/handlers/handlers_test.goindex 83d1eceb85..98d79681f8 100644--- a/webserver/handlers/handlers_test.go+++ b/webserver/handlers/handlers_test.go@@ -10,12 +10,13 @@ import ("testing""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/userrepository""github.com/owncast/owncast/services/datastore")// testHandlers is the *Handlers used by tests in this package, holding-// only the configRepository handle. Expand if other handler tests land-// that need additional deps.+// only the configRepository and userRepository handles. Expand if other+// handler tests land that need additional deps.var (testHandlers *HandlerstestDatastore *datastore.Datastore@@ -34,7 +35,10 @@ func TestMain(m *testing.M) {}testDatastore = ds- testHandlers = &Handlers{configRepository: configrepository.New(testDatastore)}+ testHandlers = &Handlers{+ configRepository: configrepository.New(testDatastore),+ userRepository: userrepository.New(testDatastore),+ }code := m.Run()os.Remove(dbFile.Name())