Browse Source
* Able to authenticate user against IndieAuth. For #1273 * WIP server indieauth endpoint. For https://github.com/owncast/owncast/issues/1272 * Add migration to remove access tokens from user * Add authenticated bool to user for display purposes * Add indieauth modal and auth flair to display names. For #1273 * Validate URLs and display errors * Renames, cleanups * Handle relative auth endpoint paths. Add error handling for missing redirects. * Disallow using display names in use by registered users. Closes #1810 * Verify code verifier via code challenge on callback * Use relative path to authorization_endpoint * Post-rebase fixes * Use a timestamp instead of a bool for authenticated * Propertly handle and display error in modal * Use auth'ed timestamp to derive authenticated flag to display in chat * Fediverse chat auth via OTP * Increase validity time just in case * Add fediverse auth into auth modal * Text, validation, cleanup updates for fedi auth * Fix typo * Remove unused images * Remove unused file * Add chat display name to auth modal textpull/1872/head
21 changed files with 855 additions and 81 deletions
@ -0,0 +1,46 @@
@@ -0,0 +1,46 @@
|
||||
package webfinger |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
// GetWebfingerLinks will return webfinger data for an account.
|
||||
func GetWebfingerLinks(account string) ([]map[string]interface{}, error) { |
||||
type webfingerResponse struct { |
||||
Links []map[string]interface{} `json:"links"` |
||||
} |
||||
|
||||
account = strings.TrimLeft(account, "@") // remove any leading @
|
||||
accountComponents := strings.Split(account, "@") |
||||
fediverseServer := accountComponents[1] |
||||
|
||||
// HTTPS is required.
|
||||
requestURL, err := url.Parse("https://" + fediverseServer) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("unable to parse fediverse server host %s", fediverseServer) |
||||
} |
||||
|
||||
requestURL.Path = "/.well-known/webfinger" |
||||
query := requestURL.Query() |
||||
query.Add("resource", fmt.Sprintf("acct:%s", account)) |
||||
requestURL.RawQuery = query.Encode() |
||||
|
||||
response, err := http.DefaultClient.Get(requestURL.String()) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
defer response.Body.Close() |
||||
|
||||
var links webfingerResponse |
||||
decoder := json.NewDecoder(response.Body) |
||||
if err := decoder.Decode(&links); err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
return links.Links, nil |
||||
} |
@ -0,0 +1,63 @@
@@ -0,0 +1,63 @@
|
||||
package fediverse |
||||
|
||||
import ( |
||||
"crypto/rand" |
||||
"io" |
||||
"time" |
||||
) |
||||
|
||||
// OTPRegistration represents a single OTP request.
|
||||
type OTPRegistration struct { |
||||
UserID string |
||||
UserDisplayName string |
||||
Code string |
||||
Account string |
||||
Timestamp time.Time |
||||
} |
||||
|
||||
// Key by access token to limit one OTP request for a person
|
||||
// to be active at a time.
|
||||
var pendingAuthRequests = make(map[string]OTPRegistration) |
||||
|
||||
// RegisterFediverseOTP will start the OTP flow for a user, creating a new
|
||||
// code and returning it to be sent to a destination.
|
||||
func RegisterFediverseOTP(accessToken, userID, userDisplayName, account string) OTPRegistration { |
||||
code, _ := createCode() |
||||
r := OTPRegistration{ |
||||
Code: code, |
||||
UserID: userID, |
||||
UserDisplayName: userDisplayName, |
||||
Account: account, |
||||
Timestamp: time.Now(), |
||||
} |
||||
pendingAuthRequests[accessToken] = r |
||||
|
||||
return r |
||||
} |
||||
|
||||
// ValidateFediverseOTP will verify a OTP code for a auth request.
|
||||
func ValidateFediverseOTP(accessToken, code string) (bool, *OTPRegistration) { |
||||
request, ok := pendingAuthRequests[accessToken] |
||||
|
||||
if !ok || request.Code != code || time.Since(request.Timestamp) > time.Minute*10 { |
||||
return false, nil |
||||
} |
||||
|
||||
delete(pendingAuthRequests, accessToken) |
||||
return true, &request |
||||
} |
||||
|
||||
func createCode() (string, error) { |
||||
table := [...]byte{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'} |
||||
|
||||
digits := 6 |
||||
b := make([]byte, digits) |
||||
n, err := io.ReadAtLeast(rand.Reader, b, digits) |
||||
if n != digits { |
||||
return "", err |
||||
} |
||||
for i := 0; i < len(b); i++ { |
||||
b[i] = table[int(b[i])%len(table)] |
||||
} |
||||
return string(b), nil |
||||
} |
@ -0,0 +1,43 @@
@@ -0,0 +1,43 @@
|
||||
package fediverse |
||||
|
||||
import "testing" |
||||
|
||||
const ( |
||||
accessToken = "fake-access-token" |
||||
account = "blah" |
||||
userID = "fake-user-id" |
||||
userDisplayName = "fake-user-display-name" |
||||
) |
||||
|
||||
func TestOTPFlowValidation(t *testing.T) { |
||||
r := RegisterFediverseOTP(accessToken, userID, userDisplayName, account) |
||||
|
||||
if r.Code == "" { |
||||
t.Error("Code is empty") |
||||
} |
||||
|
||||
if r.Account != account { |
||||
t.Error("Account is not set correctly") |
||||
} |
||||
|
||||
if r.Timestamp.IsZero() { |
||||
t.Error("Timestamp is empty") |
||||
} |
||||
|
||||
valid, registration := ValidateFediverseOTP(accessToken, r.Code) |
||||
if !valid { |
||||
t.Error("Code is not valid") |
||||
} |
||||
|
||||
if registration.Account != account { |
||||
t.Error("Account is not set correctly") |
||||
} |
||||
|
||||
if registration.UserID != userID { |
||||
t.Error("UserID is not set correctly") |
||||
} |
||||
|
||||
if registration.UserDisplayName != userDisplayName { |
||||
t.Error("UserDisplayName is not set correctly") |
||||
} |
||||
} |
@ -0,0 +1,98 @@
@@ -0,0 +1,98 @@
|
||||
package fediverse |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"net/http" |
||||
|
||||
"github.com/owncast/owncast/activitypub" |
||||
"github.com/owncast/owncast/auth" |
||||
"github.com/owncast/owncast/auth/fediverse" |
||||
fediverseauth "github.com/owncast/owncast/auth/fediverse" |
||||
"github.com/owncast/owncast/controllers" |
||||
"github.com/owncast/owncast/core/chat" |
||||
"github.com/owncast/owncast/core/data" |
||||
"github.com/owncast/owncast/core/user" |
||||
log "github.com/sirupsen/logrus" |
||||
) |
||||
|
||||
// RegisterFediverseOTPRequest registers a new OTP request for the given access token.
|
||||
func RegisterFediverseOTPRequest(u user.User, w http.ResponseWriter, r *http.Request) { |
||||
type request struct { |
||||
FediverseAccount string `json:"account"` |
||||
} |
||||
var req request |
||||
decoder := json.NewDecoder(r.Body) |
||||
if err := decoder.Decode(&req); err != nil { |
||||
controllers.WriteSimpleResponse(w, false, "Could not decode request: "+err.Error()) |
||||
return |
||||
} |
||||
|
||||
accessToken := r.URL.Query().Get("accessToken") |
||||
reg := fediverseauth.RegisterFediverseOTP(accessToken, u.ID, u.DisplayName, req.FediverseAccount) |
||||
msg := fmt.Sprintf("<p>This is an automated message from %s. If you did not request this message please ignore or block. Your requested one-time code is:</p><p>%s</p>", data.GetServerName(), reg.Code) |
||||
if err := activitypub.SendDirectFederatedMessage(msg, reg.Account); err != nil { |
||||
controllers.WriteSimpleResponse(w, false, "Could not send code to fediverse: "+err.Error()) |
||||
return |
||||
} |
||||
|
||||
controllers.WriteSimpleResponse(w, true, "") |
||||
} |
||||
|
||||
// VerifyFediverseOTPRequest verifies the given OTP code for the given access token.
|
||||
func VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) { |
||||
type request struct { |
||||
Code string `json:"code"` |
||||
} |
||||
|
||||
var req request |
||||
decoder := json.NewDecoder(r.Body) |
||||
if err := decoder.Decode(&req); err != nil { |
||||
controllers.WriteSimpleResponse(w, false, "Could not decode request: "+err.Error()) |
||||
return |
||||
} |
||||
accessToken := r.URL.Query().Get("accessToken") |
||||
valid, authRegistration := fediverse.ValidateFediverseOTP(accessToken, req.Code) |
||||
if !valid { |
||||
w.WriteHeader(http.StatusForbidden) |
||||
return |
||||
} |
||||
|
||||
// Check if a user with this auth already exists, if so, log them in.
|
||||
if u := auth.GetUserByAuth(authRegistration.Account, auth.Fediverse); u != nil { |
||||
// Handle existing auth.
|
||||
log.Debugln("user with provided fedvierse identity already exists, logging them in") |
||||
|
||||
// Update the current user's access token to point to the existing user id.
|
||||
userID := u.ID |
||||
if err := user.SetAccessTokenToOwner(accessToken, userID); err != nil { |
||||
controllers.WriteSimpleResponse(w, false, err.Error()) |
||||
return |
||||
} |
||||
|
||||
loginMessage := fmt.Sprintf("**%s** is now authenticated as **%s**", authRegistration.UserDisplayName, u.DisplayName) |
||||
if err := chat.SendSystemAction(loginMessage, true); err != nil { |
||||
log.Errorln(err) |
||||
} |
||||
|
||||
controllers.WriteSimpleResponse(w, true, "") |
||||
|
||||
return |
||||
} |
||||
|
||||
// Otherwise, save this as new auth.
|
||||
log.Debug("fediverse account does not already exist, saving it as a new one for the current user") |
||||
if err := auth.AddAuth(authRegistration.UserID, authRegistration.Account, auth.Fediverse); err != nil { |
||||
controllers.WriteSimpleResponse(w, false, err.Error()) |
||||
return |
||||
} |
||||
|
||||
// Update the current user's authenticated flag so we can show it in
|
||||
// the chat UI.
|
||||
if err := user.SetUserAsAuthenticated(authRegistration.UserID); err != nil { |
||||
log.Errorln(err) |
||||
} |
||||
|
||||
controllers.WriteSimpleResponse(w, true, "") |
||||
w.WriteHeader(http.StatusOK) |
||||
} |
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 9.9 KiB |
@ -1,3 +0,0 @@
@@ -1,3 +0,0 @@
|
||||
import { URL_CHAT_INDIEAUTH_BEGIN } from '../utils/constants.js'; |
||||
|
||||
export async function beginIndieAuthFlow() {} |
@ -0,0 +1,206 @@
@@ -0,0 +1,206 @@
|
||||
import { h, Component } from '/js/web_modules/preact.js'; |
||||
import htm from '/js/web_modules/htm.js'; |
||||
|
||||
const html = htm.bind(h); |
||||
|
||||
export default class FediverseAuth extends Component { |
||||
constructor(props) { |
||||
super(props); |
||||
|
||||
this.submitButtonPressed = this.submitButtonPressed.bind(this); |
||||
|
||||
this.state = { |
||||
account: '', |
||||
code: '', |
||||
errorMessage: null, |
||||
loading: false, |
||||
verifying: false, |
||||
valid: false, |
||||
}; |
||||
} |
||||
|
||||
async makeRequest(url, data) { |
||||
const rawResponse = await fetch(url, { |
||||
method: 'POST', |
||||
headers: { |
||||
Accept: 'application/json', |
||||
'Content-Type': 'application/json', |
||||
}, |
||||
body: JSON.stringify(data), |
||||
}); |
||||
|
||||
const content = await rawResponse.json(); |
||||
if (content.message) { |
||||
this.setState({ errorMessage: content.message, loading: false }); |
||||
return; |
||||
} |
||||
} |
||||
|
||||
switchToCodeVerify() { |
||||
this.setState({ verifying: true, loading: false }); |
||||
} |
||||
|
||||
async validateCodeButtonPressed() { |
||||
const { accessToken } = this.props; |
||||
const { code } = this.state; |
||||
|
||||
this.setState({ loading: true, errorMessage: null }); |
||||
|
||||
const url = `/api/auth/fediverse/verify?accessToken=${accessToken}`; |
||||
const data = { code: code }; |
||||
|
||||
try { |
||||
await this.makeRequest(url, data); |
||||
|
||||
// Success. Reload the page.
|
||||
window.location = '/'; |
||||
} catch (e) { |
||||
console.error(e); |
||||
this.setState({ errorMessage: e, loading: false }); |
||||
} |
||||
} |
||||
|
||||
async registerAccountButtonPressed() { |
||||
const { accessToken } = this.props; |
||||
const { account, valid } = this.state; |
||||
|
||||
if (!valid) { |
||||
return; |
||||
} |
||||
|
||||
const url = `/api/auth/fediverse?accessToken=${accessToken}`; |
||||
const normalizedAccount = account.replace(/^@+/, ''); |
||||
const data = { account: normalizedAccount }; |
||||
|
||||
this.setState({ loading: true, errorMessage: null }); |
||||
|
||||
try { |
||||
await this.makeRequest(url, data); |
||||
this.switchToCodeVerify(); |
||||
} catch (e) { |
||||
console.error(e); |
||||
this.setState({ errorMessage: e, loading: false }); |
||||
} |
||||
} |
||||
|
||||
async submitButtonPressed() { |
||||
const { verifying } = this.state; |
||||
if (verifying) { |
||||
this.validateCodeButtonPressed(); |
||||
} else { |
||||
this.registerAccountButtonPressed(); |
||||
} |
||||
} |
||||
|
||||
onInput = (e) => { |
||||
const { value } = e.target; |
||||
const { verifying } = this.state; |
||||
|
||||
if (verifying) { |
||||
this.setState({ code: value }); |
||||
return; |
||||
} |
||||
|
||||
const valid = validateAccount(value); |
||||
this.setState({ account: value, valid }); |
||||
}; |
||||
|
||||
render() { |
||||
const { errorMessage, account, code, valid, loading, verifying } = |
||||
this.state; |
||||
const { authenticated, username } = this.props; |
||||
const buttonState = valid ? '' : 'cursor-not-allowed opacity-50'; |
||||
|
||||
const loaderStyle = loading ? 'flex' : 'none'; |
||||
const message = verifying |
||||
? 'Paste in the code that was sent to your Fediverse account. If you did not receive a code, make sure you can accept direct messages.' |
||||
: !authenticated |
||||
? html`Receive a direct message from on the Fediverse to ${' '} link your
|
||||
account to ${' '} <span class="font-bold">${username}</span>, or login |
||||
as a previously linked chat user.` |
||||
: html`<span
|
||||
><b>You are already authenticated</b>. However, you can add other |
||||
accounts or log in as a different user.</span |
||||
>`;
|
||||
const label = verifying ? 'Code' : 'Your fediverse account'; |
||||
const placeholder = verifying ? '123456' : 'youraccount@fediverse.server'; |
||||
const buttonText = verifying ? 'Verify' : 'Authenticate with Fediverse'; |
||||
|
||||
const error = errorMessage |
||||
? html` <div
|
||||
class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" |
||||
role="alert" |
||||
> |
||||
<div class="font-bold mb-2">There was an error.</div> |
||||
<div class="block mt-2"> |
||||
Server error: |
||||
<div>${errorMessage}</div> |
||||
</div> |
||||
</div>` |
||||
: null; |
||||
|
||||
return html` |
||||
<div class="bg-gray-100 bg-center bg-no-repeat"> |
||||
<p class="text-gray-700 text-md">${message}</p> |
||||
|
||||
${error} |
||||
|
||||
<div class="mb34"> |
||||
<label |
||||
class="block text-gray-700 text-sm font-semibold mt-6" |
||||
for="username" |
||||
> |
||||
${label} |
||||
</label> |
||||
<input |
||||
onInput=${this.onInput} |
||||
type="url" |
||||
value=${verifying ? code : account} |
||||
class="border bg-white rounded w-full py-2 px-3 mb-2 mt-2 text-indigo-700 leading-tight focus:outline-none focus:shadow-outline" |
||||
id="username" |
||||
type="text" |
||||
placeholder=${placeholder} |
||||
/> |
||||
<button |
||||
class="bg-indigo-500 hover:bg-indigo-600 text-white font-bold py-2 mt-6 px-4 rounded focus:outline-none focus:shadow-outline ${buttonState}" |
||||
type="button" |
||||
onClick=${this.submitButtonPressed} |
||||
> |
||||
${buttonText} |
||||
</button> |
||||
</div> |
||||
|
||||
<p class="mt-4"> |
||||
<details> |
||||
<summary class="cursor-pointer"> |
||||
Learn more about using the Fediverse to authenticate with chat. |
||||
</summary> |
||||
<div class="inline"> |
||||
<p class="mt-4"> |
||||
You can link your chat identity with your Fediverse identity. |
||||
Next time you want to use this chat identity you can again go |
||||
through the Fediverse authentication. |
||||
</p> |
||||
</div> |
||||
</details> |
||||
</p> |
||||
|
||||
<div |
||||
id="follow-loading-spinner-container" |
||||
style="display: ${loaderStyle}" |
||||
> |
||||
<img id="follow-loading-spinner" src="/img/loading.gif" /> |
||||
<p class="text-gray-700 text-lg">Authenticating.</p> |
||||
<p class="text-gray-600 text-lg">Please wait...</p> |
||||
</div> |
||||
</div> |
||||
`;
|
||||
} |
||||
} |
||||
|
||||
function validateAccount(account) { |
||||
account = account.replace(/^@+/, ''); |
||||
var regex = |
||||
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; |
||||
return regex.test(String(account).toLowerCase()); |
||||
} |
@ -0,0 +1,162 @@
@@ -0,0 +1,162 @@
|
||||
import { h, Component } from '/js/web_modules/preact.js'; |
||||
import htm from '/js/web_modules/htm.js'; |
||||
import { ExternalActionButton } from './external-action-modal.js'; |
||||
|
||||
const html = htm.bind(h); |
||||
|
||||
export default class AuthModal extends Component { |
||||
constructor(props) { |
||||
super(props); |
||||
|
||||
this.submitButtonPressed = this.submitButtonPressed.bind(this); |
||||
|
||||
this.state = { |
||||
errorMessage: null, |
||||
loading: false, |
||||
valid: false, |
||||
}; |
||||
} |
||||
|
||||
async submitButtonPressed() { |
||||
const { accessToken } = this.props; |
||||
const { host, valid } = this.state; |
||||
|
||||
if (!valid) { |
||||
return; |
||||
} |
||||
|
||||
const url = `/api/auth/indieauth?accessToken=${accessToken}`; |
||||
const data = { authHost: host }; |
||||
|
||||
this.setState({ loading: true }); |
||||
|
||||
try { |
||||
const rawResponse = await fetch(url, { |
||||
method: 'POST', |
||||
headers: { |
||||
Accept: 'application/json', |
||||
'Content-Type': 'application/json', |
||||
}, |
||||
body: JSON.stringify(data), |
||||
}); |
||||
|
||||
const content = await rawResponse.json(); |
||||
if (content.message) { |
||||
this.setState({ errorMessage: content.message, loading: false }); |
||||
return; |
||||
} else if (!content.redirect) { |
||||
this.setState({ |
||||
errorMessage: 'Auth provider did not return a redirect URL.', |
||||
loading: false, |
||||
}); |
||||
return; |
||||
} |
||||
|
||||
const redirect = content.redirect; |
||||
window.location = redirect; |
||||
} catch (e) { |
||||
console.error(e); |
||||
this.setState({ errorMessage: e, loading: false }); |
||||
} |
||||
} |
||||
|
||||
onInput = (e) => { |
||||
const { value } = e.target; |
||||
let valid = validateURL(value); |
||||
this.setState({ host: value, valid }); |
||||
}; |
||||
|
||||
render() { |
||||
const { errorMessage, host, valid, loading } = this.state; |
||||
const { authenticated } = this.props; |
||||
const buttonState = valid ? '' : 'cursor-not-allowed opacity-50'; |
||||
|
||||
const loaderStyle = loading ? 'flex' : 'none'; |
||||
|
||||
const message = !authenticated |
||||
? `While you can chat completely anonymously you can also add
|
||||
authentication so you can rejoin with the same chat persona from any |
||||
device or browser.` |
||||
: `You are already authenticated, however you can add other external sites or accounts to your chat account or log in as a different user.`; |
||||
|
||||
const error = errorMessage |
||||
? html` <div
|
||||
class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" |
||||
role="alert" |
||||
> |
||||
<div class="font-bold mb-2">There was an error.</div> |
||||
<div class="block mt-2"> |
||||
Server error: |
||||
<div>${errorMessage}</div> |
||||
</div> |
||||
</div>` |
||||
: null; |
||||
|
||||
return html` |
||||
<div class="bg-gray-100 bg-center bg-no-repeat p-4"> |
||||
<p class="text-gray-700 text-md">${message}</p> |
||||
|
||||
${error} |
||||
|
||||
<div class="mb34"> |
||||
<label |
||||
class="block text-gray-700 text-sm font-semibold mt-6" |
||||
for="username" |
||||
> |
||||
IndieAuth with your own site |
||||
</label> |
||||
<input |
||||
onInput=${this.onInput} |
||||
type="url" |
||||
value=${host} |
||||
class="border bg-white rounded w-full py-2 px-3 mb-2 mt-2 text-indigo-700 leading-tight focus:outline-none focus:shadow-outline" |
||||
id="username" |
||||
type="text" |
||||
placeholder="https://yoursite.com" |
||||
/> |
||||
<button |
||||
class="bg-indigo-500 hover:bg-indigo-600 text-white font-bold py-2 mt-6 px-4 rounded focus:outline-none focus:shadow-outline ${buttonState}" |
||||
type="button" |
||||
onClick=${this.submitButtonPressed} |
||||
> |
||||
Authenticate with IndieAuth |
||||
</button> |
||||
<p> |
||||
Learn more about |
||||
<a class="underline" href="https://indieauth.net/">IndieAuth</a>. |
||||
</p> |
||||
</div> |
||||
|
||||
<div |
||||
id="follow-loading-spinner-container" |
||||
style="display: ${loaderStyle}" |
||||
> |
||||
<img id="follow-loading-spinner" src="/img/loading.gif" /> |
||||
<p class="text-gray-700 text-lg">Authenticating.</p> |
||||
<p class="text-gray-600 text-lg">Please wait...</p> |
||||
</div> |
||||
</div> |
||||
`;
|
||||
} |
||||
} |
||||
|
||||
function validateURL(url) { |
||||
if (!url) { |
||||
return false; |
||||
} |
||||
|
||||
try { |
||||
const u = new URL(url); |
||||
if (!u) { |
||||
return false; |
||||
} |
||||
|
||||
if (u.protocol !== 'https:') { |
||||
return false; |
||||
} |
||||
} catch (e) { |
||||
return false; |
||||
} |
||||
|
||||
return true; |
||||
} |
Loading…
Reference in new issue