Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(auth): first-class linked identities for chat users
Gabe Kangas51c6b84ef239
diff --git a/db/db.go b/db/db.goindex f43598b1eb..cd5bbb8e08 100644--- a/db/db.go+++ b/db/db.go@@ -1,6 +1,6 @@// Code generated by sqlc. DO NOT EDIT.// versions:-// sqlc v1.31.1+// sqlc v1.30.0package dbdiff --git a/db/models.go b/db/models.goindex 96fbf7d78e..85a7322739 100644--- a/db/models.go+++ b/db/models.go@@ -1,6 +1,6 @@// Code generated by sqlc. DO NOT EDIT.// versions:-// sqlc v1.31.1+// sqlc v1.30.0package db@@ -43,11 +43,15 @@ type ApOutbox struct {}type Auth struct {- ID int64- UserID string- Token string- Type string- Timestamp time.Time+ ID int64+ UserID string+ AuthKey string+ Type string+ Timestamp time.Time+ Provider string+ ProfileUrl sql.NullString+ Handle sql.NullString+ IsPublic bool}type Datastore struct {diff --git a/db/query.sql b/db/query.sqlindex 14868debc4..6622129024 100644--- a/db/query.sql+++ b/db/query.sql@@ -124,18 +124,24 @@ SELECT destination FROM notifications WHERE channel = ?;DELETE FROM notifications WHERE channel = ? AND destination = ?;-- name: AddAuthForUser :exec-INSERT INTO auth(user_id, token, type) values(?, ?, ?);+INSERT INTO auth(user_id, auth_key, type, provider, profile_url, handle, is_public) values(?, ?, ?, ?, ?, ?, ?);-- name: GetUserByAuth :one-SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE token = ? AND auth.type = ? AND users.id = auth.user_id;+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth_key = ? AND auth.type = ? AND users.id = auth.user_id;--- name: CountUserAuthByTypeAndTokenPrefix :one-SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND token LIKE ?;+-- name: GetUserByPluginAuth :one+-- Plugin-auth lookup keyed on (provider, auth_key). The type literal mirrors+-- models.PluginAuth and pins the lookup to the plugin namespace, so a plugin+-- slug can never resolve a built-in identity.+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth.type = 'plugin.auth' AND auth.provider = ? AND auth.auth_key = ? AND users.id = auth.user_id;++-- name: CountUserAuthByProvider :one+SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND provider = ?;-- name: GetAuthForUsers :many--- External auth identities (type + token) for the given users, so the admin+-- External auth identities (type + provider) for the given users, so the admin-- user list can show how each authenticated user signed in.-SELECT user_id, type, token FROM auth WHERE user_id IN (sqlc.slice('user_ids'));+SELECT user_id, type, provider FROM auth WHERE user_id IN (sqlc.slice('user_ids'));-- name: AddAccessTokenForUser :execINSERT INTO user_access_tokens(token, user_id) values(?, ?);diff --git a/db/query.sql.go b/db/query.sql.goindex ca7854e934..e0e8b42201 100644--- a/db/query.sql.go+++ b/db/query.sql.go@@ -1,6 +1,6 @@// Code generated by sqlc. DO NOT EDIT.// versions:-// sqlc v1.31.1+// sqlc v1.30.0// source: query.sqlpackage db@@ -27,17 +27,29 @@ func (q *Queries) AddAccessTokenForUser(ctx context.Context, arg AddAccessTokenF}const addAuthForUser = `-- name: AddAuthForUser :exec-INSERT INTO auth(user_id, token, type) values(?, ?, ?)+INSERT INTO auth(user_id, auth_key, type, provider, profile_url, handle, is_public) values(?, ?, ?, ?, ?, ?, ?)`type AddAuthForUserParams struct {- UserID string- Token string- Type string+ UserID string+ AuthKey string+ Type string+ Provider string+ ProfileUrl sql.NullString+ Handle sql.NullString+ IsPublic bool}func (q *Queries) AddAuthForUser(ctx context.Context, arg AddAuthForUserParams) error {- _, err := q.db.ExecContext(ctx, addAuthForUser, arg.UserID, arg.Token, arg.Type)+ _, err := q.db.ExecContext(ctx, addAuthForUser,+ arg.UserID,+ arg.AuthKey,+ arg.Type,+ arg.Provider,+ arg.ProfileUrl,+ arg.Handle,+ arg.IsPublic,+ )return err}@@ -56,8 +68,7 @@ type AddFederatedServerParams struct {}func (q *Queries) AddFederatedServer(ctx context.Context, arg AddFederatedServerParams) error {- _, err := q.db.ExecContext(- ctx, addFederatedServer,+ _, err := q.db.ExecContext(ctx, addFederatedServer,arg.Iri,arg.Name,arg.LogoUrl,@@ -87,8 +98,7 @@ type AddFollowerParams struct {}func (q *Queries) AddFollower(ctx context.Context, arg AddFollowerParams) error {- _, err := q.db.ExecContext(- ctx, addFollower,+ _, err := q.db.ExecContext(ctx, addFollower,arg.Iri,arg.Inbox,arg.SharedInbox,@@ -129,8 +139,7 @@ type AddToAcceptedActivitiesParams struct {}func (q *Queries) AddToAcceptedActivities(ctx context.Context, arg AddToAcceptedActivitiesParams) error {- _, err := q.db.ExecContext(- ctx, addToAcceptedActivities,+ _, err := q.db.ExecContext(ctx, addToAcceptedActivities,arg.Iri,arg.Actor,arg.Type,@@ -151,8 +160,7 @@ type AddToOutboxParams struct {}func (q *Queries) AddToOutbox(ctx context.Context, arg AddToOutboxParams) error {- _, err := q.db.ExecContext(- ctx, addToOutbox,+ _, err := q.db.ExecContext(ctx, addToOutbox,arg.Iri,arg.Value,arg.Type,@@ -215,8 +223,7 @@ type ChangeDisplayNameParams struct {}func (q *Queries) ChangeDisplayName(ctx context.Context, arg ChangeDisplayNameParams) error {- _, err := q.db.ExecContext(- ctx, changeDisplayName,+ _, err := q.db.ExecContext(ctx, changeDisplayName,arg.DisplayName,arg.PreviousNames,arg.NamechangedAt,@@ -225,18 +232,18 @@ func (q *Queries) ChangeDisplayName(ctx context.Context, arg ChangeDisplayNamePareturn err}-const countUserAuthByTypeAndTokenPrefix = `-- name: CountUserAuthByTypeAndTokenPrefix :one-SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND token LIKE ?+const countUserAuthByProvider = `-- name: CountUserAuthByProvider :one+SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND provider = ?`-type CountUserAuthByTypeAndTokenPrefixParams struct {- UserID string- Type string- Token string+type CountUserAuthByProviderParams struct {+ UserID string+ Type string+ Provider string}-func (q *Queries) CountUserAuthByTypeAndTokenPrefix(ctx context.Context, arg CountUserAuthByTypeAndTokenPrefixParams) (int64, error) {- row := q.db.QueryRowContext(ctx, countUserAuthByTypeAndTokenPrefix, arg.UserID, arg.Type, arg.Token)+func (q *Queries) CountUserAuthByProvider(ctx context.Context, arg CountUserAuthByProviderParams) (int64, error) {+ row := q.db.QueryRowContext(ctx, countUserAuthByProvider, arg.UserID, arg.Type, arg.Provider)var count int64err := row.Scan(&count)return count, err@@ -371,16 +378,16 @@ func (q *Queries) GetApprovedDirectoryFollowers(ctx context.Context) ([]GetAppro}const getAuthForUsers = `-- name: GetAuthForUsers :many-SELECT user_id, type, token FROM auth WHERE user_id IN (/*SLICE:user_ids*/?)+SELECT user_id, type, provider FROM auth WHERE user_id IN (/*SLICE:user_ids*/?)`type GetAuthForUsersRow struct {- UserID string- Type string- Token string+ UserID string+ Type string+ Provider string}-// External auth identities (type + token) for the given users, so the admin+// External auth identities (type + provider) for the given users, so the admin// user list can show how each authenticated user signed in.func (q *Queries) GetAuthForUsers(ctx context.Context, userIds []string) ([]GetAuthForUsersRow, error) {query := getAuthForUsers@@ -401,7 +408,7 @@ func (q *Queries) GetAuthForUsers(ctx context.Context, userIds []string) ([]GetAvar items []GetAuthForUsersRowfor rows.Next() {var i GetAuthForUsersRow- if err := rows.Scan(&i.UserID, &i.Type, &i.Token); err != nil {+ if err := rows.Scan(&i.UserID, &i.Type, &i.Provider); err != nil {return nil, err}items = append(items, i)@@ -1143,12 +1150,12 @@ func (q *Queries) GetUserByAccessToken(ctx context.Context, token string) (GetUs}const getUserByAuth = `-- name: GetUserByAuth :one-SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE token = ? AND auth.type = ? AND users.id = auth.user_id+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth_key = ? AND auth.type = ? AND users.id = auth.user_id`type GetUserByAuthParams struct {- Token string- Type string+ AuthKey string+ Type string}type GetUserByAuthRow struct {@@ -1164,7 +1171,7 @@ type GetUserByAuthRow struct {}func (q *Queries) GetUserByAuth(ctx context.Context, arg GetUserByAuthParams) (GetUserByAuthRow, error) {- row := q.db.QueryRowContext(ctx, getUserByAuth, arg.Token, arg.Type)+ row := q.db.QueryRowContext(ctx, getUserByAuth, arg.AuthKey, arg.Type)var i GetUserByAuthRowerr := row.Scan(&i.ID,@@ -1215,6 +1222,47 @@ func (q *Queries) GetUserByID(ctx context.Context, id string) (GetUserByIDRow, ereturn i, err}+const getUserByPluginAuth = `-- name: GetUserByPluginAuth :one+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth.type = 'plugin.auth' AND auth.provider = ? AND auth.auth_key = ? AND users.id = auth.user_id+`++type GetUserByPluginAuthParams struct {+ Provider string+ AuthKey string+}++type GetUserByPluginAuthRow struct {+ ID string+ DisplayName string+ DisplayColor int64+ CreatedAt sql.NullTime+ DisabledAt sql.NullTime+ PreviousNames sql.NullString+ NamechangedAt sql.NullTime+ AuthenticatedAt sql.NullTime+ Scopes sql.NullString+}++// Plugin-auth lookup keyed on (provider, auth_key). The type literal mirrors+// models.PluginAuth and pins the lookup to the plugin namespace, so a plugin+// slug can never resolve a built-in identity.+func (q *Queries) GetUserByPluginAuth(ctx context.Context, arg GetUserByPluginAuthParams) (GetUserByPluginAuthRow, error) {+ row := q.db.QueryRowContext(ctx, getUserByPluginAuth, arg.Provider, arg.AuthKey)+ var i GetUserByPluginAuthRow+ err := row.Scan(+ &i.ID,+ &i.DisplayName,+ &i.DisplayColor,+ &i.CreatedAt,+ &i.DisabledAt,+ &i.PreviousNames,+ &i.NamechangedAt,+ &i.AuthenticatedAt,+ &i.Scopes,+ )+ return i, err+}+const getUserDisplayNameByToken = `-- name: GetUserDisplayNameByToken :oneSELECT display_name FROM users JOIN user_access_tokens ON users.id = user_access_tokens.user_id WHERE token = ? AND users.disabled_at IS NULL`@@ -1318,8 +1366,7 @@ type GetUsersPaginatedRow struct {// 'active' (not banned), 'banned' (disabled), 'moderators', or 'bots' (API// users). An empty @search matches every user (LIKE '%%').func (q *Queries) GetUsersPaginated(ctx context.Context, arg GetUsersPaginatedParams) ([]GetUsersPaginatedRow, error) {- rows, err := q.db.QueryContext(- ctx, getUsersPaginated,+ rows, err := q.db.QueryContext(ctx, getUsersPaginated,arg.Search,arg.Status,arg.PageOffset,@@ -1470,8 +1517,7 @@ type UpdateFederatedServerFollowStatusParams struct {}func (q *Queries) UpdateFederatedServerFollowStatus(ctx context.Context, arg UpdateFederatedServerFollowStatusParams) error {- _, err := q.db.ExecContext(- ctx, updateFederatedServerFollowStatus,+ _, err := q.db.ExecContext(ctx, updateFederatedServerFollowStatus,arg.FollowStatus,arg.Pending,arg.AcceptedAt,@@ -1494,8 +1540,7 @@ type UpdateFederatedServerMetadataParams struct {}func (q *Queries) UpdateFederatedServerMetadata(ctx context.Context, arg UpdateFederatedServerMetadataParams) error {- _, err := q.db.ExecContext(- ctx, updateFederatedServerMetadata,+ _, err := q.db.ExecContext(ctx, updateFederatedServerMetadata,arg.Name,arg.DisplayName,arg.Summary,@@ -1517,8 +1562,7 @@ type UpdateFederatedServerOnlineStatusParams struct {}func (q *Queries) UpdateFederatedServerOnlineStatus(ctx context.Context, arg UpdateFederatedServerOnlineStatusParams) error {- _, err := q.db.ExecContext(- ctx, updateFederatedServerOnlineStatus,+ _, err := q.db.ExecContext(ctx, updateFederatedServerOnlineStatus,arg.IsOnline,arg.LastSeenOnline,arg.LastStatusUpdate,@@ -1542,8 +1586,7 @@ type UpdateFederatedServerStatusParams struct {}func (q *Queries) UpdateFederatedServerStatus(ctx context.Context, arg UpdateFederatedServerStatusParams) error {- _, err := q.db.ExecContext(- ctx, updateFederatedServerStatus,+ _, err := q.db.ExecContext(ctx, updateFederatedServerStatus,arg.IsOnline,arg.StreamTitle,arg.StreamDescription,@@ -1569,8 +1612,7 @@ type UpdateFollowerByIRIParams struct {}func (q *Queries) UpdateFollowerByIRI(ctx context.Context, arg UpdateFollowerByIRIParams) error {- _, err := q.db.ExecContext(- ctx, updateFollowerByIRI,+ _, err := q.db.ExecContext(ctx, updateFollowerByIRI,arg.Inbox,arg.SharedInbox,arg.Name,diff --git a/models/auth.go b/models/auth.goindex 3c65e37fe9..eff1618892 100644--- a/models/auth.go+++ b/models/auth.go@@ -9,7 +9,25 @@ const (IndieAuth AuthType = "indieauth"Fediverse AuthType = "fediverse"// PluginAuth is an identity established by a viewer-auth plugin- // (owncast.users.register). The stored auth token is the plugin's external- // identity, namespaced by the plugin slug (e.g. "github-auth:github:583231").+ // (owncast.users.register). type stays the coarse namespace; the auth row's+ // provider column carries the plugin slug and auth_key the raw external id.PluginAuth AuthType = "plugin.auth")++// LinkedIdentityFields carries the optional public-profile metadata for a+// linked identity (see the auth table's provider/profile_url/handle/is_public+// columns). All fields are optional. Provider overrides the default provider+// (the auth type) — set it to the plugin slug for plugin auth.+type LinkedIdentityFields struct {+ // Provider is the first-class provider id. Empty defaults to the auth type+ // (correct for built-in IndieAuth/Fediverse); set to the plugin slug for+ // plugin auth.+ Provider string+ // ProfileURL is the public, clickable link to the external profile.+ ProfileURL string+ // Handle is the human label for the identity, e.g. @me@host.+ Handle string+ // Public is the user's consent to surface this identity publicly. Defaults+ // to false; nothing shows publicly until the user opts in.+ Public bool+}diff --git a/persistence/migrations/00004_linked_identities.sql b/persistence/migrations/00004_linked_identities.sqlnew file mode 100644index 0000000000..0116854418--- /dev/null+++ b/persistence/migrations/00004_linked_identities.sql@@ -0,0 +1,60 @@+-- +goose Up+-- +goose StatementBegin++-- Linked-identity fields for the auth table.+--+-- An auth row is one external identity a user proved they own (IndieAuth,+-- Fediverse, or a viewer-auth plugin). Until now a row carried only the auth+-- key (token) and a coarse type. To surface a verified identity publicly we+-- need more: which provider it is (first-class, not parsed from a token+-- prefix), where it links, a human label, and whether the user consents to+-- showing it.+--+-- token -> auth_key the value matched at login. For plugin auth this is now+-- the raw external id, with no "<slug>:" prefix.+-- provider first-class provider id. For built-ins it equals the+-- type; for plugins it is the plugin slug. `type` is kept+-- as the security namespace, so a plugin whose slug is+-- "fediverse" still lands in type='plugin.auth' and can+-- never collide with the built-in fediverse provider.+-- profile_url public, clickable link. Optional.+-- handle human label, e.g. @me@host. Optional.+-- is_public consent. Off by default; the user opts an identity in.+ALTER TABLE auth RENAME COLUMN token TO auth_key;+ALTER TABLE auth ADD COLUMN provider TEXT NOT NULL DEFAULT '';+ALTER TABLE auth ADD COLUMN profile_url TEXT;+ALTER TABLE auth ADD COLUMN handle TEXT;+ALTER TABLE auth ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT FALSE;++-- Backfill existing rows. Only IndieAuth and Fediverse identities exist today+-- (plugin auth has not shipped), so provider == type for every current row.+UPDATE auth SET provider = type;+-- IndieAuth's key is the user's website, which already is the public profile.+UPDATE auth SET profile_url = auth_key WHERE type = 'indieauth';+-- Fediverse's key is the @me@host handle, which is the human label.+UPDATE auth SET handle = auth_key WHERE type = 'fediverse';++DROP INDEX IF EXISTS idx_auth_token;+CREATE INDEX IF NOT EXISTS idx_auth_auth_key ON auth (auth_key);++-- A plugin identity (provider=slug, auth_key=external id) must map to exactly+-- one user, so a concurrent double-registration can't mint two users for the+-- same external identity. Partial to type='plugin.auth': it is the formalized+-- path and has no existing rows (plugin auth has not shipped), so the unique+-- index can never fail to build on legacy data. Built-in IndieAuth/Fediverse+-- linking is guarded by a find-first check in their handlers.+CREATE UNIQUE INDEX IF NOT EXISTS idx_auth_plugin_identity ON auth (provider, auth_key) WHERE type = 'plugin.auth';++-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin+DROP INDEX IF EXISTS idx_auth_plugin_identity;+DROP INDEX IF EXISTS idx_auth_auth_key;+ALTER TABLE auth DROP COLUMN is_public;+ALTER TABLE auth DROP COLUMN handle;+ALTER TABLE auth DROP COLUMN profile_url;+ALTER TABLE auth DROP COLUMN provider;+ALTER TABLE auth RENAME COLUMN auth_key TO token;+CREATE INDEX IF NOT EXISTS idx_auth_token ON auth (token);+-- +goose StatementEnddiff --git a/persistence/migrations/migrations_test.go b/persistence/migrations/migrations_test.goindex 4550406e2d..04958ef360 100644--- a/persistence/migrations/migrations_test.go+++ b/persistence/migrations/migrations_test.go@@ -68,8 +68,8 @@ func TestRun_FreshDatabase(t *testing.T) {t.Error("fresh install should not have legacy config table")}- if v := gooseVersion(t, db); v != 3 {- t.Errorf("goose version = %d, want 3", v)+ if v := gooseVersion(t, db); v != 4 {+ t.Errorf("goose version = %d, want 4", v)}// Calling Run a second time should be a no-op (idempotent).@@ -93,8 +93,8 @@ func TestRun_LegacyDatabaseAtV9(t *testing.T) {}// Goose should record the latest migration.- if v := gooseVersion(t, db); v != 3 {- t.Errorf("goose version = %d, want 3", v)+ if v := gooseVersion(t, db); v != 4 {+ t.Errorf("goose version = %d, want 4", v)}// Config version should still be 9, the legacy bridge was not invoked.@@ -141,8 +141,58 @@ func TestRun_LegacyDatabasePreV9(t *testing.T) {}// Goose should have recorded the latest migration.- if v := gooseVersion(t, db); v != 3 {- t.Errorf("goose version = %d, want 3", v)+ if v := gooseVersion(t, db); v != 4 {+ t.Errorf("goose version = %d, want 4", v)+ }+}++// TestRun_BackfillsLinkedIdentities verifies that the 00004 migration upgrades+// existing auth rows in place: token becomes auth_key, provider is set, and the+// IndieAuth/Fediverse freebies (profile_url / handle) are backfilled — so+// returning users keep their linked identity across the upgrade.+func TestRun_BackfillsLinkedIdentities(t *testing.T) {+ db := openTestDB(t)+ createV9Schema(t, db) // auth table here still has the old "token" column++ // Seed one identity per built-in provider, as a pre-goose install would.+ mustExec(t, db, `INSERT INTO auth(user_id, token, type) VALUES('u-indie', 'https://me.example.com', 'indieauth')`)+ mustExec(t, db, `INSERT INTO auth(user_id, token, type) VALUES('u-fedi', '@[email protected]', 'fediverse')`)++ if err := Run(db, t.TempDir()); err != nil {+ t.Fatalf("Run: %v", err)+ }++ // IndieAuth: auth_key carried over, provider=type, profile_url=auth_key,+ // no handle, consent off.+ var authKey, provider string+ var profileURL, handle sql.NullString+ var isPublic bool+ mustScan(t, db.QueryRow(`SELECT auth_key, provider, profile_url, handle, is_public FROM auth WHERE user_id='u-indie'`),+ &authKey, &provider, &profileURL, &handle, &isPublic)+ if authKey != "https://me.example.com" || provider != "indieauth" {+ t.Errorf("indieauth row: auth_key=%q provider=%q", authKey, provider)+ }+ if !profileURL.Valid || profileURL.String != "https://me.example.com" {+ t.Errorf("indieauth profile_url = %v, want the me URL", profileURL)+ }+ if handle.Valid {+ t.Errorf("indieauth handle should be NULL, got %q", handle.String)+ }+ if isPublic {+ t.Errorf("indieauth is_public = %v, want false", isPublic)+ }++ // Fediverse: handle backfilled from auth_key, no profile_url (resolved later).+ mustScan(t, db.QueryRow(`SELECT auth_key, provider, profile_url, handle, is_public FROM auth WHERE user_id='u-fedi'`),+ &authKey, &provider, &profileURL, &handle, &isPublic)+ if authKey != "@[email protected]" || provider != "fediverse" {+ t.Errorf("fediverse row: auth_key=%q provider=%q", authKey, provider)+ }+ if profileURL.Valid {+ t.Errorf("fediverse profile_url should be NULL, got %q", profileURL.String)+ }+ if !handle.Valid || handle.String != "@[email protected]" {+ t.Errorf("fediverse handle = %v, want the account", handle)}}diff --git a/persistence/userrepository/userrepository.go b/persistence/userrepository/userrepository.goindex 8061a7dbc8..ce73af1f54 100644--- a/persistence/userrepository/userrepository.go+++ b/persistence/userrepository/userrepository.go@@ -43,7 +43,8 @@ type UserRepository interface {SetUserAsAuthenticated(userID string) errorHasValidScopes(scopes []string) boolGetUserByAuth(authToken string, authType models.AuthType) *models.User- AddAuth(userID, authToken string, authType models.AuthType) error+ GetUserByPluginAuth(pluginName, authKey string) *models.User+ AddAuth(userID, authKey string, authType models.AuthType, fields *models.LinkedIdentityFields) errorUserRegisteredByPlugin(pluginName, userID string) boolAddAccessTokenForUser(accessToken, userID string) errorSetUserScopes(userID string, scopes []string) error@@ -286,30 +287,54 @@ func (r *SqlUserRepository) SetUserAsAuthenticated(userID string) error {return errors.Wrap(r.datastore.GetQueries().SetUserAsAuthenticated(context.Background(), userID), "unable to set user as authenticated")}-// AddAuth will add an external authentication token and type for a user.-func (r *SqlUserRepository) AddAuth(userID, authToken string, authType models.AuthType) error {+// AddAuth links an external authentication identity to a user. authKey is the+// value matched at login (the IndieAuth/Fediverse identity, or a plugin's raw+// external id). fields carries the optional linked-identity metadata (provider,+// profile URL, handle, public consent) and may be nil for a bare identity, in+// which case provider defaults to the auth type.+func (r *SqlUserRepository) AddAuth(userID, authKey string, authType models.AuthType, fields *models.LinkedIdentityFields) error {+ provider := string(authType)+ var profileURL, handle sql.NullString+ var isPublic bool+ if fields != nil {+ if fields.Provider != "" {+ provider = fields.Provider+ }+ if fields.ProfileURL != "" {+ profileURL = sql.NullString{String: fields.ProfileURL, Valid: true}+ }+ if fields.Handle != "" {+ handle = sql.NullString{String: fields.Handle, Valid: true}+ }+ isPublic = fields.Public+ }+return r.datastore.GetQueries().AddAuthForUser(context.Background(), db.AddAuthForUserParams{- UserID: userID,- Token: authToken,- Type: string(authType),+ UserID: userID,+ AuthKey: authKey,+ Type: string(authType),+ Provider: provider,+ ProfileUrl: profileURL,+ Handle: handle,+ IsPublic: isPublic,})}// UserRegisteredByPlugin reports whether userID belongs to a user the named// plugin registered via owncast.users.register — i.e. the user has a-// plugin.auth identity namespaced to that plugin's slug (RegisterUser stores-// it as "<slug>:<authId>"). The viewer-auth gate uses this to confine-// owncast.auth.grantSession to a plugin's own users, so a gate plugin can't-// mint a session impersonating an arbitrary existing user (e.g. a moderator).+// plugin.auth identity whose provider is that plugin's slug. The viewer-auth+// gate uses this to confine owncast.auth.grantSession to a plugin's own users,+// so a gate plugin can't mint a session impersonating an arbitrary existing+// user (e.g. a moderator).//-// Matching on the "<slug>:" prefix is safe: plugin slugs are validated to-// lowercase letters/digits/hyphens, so they can't carry SQL LIKE wildcards.-// Fails closed (returns false) on any query error.+// The match is an exact equality on (type='plugin.auth', provider=slug): type+// keeps built-in identities out of reach even if a plugin's slug is "indieauth"+// or "fediverse". Fails closed (returns false) on any query error.func (r *SqlUserRepository) UserRegisteredByPlugin(pluginName, userID string) bool {- count, err := r.datastore.GetQueries().CountUserAuthByTypeAndTokenPrefix(context.Background(), db.CountUserAuthByTypeAndTokenPrefixParams{- UserID: userID,- Type: string(models.PluginAuth),- Token: pluginName + ":%",+ count, err := r.datastore.GetQueries().CountUserAuthByProvider(context.Background(), db.CountUserAuthByProviderParams{+ UserID: userID,+ Type: string(models.PluginAuth),+ Provider: pluginName,})if err != nil {log.Errorln("checking plugin user ownership:", err)@@ -319,32 +344,35 @@ func (r *SqlUserRepository) UserRegisteredByPlugin(pluginName, userID string) bo}// GetUserByAuth will return an existing user given auth details if a user-// has previously authenticated with that method.+// has previously authenticated with that method. For built-in providers the+// auth key (IndieAuth website / Fediverse handle) plus type uniquely identify+// the row. Plugin auth must use GetUserByPluginAuth so the lookup is scoped to+// the registering plugin's slug.func (r *SqlUserRepository) GetUserByAuth(authToken string, authType models.AuthType) *models.User {u, err := r.datastore.GetQueries().GetUserByAuth(context.Background(), db.GetUserByAuthParams{- Token: authToken,- Type: string(authType),+ AuthKey: authToken,+ Type: string(authType),})if err != nil {return nil}+ return userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, false)+}- var scopes []string- if u.Scopes.Valid {- scopes = strings.Split(u.Scopes.String, ",")- }-- return &models.User{- ID: u.ID,- DisplayName: u.DisplayName,- DisplayColor: int(u.DisplayColor),- CreatedAt: u.CreatedAt.Time,- DisabledAt: &u.DisabledAt.Time,- PreviousNames: strings.Split(u.PreviousNames.String, ","),- NameChangedAt: &u.NamechangedAt.Time,- AuthenticatedAt: &u.AuthenticatedAt.Time,- Scopes: scopes,+// GetUserByPluginAuth returns the user a viewer-auth plugin registered for the+// given raw external id, scoped to that plugin's slug. It is the find half of+// owncast.users.register's find-or-create, and the (provider, auth_key) scoping+// keeps two plugins that mint the same external id from resolving each other's+// users.+func (r *SqlUserRepository) GetUserByPluginAuth(pluginName, authKey string) *models.User {+ u, err := r.datastore.GetQueries().GetUserByPluginAuth(context.Background(), db.GetUserByPluginAuthParams{+ Provider: pluginName,+ AuthKey: authKey,+ })+ if err != nil {+ return nil}+ return userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, false)}// SetUserScopes replaces a user's full scope set. Used by viewer-auth plugins@@ -538,7 +566,7 @@ func (r *SqlUserRepository) attachAuthProviders(ctx context.Context, users []*mobyUser := map[string][]string{}seen := map[string]map[string]bool{}for _, a := range authRows {- label := authProviderLabel(a.Type, a.Token)+ label := authProviderLabel(a.Type, a.Provider)if seen[a.UserID] == nil {seen[a.UserID] = map[string]bool{}}@@ -557,17 +585,17 @@ func (r *SqlUserRepository) attachAuthProviders(ctx context.Context, users []*mo}// authProviderLabel turns an auth row into a human-friendly provider name. For-// plugin auth the token is namespaced as "<plugin-slug>:<externalId>", so the-// plugin slug is surfaced rather than the opaque "plugin.auth" type.-func authProviderLabel(authType, token string) string {+// plugin auth the provider column holds the plugin slug, so the slug is+// surfaced rather than the opaque "plugin.auth" type.+func authProviderLabel(authType, provider string) string {switch models.AuthType(authType) {case models.IndieAuth:return "IndieAuth"case models.Fediverse:return "Fediverse"case models.PluginAuth:- if i := strings.IndexByte(token, ':'); i > 0 {- return token[:i]+ if provider != "" {+ return provider}return "Plugin"default:diff --git a/persistence/userrepository/userrepository_test.go b/persistence/userrepository/userrepository_test.goindex ea5e7d15f2..10e43df204 100644--- a/persistence/userrepository/userrepository_test.go+++ b/persistence/userrepository/userrepository_test.go@@ -1,6 +1,7 @@package userrepositoryimport (+ "database/sql""os""testing"@@ -53,8 +54,8 @@ func TestGetExternalAPIUserForAccessTokenAndScope_OnlyAPIUsers(t *testing.T) {}// grantSession is confined to users a plugin registered. UserRegisteredByPlugin-// is the durable ownership check behind that, matching the "<slug>:<authId>"-// plugin.auth identity RegisterUser stores.+// is the durable ownership check behind that, matching the plugin.auth identity+// RegisterUser stores with provider=<slug>.func TestUserRegisteredByPlugin(t *testing.T) {r := newTestRepo(t)@@ -62,8 +63,9 @@ func TestUserRegisteredByPlugin(t *testing.T) {if err != nil {t.Fatalf("create user: %v", err)}- // Mirror what RegisterUser stores: "<slug>:<authId>" under PluginAuth.- if err := r.AddAuth(user.ID, "basic-auth:shared", models.PluginAuth); err != nil {+ // Mirror what RegisterUser stores: auth_key=authId, provider=<slug>, under+ // the PluginAuth type.+ if err := r.AddAuth(user.ID, "shared", models.PluginAuth, &models.LinkedIdentityFields{Provider: "basic-auth"}); err != nil {t.Fatalf("add auth: %v", err)}@@ -76,7 +78,7 @@ func TestUserRegisteredByPlugin(t *testing.T) {{"owning plugin", "basic-auth", user.ID, true},{"different plugin", "github-auth", user.ID, false},{"unknown user", "basic-auth", "no-such-user", false},- // Slug prefix must respect the ":" separator, not match a partial slug.+ // Provider is matched on exact equality, so a partial slug is no match.{"partial slug is not a match", "basic", user.ID, false},}for _, tc := range cases {@@ -87,3 +89,171 @@ func TestUserRegisteredByPlugin(t *testing.T) {})}}++// A plugin identity (provider=slug, auth_key) must map to exactly one user. The+// partial unique index backs RegisterUser's find-or-create so a concurrent+// double-registration can't mint two users for the same external identity.+func TestPluginIdentityIsUnique(t *testing.T) {+ r := newTestRepo(t)++ a, _, err := r.CreateAnonymousUser("first")+ if err != nil {+ t.Fatalf("create user a: %v", err)+ }+ b, _, err := r.CreateAnonymousUser("second")+ if err != nil {+ t.Fatalf("create user b: %v", err)+ }++ githubID := &models.LinkedIdentityFields{Provider: "github-auth"}+ if err := r.AddAuth(a.ID, "583231", models.PluginAuth, githubID); err != nil {+ t.Fatalf("first link: %v", err)+ }+ // The same (provider, auth_key) for a different user must be rejected.+ if err := r.AddAuth(b.ID, "583231", models.PluginAuth, githubID); err == nil {+ t.Fatal("expected duplicate plugin identity to be rejected, got nil")+ }+ // The same raw id under a different provider is a distinct identity: allowed.+ if err := r.AddAuth(b.ID, "583231", models.PluginAuth, &models.LinkedIdentityFields{Provider: "discord-auth"}); err != nil {+ t.Fatalf("distinct provider link: %v", err)+ }+}++// TestGetUserByAuthBuiltinRoundTrip is the core regression guard for the+// token->auth_key rename: a returning IndieAuth/Fediverse user must still+// resolve by (auth_key, type), and type must keep the two providers distinct.+func TestGetUserByAuthBuiltinRoundTrip(t *testing.T) {+ r := newTestRepo(t)++ indie, _, err := r.CreateAnonymousUser("indie user")+ if err != nil {+ t.Fatalf("create indie user: %v", err)+ }+ const me = "https://me.example.com"+ if err := r.AddAuth(indie.ID, me, models.IndieAuth, &models.LinkedIdentityFields{ProfileURL: me}); err != nil {+ t.Fatalf("add indieauth: %v", err)+ }++ fedi, _, err := r.CreateAnonymousUser("fedi user")+ if err != nil {+ t.Fatalf("create fedi user: %v", err)+ }+ const account = "@[email protected]"+ if err := r.AddAuth(fedi.ID, account, models.Fediverse, &models.LinkedIdentityFields{Handle: account}); err != nil {+ t.Fatalf("add fediverse: %v", err)+ }++ if u := r.GetUserByAuth(me, models.IndieAuth); u == nil || u.ID != indie.ID {+ t.Errorf("GetUserByAuth(me, IndieAuth) = %v, want %s", u, indie.ID)+ }+ if u := r.GetUserByAuth(account, models.Fediverse); u == nil || u.ID != fedi.ID {+ t.Errorf("GetUserByAuth(account, Fediverse) = %v, want %s", u, fedi.ID)+ }+ // type discriminates: the right key under the wrong provider type matches no one.+ if u := r.GetUserByAuth(me, models.Fediverse); u != nil {+ t.Errorf("GetUserByAuth(me, Fediverse) = %v, want nil", u)+ }+ if u := r.GetUserByAuth("https://nobody.example", models.IndieAuth); u != nil {+ t.Errorf("GetUserByAuth(unknown) = %v, want nil", u)+ }+}++// TestPluginAuthNamespacing locks in the security invariant behind the+// type+provider split: a plugin identity resolves only within its own slug, and+// a plugin whose slug equals a built-in provider name ("fediverse") can neither+// resolve nor claim ownership of the built-in identity — that row's type is+// 'fediverse', not 'plugin.auth'.+func TestPluginAuthNamespacing(t *testing.T) {+ r := newTestRepo(t)++ // A real Fediverse user.+ fedi, _, err := r.CreateAnonymousUser("real fedi")+ if err != nil {+ t.Fatalf("create fedi: %v", err)+ }+ const account = "@[email protected]"+ if err := r.AddAuth(fedi.ID, account, models.Fediverse, &models.LinkedIdentityFields{Handle: account}); err != nil {+ t.Fatalf("add fediverse: %v", err)+ }++ // A plugin whose slug is "fediverse" registers a user with the SAME raw key.+ pluginUser, _, err := r.CreateAnonymousUser("plugin user")+ if err != nil {+ t.Fatalf("create plugin user: %v", err)+ }+ if err := r.AddAuth(pluginUser.ID, account, models.PluginAuth, &models.LinkedIdentityFields{Provider: "fediverse"}); err != nil {+ t.Fatalf("add plugin auth: %v", err)+ }++ // The plugin lookup resolves to the plugin's own user, never the built-in one.+ if u := r.GetUserByPluginAuth("fediverse", account); u == nil || u.ID != pluginUser.ID {+ t.Errorf("GetUserByPluginAuth(fediverse, account) = %v, want %s", u, pluginUser.ID)+ }+ // A different slug with the same key resolves to nobody.+ if u := r.GetUserByPluginAuth("github-auth", account); u != nil {+ t.Errorf("GetUserByPluginAuth(github-auth, account) = %v, want nil", u)+ }+ // Ownership: the plugin owns the user it registered, but NOT the built-in one.+ if !r.UserRegisteredByPlugin("fediverse", pluginUser.ID) {+ t.Error("plugin should own the user it registered")+ }+ if r.UserRegisteredByPlugin("fediverse", fedi.ID) {+ t.Error("plugin slug 'fediverse' must NOT own the built-in Fediverse user")+ }+}++// TestAddAuthPersistsLinkedIdentityFields verifies AddAuth actually writes the+// provider/profile_url/handle/is_public columns. There is no Go reader for them+// yet, so assert against the row directly.+func TestAddAuthPersistsLinkedIdentityFields(t *testing.T) {+ r := newTestRepo(t)+ u, _, err := r.CreateAnonymousUser("plugin user")+ if err != nil {+ t.Fatalf("create user: %v", err)+ }+ fields := &models.LinkedIdentityFields{+ Provider: "github-auth",+ ProfileURL: "https://github.com/octocat",+ Handle: "octocat",+ Public: true,+ }+ if err := r.AddAuth(u.ID, "583231", models.PluginAuth, fields); err != nil {+ t.Fatalf("add auth: %v", err)+ }++ var authKey, typ, provider string+ var profileURL, handle sql.NullString+ var isPublic bool+ if err := r.datastore.DB.QueryRow(+ `SELECT auth_key, type, provider, profile_url, handle, is_public FROM auth WHERE user_id = ?`, u.ID,+ ).Scan(&authKey, &typ, &provider, &profileURL, &handle, &isPublic); err != nil {+ t.Fatalf("read back: %v", err)+ }+ if authKey != "583231" || typ != string(models.PluginAuth) || provider != "github-auth" {+ t.Errorf("got auth_key=%q type=%q provider=%q", authKey, typ, provider)+ }+ if profileURL.String != "https://github.com/octocat" || handle.String != "octocat" || !isPublic {+ t.Errorf("profile fields not persisted: url=%v handle=%v public=%v", profileURL, handle, isPublic)+ }+}++// TestAuthProviderLabel covers the admin user-list label after the switch from+// token-prefix parsing to the provider column.+func TestAuthProviderLabel(t *testing.T) {+ cases := []struct {+ authType string+ provider string+ want string+ }{+ {"indieauth", "indieauth", "IndieAuth"},+ {"fediverse", "fediverse", "Fediverse"},+ {"plugin.auth", "github-auth", "github-auth"},+ {"plugin.auth", "", "Plugin"},+ {"something-else", "something-else", "something-else"},+ }+ for _, tc := range cases {+ if got := authProviderLabel(tc.authType, tc.provider); got != tc.want {+ t.Errorf("authProviderLabel(%q, %q) = %q, want %q", tc.authType, tc.provider, got, tc.want)+ }+ }+}diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex bcba63b908..f5c6667503 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -10,6 +10,7 @@ import ("io""io/fs""net/http"+ "net/url""os""path/filepath""regexp"@@ -1635,6 +1636,25 @@ func validatePluginGrantedScopes(scopes []string) error {return nil}+// validateProfileURL rejects a plugin-supplied profile URL that isn't a plain+// http(s) link. The URL is stored as a verified identity and rendered as a+// clickable public link later, so a non-http scheme (javascript:, data:) or a+// hostless value must fail at registration rather than ship to a browser. An+// empty URL is allowed: a gate-only plugin surfaces nothing publicly.+func validateProfileURL(profileURL string) error {+ if profileURL == "" {+ return nil+ }+ u, err := url.Parse(profileURL)+ if err != nil {+ return fmt.Errorf("invalid profile URL: %w", err)+ }+ if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {+ return fmt.Errorf("profile URL must be an http(s) link")+ }+ return nil+}+// wireAuthHostFns wires the viewer-authentication host functions: register an// authenticated user for an external (plugin-provided) identity, and mint a// signed gate session for them.@@ -1649,37 +1669,63 @@ func wireAuthHostFns(env *plugins.HostEnv, deps Deps) {return}- env.RegisterUser = func(pluginName, authID, displayName string, scopes []string) (string, error) {- // Validate requested scopes against the plugin-grantable allow-list+ env.RegisterUser = func(pluginName string, req plugins.UserRegisterRequest) (string, error) {+ // Validate requested scopes and the profile URL against their boundaries// BEFORE creating any user, so a disallowed scope (e.g. HAS_ADMIN_ACCESS)- // fails cleanly without leaving an orphan account.- if err := validatePluginGrantedScopes(scopes); err != nil {+ // or a bad URL fails cleanly without leaving an orphan account.+ if err := validatePluginGrantedScopes(req.Scopes); err != nil {return "", err}- // Namespace the external identity by plugin slug so two auth plugins- // can't collide on, or impersonate, each other's users.- namespaced := pluginName + ":" + authID+ if err := validateProfileURL(req.ProfileURL); err != nil {+ return "", err+ }+ // The identity is keyed by (provider=plugin slug, auth_key=authId), so+ // two auth plugins can't collide on, or impersonate, each other's users.var userID string- if existing := users.GetUserByAuth(namespaced, models.PluginAuth); existing != nil {+ if existing := users.GetUserByPluginAuth(pluginName, req.AuthID); existing != nil {userID = existing.ID} else {- user, _, err := users.CreateAnonymousUser(displayName)+ user, _, err := users.CreateAnonymousUser(req.DisplayName)if err != nil {return "", err}- if err := users.AddAuth(user.ID, namespaced, models.PluginAuth); err != nil {- return "", err+ // Profile fields are captured at registration only. is_public is the+ // user's consent and must not be silently re-flipped by the plugin on+ // later logins; profileUrl/handle staleness is a worthwhile trade for+ // not adding an update path until the public UI needs one.+ // ponytail: capture-on-create; add UpdateAuth when the badge UI lands.+ fields := &models.LinkedIdentityFields{+ Provider: pluginName,+ ProfileURL: req.ProfileURL,+ Handle: req.Handle,+ Public: req.Public,}- if err := users.SetUserAsAuthenticated(user.ID); err != nil {- log.Errorln("plugin", pluginName, "set user authenticated:", err)+ if err := users.AddAuth(user.ID, req.AuthID, models.PluginAuth, fields); err != nil {+ // AddAuth failed after the user was created — most likely a+ // concurrent registration won the race against the unique plugin+ // identity index. Don't leave the half-built user (with its access+ // token) orphaned: drop it, and if the identity now resolves, adopt+ // the winner so the racing login still succeeds as one user.+ if delErr := users.DeleteUser(user.ID); delErr != nil {+ log.Errorln("plugin", pluginName, "cleanup user after failed auth link:", delErr)+ }+ winner := users.GetUserByPluginAuth(pluginName, req.AuthID)+ if winner == nil {+ return "", err+ }+ userID = winner.ID+ } else {+ if err := users.SetUserAsAuthenticated(user.ID); err != nil {+ log.Errorln("plugin", pluginName, "set user authenticated:", err)+ }+ userID = user.ID}- userID = user.ID}// Map the provider's roles onto Owncast scopes (e.g. MODERATOR), applied// on every login so an upstream role change takes effect. The scopes// were allow-listed above.- if len(scopes) > 0 {- if err := users.SetUserScopes(userID, scopes); err != nil {+ if len(req.Scopes) > 0 {+ if err := users.SetUserScopes(userID, req.Scopes); err != nil {log.Errorln("plugin", pluginName, "set user scopes:", err)}}diff --git a/pluginhost/register_test.go b/pluginhost/register_test.gonew file mode 100644index 0000000000..4261939c55--- /dev/null+++ b/pluginhost/register_test.go@@ -0,0 +1,114 @@+package pluginhost++import (+ "testing"++ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/services/plugins"+)++// validateProfileURL is a trust boundary: a plugin-supplied profile URL is+// stored as a verified identity and later rendered as a clickable public link,+// so only plain http(s) links may pass. Non-http schemes (javascript:, data:),+// hostless values, and unparseable input must be rejected.+func TestValidateProfileURL(t *testing.T) {+ cases := []struct {+ url string+ ok bool+ }{+ {"", true}, // a gate-only plugin surfaces nothing publicly+ {"https://github.com/octocat", true},+ {"http://example.com/u/1", true},+ {"javascript:alert(1)", false},+ {"data:text/html,<script>", false},+ {"ftp://example.com", false},+ {"https://", false}, // no host+ {"/relative/path", false}, // no scheme or host+ {"not a url", false},+ {"ht tp://x", false}, // unparseable (space)+ }+ for _, tc := range cases {+ err := validateProfileURL(tc.url)+ if tc.ok && err != nil {+ t.Errorf("validateProfileURL(%q) = %v, want nil", tc.url, err)+ }+ if !tc.ok && err == nil {+ t.Errorf("validateProfileURL(%q) = nil, want error", tc.url)+ }+ }+}++// newRegisterEnv wires the auth host functions against a fresh in-memory+// datastore, returning the live RegisterUser closure and the repository behind+// it so tests can assert against stored state.+func newRegisterEnv(t *testing.T) (*plugins.HostEnv, userrepository.UserRepository) {+ t.Helper()+ ds, err := datastore.SetupPersistence(":memory:", t.TempDir())+ if err != nil {+ t.Fatalf("setup persistence: %v", err)+ }+ users := userrepository.New(ds)+ env := &plugins.HostEnv{}+ wireAuthHostFns(env, Deps{Datastore: ds, UserRepository: users})+ if env.RegisterUser == nil {+ t.Fatal("RegisterUser was not wired (signing secret failed to establish)")+ }+ return env, users+}++// TestRegisterUser exercises the whole users.register flow: find-or-create+// idempotency, per-plugin namespacing, and that scope/URL rejections fail+// before any user is created (so a rejected call leaves no orphan account).+func TestRegisterUser(t *testing.T) {+ env, users := newRegisterEnv(t)++ // Happy path creates an authenticated user.+ id, err := env.RegisterUser("github-auth", plugins.UserRegisterRequest{+ AuthID: "583231",+ DisplayName: "octocat",+ ProfileURL: "https://github.com/octocat",+ Handle: "octocat",+ Public: true,+ })+ if err != nil || id == "" {+ t.Fatalf("register: id=%q err=%v", id, err)+ }++ // Idempotent: the same identity resolves to the same user, not a duplicate.+ again, err := env.RegisterUser("github-auth", plugins.UserRegisterRequest{AuthID: "583231"})+ if err != nil || again != id {+ t.Fatalf("re-register: got %q err=%v, want %q", again, err, id)+ }++ // A different plugin with the same raw authId is a distinct user. (A new-user+ // registration must carry a display name; CreateAnonymousUser rejects empty.)+ other, err := env.RegisterUser("discord-auth", plugins.UserRegisterRequest{AuthID: "583231", DisplayName: "octocat"})+ if err != nil {+ t.Fatalf("other plugin register: %v", err)+ }+ if other == id {+ t.Error("a different plugin must not resolve to the same user")+ }++ // A disallowed scope is rejected, and no orphan user is left behind.+ if _, err := env.RegisterUser("github-auth", plugins.UserRegisterRequest{+ AuthID: "scope-reject", Scopes: []string{models.ScopeHasAdminAccess},+ }); err == nil {+ t.Error("expected admin scope to be rejected")+ }+ if u := users.GetUserByPluginAuth("github-auth", "scope-reject"); u != nil {+ t.Error("scope-rejected registration left an orphan user")+ }++ // A bad profile URL is rejected, and no orphan user is left behind.+ if _, err := env.RegisterUser("github-auth", plugins.UserRegisterRequest{+ AuthID: "url-reject", ProfileURL: "javascript:alert(1)",+ }); err == nil {+ t.Error("expected bad profile URL to be rejected")+ }+ if u := users.GetUserByPluginAuth("github-auth", "url-reject"); u != nil {+ t.Error("url-rejected registration left an orphan user")+ }+}diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.goindex be976e05e7..679dde65de 100644--- a/services/plugins/hostfns.go+++ b/services/plugins/hostfns.go@@ -300,11 +300,13 @@ type HostEnv struct {Users func() []HostUser // users.readUserGet func(id string) (HostUser, bool) // users.read// RegisterUser finds-or-creates an authenticated Owncast user for an external- // identity (users.register). pluginName namespaces authID internally so two- // auth plugins can't collide on, or spoof, each other's identities. Returns- // the Owncast user ID. Optional; nil → the host function reports an error to- // the plugin.- RegisterUser func(pluginName, authID, displayName string, scopes []string) (userID string, err error)+ // identity (users.register). pluginName is the verified calling slug; it+ // scopes the identity so two auth plugins can't collide on, or spoof, each+ // other's users. req carries the plugin-supplied identity (authId, optional+ // display name, scopes, and optional public-profile fields). Returns the+ // Owncast user ID. Optional; nil → the host function reports an error to the+ // plugin.+ RegisterUser func(pluginName string, req UserRegisterRequest) (userID string, err error)// GrantSession mints a signed, stateless session token for an// already-registered user (auth.gate). ttlSeconds of 0 means the host// default. It returns the token; the host function attaches it as a cookie@@ -730,10 +732,19 @@ func hostUserGet(env *HostEnv) extism.HostFunction {}// UserRegisterRequest is the JSON payload a plugin sends to owncast.users.register.+//+// The optional ProfileURL/Handle/Public fields describe a public verified+// identity: where it links, how to label it, and whether the user agreed to+// surface it. A gate-only plugin leaves them empty and nothing shows publicly;+// an identity plugin (GitHub, Fediverse, ...) fills them in. The host pins the+// provider to the calling plugin's slug, so it is not part of this payload.type UserRegisterRequest struct {AuthID string `json:"authId"`DisplayName string `json:"displayName,omitempty"`Scopes []string `json:"scopes,omitempty"`+ ProfileURL string `json:"profileUrl,omitempty"`+ Handle string `json:"handle,omitempty"`+ Public bool `json:"public,omitempty"`}// UserRegisterResult is the JSON envelope returned to the plugin: the resolved@@ -795,7 +806,7 @@ func hostUsersRegister(env *HostEnv) extism.HostFunction {stack[0] = writeJSON(p, UserRegisterResult{Error: "users.register is not available on this host"})return}- userID, err := env.RegisterUser(ident.slug, req.AuthID, req.DisplayName, req.Scopes)+ userID, err := env.RegisterUser(ident.slug, req)if err != nil {stack[0] = writeJSON(p, UserRegisterResult{Error: err.Error()})returndiff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.jsonindex deccce065b..113364916e 100644--- a/services/plugins/plugin-contract.json+++ b/services/plugins/plugin-contract.json@@ -177,6 +177,9 @@"UserRegisterRequest": {"authId": "string","displayName": "string",+ "handle": "string",+ "profileUrl": "string",+ "public": "bool","scopes": "[]string"},"UserRegisterResult": {diff --git a/webserver/handlers/auth/fediverse/fediverse.go b/webserver/handlers/auth/fediverse/fediverse.goindex 14836e1da7..0ddf1b3ec1 100644--- a/webserver/handlers/auth/fediverse/fediverse.go+++ b/webserver/handlers/auth/fediverse/fediverse.go@@ -129,9 +129,11 @@ func (h *Handler) VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Requereturn}- // Otherwise, save this as new auth.+ // Otherwise, save this as new auth. The @me@host account is the auth key and+ // the human-readable handle; the public profile URL is left to be resolved+ // from the handle (webfinger) when the public badge UI needs it.log.Debug("fediverse account does not already exist, saving it as a new one for the current user")- if err := h.userRepository.AddAuth(authRegistration.UserID, authRegistration.Account, models.Fediverse); err != nil {+ if err := h.userRepository.AddAuth(authRegistration.UserID, authRegistration.Account, models.Fediverse, &models.LinkedIdentityFields{Handle: authRegistration.Account}); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}diff --git a/webserver/handlers/auth/indieauth/client.go b/webserver/handlers/auth/indieauth/client.goindex 275d95329b..d2bbc1352a 100644--- a/webserver/handlers/auth/indieauth/client.go+++ b/webserver/handlers/auth/indieauth/client.go@@ -116,9 +116,10 @@ func (h *Handler) HandleRedirect(w http.ResponseWriter, r *http.Request) {return}- // Otherwise, save this as new auth.+ // Otherwise, save this as new auth. The IndieAuth "me" URL is both the auth+ // key and the public profile link, so record it as the profile URL too.log.Debug("indieauth token does not already exist, saving it as a new one for the current user")- if err := h.userRepository.AddAuth(request.UserID, response.Me, models.IndieAuth); err != nil {+ if err := h.userRepository.AddAuth(request.UserID, response.Me, models.IndieAuth, &models.LinkedIdentityFields{ProfileURL: response.Me}); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}