oauth refactor

This commit is contained in:
Brahim Hadriche committed 2026-07-03 21:34:35 -04:00
1 parent 78ecdec28d
commit 6cb5bfe985
40 files changed
+782 -301

No files matched your search

+3 -1
View File
@@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
- Nothing worth mentioning yet.
### Fixed
- Signed-in accounts no longer get stuck sending failing requests after the login session expires
## [0.48.0] - 2026-07-01
+1
View File
@@ -34,6 +34,7 @@
],
"rooibos": {
"logLevel": 2,
"tags": ["!integration"],
"isRecordingCodeCoverage": false,
"printTestTimes": true,
"showOnlyFailures": true,
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/ContextMenu/ContextMenuUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs"
@@ -44,7 +45,7 @@ function OnNodeready()
DisposableObserveFieldScoped(m.subscribeButton, "buttonSelected", FuncName(OnSubscribeButtonSelected))
SetSubscribeButtonVisibility()
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(SetSubscribeButtonVisibility))
DisposableObserveFieldScoped(m.profilesService, "currentProfileChanged", FuncName(SetSubscribeButtonVisibility))
OnSubscriptionChanged()
DisposableObserveFieldScoped(m.invidious, "subscriptions", FuncName(OnSubscriptionChanged))
end function
@@ -172,7 +173,19 @@ function OnDispose()
end if
end function
function OnSubscribeButtonSelected()
function OnSubscribeButtonSelected() as void
profile = m.profilesService.currentProfile
if profile = invalid
return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
DialogUtils.ShowDialogEx({
title: Tr(Locale.Dialogs.ProfileNeedsReauthTitle)
message: Tr(Locale.Dialogs.ProfileNeedsReauthMessage)
})
return
end if
if m.subscribeJob <> invalid
m.subscribeJob.cancel = true
end if
@@ -185,6 +198,7 @@ function OnSubscribeButtonSelected()
invidious: m.invidious
ucid: m.authorId
subscribe: not m.top.isSubscribed
profile: profile
}
m.subscribeJob = JobSystem.CreateCallback()
@@ -367,7 +381,7 @@ function GetSortingContextMenuOptionsForItem(video as object) as object
end function
function IsLoggedIn() as boolean
return m.invidious.authToken <> invalid
return m.profilesService.currentProfile <> invalid
end function
function OnAuthorIdChange()
@@ -386,7 +400,8 @@ function SetSubscribeButtonVisibility()
end function
function FetchSubscriptionStatus() as void
if not IsLoggedIn()
profile = m.profilesService.currentProfile
if profile = invalid or profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return
end if
@@ -402,7 +417,7 @@ function FetchSubscriptionStatus() as void
input = {
channelView: m.top
ucid: authorId
authToken: m.invidious.authToken
profile: profile
invidious: m.invidious
}
@@ -5,6 +5,7 @@
<field id="isSubscribed" type="boolean" onChange="OnSubscriptionChanged" />
<field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" />
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="preferences" type="node" bind="/Preferences" />
<field id="jobQueue" type="node" bind="/JobQueue" />
<field id="bookmarksService" type="node" bind="/BookmarksService" />
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/CancellationUtils.bs"
@@ -9,7 +10,7 @@ function ExecuteJob() as void
channelView = input.channelView
ucid = input.ucid
invidiousNode = input.invidious
authToken = input.authToken
profile = input.profile
if JobIsCancelled()
JobCancel()
@@ -17,12 +18,18 @@ function ExecuteJob() as void
end if
cancellation = JobGetCancellation()
isInnertubeProfile = authToken.profileNode.type = "youtube"
if isInnertubeProfile
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
JobError("No usable access token to fetch subscription status: " + auth.state)
return
end if
if profile.type = "youtube"
subscriptionStatus = InnertubeService.GetSubscriptionStatusForChannel(ucid, {
cancellation: cancellation
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
accessToken: auth.token
onBehalfOfUser: auth.activeIdentifyToken
})
if subscriptionStatus.error <> invalid
@@ -32,7 +39,7 @@ function ExecuteJob() as void
channelView.isSubscribed = subscriptionStatus.isSubscribed
else
service = new Invidious.InvidiousService(invidiousNode)
subscriptionsResponse = service.GetSubscriptions(cancellation)
subscriptionsResponse = service.GetSubscriptions(auth, cancellation)
if not subscriptionsResponse.IsSuccess()
JobError("Failed to fetch subscriptions: " + subscriptionsResponse.ErrorMessage())
return
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
@job("SubscribeJob")
@@ -8,6 +9,7 @@ function ExecuteJob() as void
invidiousNode = input.invidious
ucid = input.ucid
subscribe = input.subscribe
profile = input.profile
if JobIsCancelled()
JobCancel()
@@ -15,12 +17,19 @@ function ExecuteJob() as void
end if
cancellation = JobGetCancellation()
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
JobError("No usable access token to subscribe/unsubscribe: " + auth.state)
return
end if
service = new Invidious.InvidiousService(invidiousNode)
if subscribe
response = service.Subscribe(ucid, cancellation)
response = service.Subscribe(auth, ucid, cancellation)
else
response = service.Unsubscribe(ucid, cancellation)
response = service.Unsubscribe(auth, ucid, cancellation)
end if
if not response.IsSuccess()
@@ -0,0 +1,46 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
namespace ProfileContentAuthTokenUtils
function DeriveAuthState(profileType as string, accessToken as dynamic, refreshToken as dynamic) as string
if profileType = "youtube"
if StringUtils.IsNullOrEmpty(refreshToken)
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end if
if profileType = "invidious"
if StringUtils.IsNullOrEmpty(accessToken)
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
' The Invidious token is signed JSON carrying its own expire timestamp.
token = StringUtils.ParseJsonSafe(accessToken)
if IsAssociativeArray(token) and IsNumber(token.expire) and token.expire <= TimeUtils.Now().AsSeconds()
return ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
end if
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end if
LogError("Unknown profile type when deriving auth state:", profileType)
return ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated
end function
' The unobserve at the end is field-level: it removes every scoped observer the
' calling component holds on refreshCompleted. Hold long-lived observers on authState.
function EnsureFreshAccessToken(profileNode as object) as ProfileContentAuthTokenUtils.AccessTokenResult
messagePort = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(profileNode, "refreshCompleted", messagePort)
result = profileNode@.ResolveAccessToken()
if result.state = ProfileContentAuthTokenUtils.AccessTokenState.Refreshing
wait(30000, messagePort)
result = profileNode@.ResolveAccessToken()
end if
result.profile = profileNode
profileNode.unobserveFieldScoped("refreshCompleted")
return result
end function
end namespace
@@ -0,0 +1,23 @@
namespace ProfileContentAuthTokenUtils
enum ProfileAuthState
Authenticated = "Authenticated"
NeedsReauth = "NeedsReauth"
end enum
enum AccessTokenState
Ok = "Ok"
Refreshing = "Refreshing"
NeedsReauth = "NeedsReauth"
end enum
interface AccessTokenResult
token as string
state as AccessTokenState
serverUrl as string
activeIdentifyToken as string
profile as object
freshUntilSeconds as integer
end interface
end namespace
@@ -1,50 +1,76 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
function HasValidAccessToken(_unused as dynamic) as boolean
serverType = m.top.type
accessToken = m.top.accessToken
if StringUtils.IsNullOrEmpty(accessToken)
return false
' Refresh well before expiry; stop serving a few minutes before expiry so a request
' never carries a token that dies in flight.
const REFRESH_THRESHOLD_SECONDS = 60 * 60
const VALIDITY_THRESHOLD_SECONDS = 60 * 5
' A Refreshing state means a refresh job is in flight; its completion pulses refreshCompleted.
function ResolveAccessToken(_unused as dynamic) as object
result = {
state: ProfileContentAuthTokenUtils.AccessTokenState.Refreshing
token: ""
serverUrl: m.top.serverUrl
activeIdentifyToken: m.top.activeIdentifyToken
freshUntilSeconds: 0
}
if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
return result
end if
if serverType = "invidious"
return true
if m.top.type = "invidious"
' Invidious holds a single long-lived token — nothing to refresh.
result.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
result.token = m.top.accessToken
return result
end if
nowSeconds = TimeUtils.Now().AsSeconds()
expiresTimestamp = m.top.expiresTimestamp
result.freshUntilSeconds = expiresTimestamp - REFRESH_THRESHOLD_SECONDS
' We should refresh the token if it's about to expire in 30 minutes
' Although the current token might be valid, we can let current request
' wait for the new token
shouldRefreshToken = expiresTimestamp < nowSeconds + 60 * 30
if shouldRefreshToken
RefreshAccessToken()
accessToken = m.top.accessToken
' An empty token refreshes regardless of the stored expiry — a Refreshing verdict
' must always have a live job behind it, or a waiter blocks on a pulse that never comes.
if expiresTimestamp < nowSeconds + REFRESH_THRESHOLD_SECONDS or StringUtils.IsNullOrEmpty(accessToken)
StartRefreshJob()
if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
return result
end if
end if
return not shouldRefreshToken
if not StringUtils.IsNullOrEmpty(accessToken) and expiresTimestamp > nowSeconds + VALIDITY_THRESHOLD_SECONDS
result.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
result.token = accessToken
end if
return result
end function
function RefreshAccessToken() as void
if m.profileRefreshTokenJob <> invalid
function StartRefreshJob() as void
if m.profileRefreshTokenJob <> invalid and not m.profileRefreshTokenJob.done
return
end if
if m.scene = invalid
m.scene = m.top.getScene()
end if
if m.profilesService = invalid
m.profilesService = m.scene.findNode("ProfilesService")
end if
if m.jobQueue = invalid
m.jobQueue = m.scene.findNode("JobQueue")
' A YouTube profile holds a refresh token by construction; none means the credential is gone.
if StringUtils.IsNullOrEmpty(m.top.refreshToken)
LogError("Refresh requested for profile without a refresh token")
MarkNeedsReauth(invalid)
return
end if
EnsureSceneRefs()
LogInfo("Refreshing access token for profile:", m.top.username)
input = {
@@ -65,3 +91,46 @@ function OnProfileRefreshTokenJobDone(event as object) as void
JobSystem.UnobserveCallback(event.getRoSGNode())
m.profileRefreshTokenJob = invalid
end function
function MarkNeedsReauth(_unused as dynamic) as void
if m.top.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return
end if
m.top.update({
accessToken: ""
refreshToken: ""
expiresTimestamp: 0
authState: ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
})
' Wake any waiter blocked on a refresh; it re-resolves and sees NeedsReauth.
m.top.refreshCompleted = true
LogError("Profile credential is dead; sign-in required")
EnsureSceneRefs()
if m.profilesService <> invalid
m.profilesService@.SaveUserProfilesToRegistry()
currentProfile = m.profilesService.currentProfile
if currentProfile <> invalid and currentProfile.isSameNode(m.top)
m.profilesService.currentProfileChanged = true
end if
end if
DialogUtils.ShowDialogEx({
title: Tr(Locale.Dialogs.ProfileNeedsReauthTitle)
message: Tr(Locale.Dialogs.ProfileNeedsReauthMessage)
})
end function
function EnsureSceneRefs() as void
if m.scene = invalid
m.scene = m.top.getScene()
end if
if m.profilesService = invalid
m.profilesService = m.scene.findNode("ProfilesService")
end if
if m.jobQueue = invalid
m.jobQueue = m.scene.findNode("JobQueue")
end if
end function
@@ -21,6 +21,13 @@
<field id="color" type="color" />
<function name="HasValidAccessToken" />
<!-- Runtime credential state (ProfileAuthState); derived from the stored
credential at load, mutated only by MarkNeedsReauth and re-login. -->
<field id="authState" type="string" value="Authenticated" />
<field id="refreshCompleted" type="boolean" alwaysNotify="true" />
<function name="ResolveAccessToken" />
<function name="MarkNeedsReauth" />
</interface>
</component>
</component>
@@ -10,16 +10,23 @@ function ExecuteJob() as void
try
cancellation = JobGetCancellation()
if InnertubeService.AuthRefreshAccessToken(accessTokenObject, cancellation)
profileNode.expiresIn = accessTokenObject.expiresIn
profileNode.expiresTimestamp = accessTokenObject.expiresTimestamp
profileNode.accessToken = accessTokenObject.accessToken
profileNode.update({
expiresIn: accessTokenObject.expiresIn
expiresTimestamp: accessTokenObject.expiresTimestamp
accessToken: accessTokenObject.accessToken
})
profilesService@.SaveUserProfilesToRegistry()
else
JobError("Failed to refresh access token")
profileNode.accessToken = invalid
JobError("Refresh response contained no access token")
end if
catch error
' AuthRefreshAccessToken flags a permanently-dead refresh token on the shared object before throwing.
if ValidBool(accessTokenObject.terminalRefreshError)
profileNode@.MarkNeedsReauth()
end if
JobError("Failed to refresh access token: " + ErrorUtils.Format(error))
profileNode.accessToken = invalid
end try
' Signal completion on every outcome so a blocked waiter wakes.
profileNode.refreshCompleted = true
end function
@@ -22,7 +22,7 @@ function OnNodeReady()
m.urlLabel.text = Tr(Locale.Dialogs.IpAddressNotAvailable)
end if
m.invidious.observeFieldScoped("authToken", FuncName(OnAuthTokenChange))
m.profilesService.observeFieldScoped("currentProfileChanged", FuncName(OnCurrentProfileChanged))
end function
function Close()
@@ -36,7 +36,7 @@ function OnUrlSet()
m.qrCode.text = url
end function
function OnAuthTokenChange()
m.invidious.unobserveFieldScoped("authToken")
function OnCurrentProfileChanged()
m.profilesService.unobserveFieldScoped("currentProfileChanged")
Close()
end function
@@ -1,7 +1,7 @@
<component name="InvidiousLoginDialog" extends="StandardDialog" initialFocus="buttonArea" includes="AutoBind">
<interface>
<field id="webServer" type="node" bind="/WebServer" />
<field id="invidious" type="node" bind="/Invidious" />
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="url" type="string" onChange="OnUrlSet" />
<field id="alwaysOnTop" type="boolean" />
</interface>
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/source/utils/DisposableObserve.bs"
import "pkg:/source/utils/FocusManagement.bs"
@@ -10,6 +11,7 @@ function Init()
m.activateButton = m.top.findNode("activateButton")
m.logoutButton = m.top.findNode("logoutButton")
m.closeButton = m.top.findNode("closeButton")
m.reauthLabel = m.top.findNode("ReauthLabel")
DisposableObserveField(m.activateButton, "buttonSelected", FuncName(Activate))
DisposableObserveField(m.logoutButton, "buttonSelected", FuncName(Logout))
@@ -29,6 +31,7 @@ end function
function OnContentSet() as void
content = m.top.content
if content = invalid
m.reauthLabel.visible = false
return
end if
@@ -70,6 +73,8 @@ function OnContentSet() as void
m.top.backendTypePosterUri = ""
end if
UpdateReauthState(content)
UpdateActivateButton()
end function
@@ -140,6 +145,17 @@ function OnDispose()
m.top.content = invalid
end function
function UpdateReauthState(content as object) as void
needsReauth = content.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
if needsReauth
m.reauthLabel.text = [
Tr(Locale.Dialogs.ProfileNeedsReauthMessageLine1)
Tr(Locale.Dialogs.ProfileNeedsReauthMessageLine2)
].Join(Chr(10))
end if
m.reauthLabel.visible = needsReauth
end function
function OnCunrrentProfileChanged() as void
content = m.top.content
if content = invalid
@@ -21,11 +21,11 @@
</Rectangle>
<Rectangle
width="720"
height="420"
translation="[280,150]"
height="440"
translation="[280,140]"
color="#242424">
<Group translation="[100,90]">
<Group translation="[100,100]">
<Poster
id="circlePoster"
width="160"
@@ -85,21 +85,31 @@
anchor="[0.5,0.5]"
text="Activate"
minWidth="200"
translation="[520,132]" />
translation="[520,142]" />
<ButtonEx
id="logoutButton"
iconVisible="false"
anchor="[0.5,0.5]"
text="Logout"
minWidth="200"
translation="[520,210]" />
translation="[520,220]" />
<ButtonEx
id="closeButton"
iconVisible="false"
anchor="[0.5,0.5]"
text="Close"
minWidth="200"
translation="[520,288]" />
translation="[520,298]" />
<Label id="ReauthLabel"
width="640"
horizAlign="center"
wrap="true"
maxLines="2"
translation="[40,382]"
visible="false">
<Font role="font" uri="font:SystemFontFile" size="16" />
</Label>
</Rectangle>
</children>
@@ -7,6 +7,20 @@ import "pkg:/source/utils/TimeUtils.bs"
namespace Innertube
enum RefreshErrorCode
InvalidGrant = "invalid_grant"
InvalidClient = "invalid_client"
UnauthorizedClient = "unauthorized_client"
end enum
function IsTerminalRefreshError(json as object) as boolean
if not IsAssociativeArray(json)
return false
end if
oauthError = ValidString(json.error)
return oauthError = RefreshErrorCode.InvalidGrant or oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient
end function
function GetClientIdentity(cancellation = invalid as dynamic) as object
request = HttpClient.Get("https://www.youtube.com/tv")
request.Headers({
@@ -169,9 +183,26 @@ namespace Innertube
request = HttpClient.PostJson("https://www.youtube.com/o/oauth2/token", payload)
request.Cancellation(cancellation)
request.TryCount(3)
request.RetryCallback(function(context as object) as boolean
return not Innertube.IsTerminalRefreshError(context.response.Json())
end function)
response = request.Await()
if not response.IsSuccess()
json = response.Json()
oauthError = ""
if IsAssociativeArray(json)
oauthError = ValidString(json.error)
end if
if oauthError = RefreshErrorCode.InvalidGrant
' Dead user refresh token: flag the shared object so the job marks the profile.
accessToken.terminalRefreshError = true
else if oauthError = RefreshErrorCode.InvalidClient or oauthError = RefreshErrorCode.UnauthorizedClient
' Fleet-wide app-side rejection. The credentials are scraped public TV-client
' values, safe to log; don't clear the session — re-login uses the same client.
LogError("OAuth client rejected by token endpoint:", response.ErrorMessage(), "client_id:", accessToken.clientId, "client_secret:", accessToken.clientSecret)
end if
throw `Failed to refresh token: ${response.ErrorMessage()}`
end if
@@ -5,7 +5,6 @@
<field id="webServer" type="node" />
<field id="profilesService" type="node" />
<field id="authToken" type="assocarray" />
<field id="apiDefinitions" type="assocarray" />
<function name="GetInstance" />
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/LiveStreamInfo.bs"
@@ -5,7 +6,6 @@ import "pkg:/components/VideoFeed/PaginationType.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CryptoUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/OptionUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
@@ -66,6 +66,16 @@ namespace Invidious
}
end function
function GetCurrentProfile() as object
if m.profilesService = invalid
m.profilesService = m.invidiousNode.profilesService
end if
if m.profilesService = invalid
return invalid
end if
return m.profilesService.currentProfile
end function
function GetInstance() as string
if m.preferences = invalid
m.preferences = m.invidiousNode.preferences
@@ -90,21 +100,17 @@ namespace Invidious
return m.preferences["invidious.instance"]
end function
function MarkVideoWatched(videoId as dynamic, cancellation = invalid as object) as void
if StringUtils.IsNullOrEmpty(videoId)
function MarkVideoWatched(auth as ProfileContentAuthTokenUtils.AccessTokenResult, videoId as dynamic, cancellation = invalid as object) as void
if StringUtils.IsNullOrEmpty(videoId) or auth = invalid or auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
authToken = m.invidiousNode.authToken
if authToken = invalid
return
end if
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
url = `${auth.serverUrl}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
request.Await()
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object
@@ -180,13 +186,18 @@ namespace Invidious
end function
function GetPlaylist(playlistId as string, index = 0 as integer, continuation = "" as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken
if authToken <> invalid
url = `${authToken.instance}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
profile = m.GetCurrentProfile()
auth = invalid
if profile <> invalid
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
end if
isAuthenticatedRequest = auth <> invalid and auth.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
if isAuthenticatedRequest
url = `${auth.serverUrl}${Invidious.AUTH_PLAYLISTS}/${playlistId}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
request.Headers(m.GetAuthenticationHeaders(auth.token))
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
else
instance = m.GetInstance()
@@ -201,7 +212,11 @@ namespace Invidious
end if
request.Cancellation(cancellation)
return request.Await()
response = request.Await()
if isAuthenticatedRequest
m.MarkNeedsReauthOn403(response, auth.profile)
end if
return response
end function
function GetChannel(authorId as string, cancellation = invalid as object) as object
@@ -284,34 +299,24 @@ namespace Invidious
request = HttpClient.Get(instance + endpoint.url)
authToken = invalid
profile = invalid
if endpoint.authenticated = true
authToken = m.invidiousNode.authToken
if authToken = invalid
profile = m.GetCurrentProfile()
auth = invalid
if profile <> invalid
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
end if
if auth = invalid or auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return {
success: false
error: ERROR_NOT_AUTHENTICATED
}
end if
profileNode = authToken.profileNode
' This is not the right place for a token refresh,
' but it needs a refactor to be done properly.
if not profileNode@.HasValidAccessToken()
messagePort = CreateObject("roMessagePort")
MessagePortUtils.ObserveFieldScopedExSafe(profileNode, "accessToken", messagePort)
msg = wait(10000, messagePort)
profileNode.unobserveFieldScoped("accessToken")
if msg <> invalid
authToken.token = profileNode.accessToken
m.invidiousNode.authToken = authToken
end if
end if
request.Url(authToken.instance + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
request.Url(auth.serverUrl + endpoint.url)
request.Headers(m.GetAuthenticationHeaders(auth.token))
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
end if
@@ -372,7 +377,7 @@ namespace Invidious
result = m[responseHandler]({
feedSource: feedSource
response: response
authToken: authToken
profile: profile
})
if response.IsSuccess() and result <> invalid
@@ -606,9 +611,8 @@ namespace Invidious
function AuthFeedHandler(context as object) as object
response = context.response
authToken = context.authToken
m.DeleteExpiredToken(response, authToken)
m.MarkNeedsReauthOn403(response, context.profile)
if not response.IsSuccess()
return invalid
@@ -642,9 +646,8 @@ namespace Invidious
function WatchHistoryHandler(context as object) as object
response = context.response
authToken = context.authToken
m.DeleteExpiredToken(response, authToken)
m.MarkNeedsReauthOn403(response, context.profile)
if not response.IsSuccess()
return invalid
@@ -696,19 +699,16 @@ namespace Invidious
return json
end function
function DeleteExpiredToken(response as object, authToken as object) as void
' A 403 on an authenticated call is terminal — only a fresh sign-in recovers.
function MarkNeedsReauthOn403(response as object, profile as object) as void
if response.StatusCode() <> 403
return
end if
LogWarn(`Invidious instance responded with 403: ${response.Text()}`)
if not IsAssociativeArray(authToken) or not IsString(authToken.token)
LogWarn("No valid token to delete")
return
if profile <> invalid and profile.type = "invidious"
profile@.MarkNeedsReauth()
end if
LogInfo("Deleting Invidious token...")
m.invidiousNode.profilesService@.LogoutWithAccessToken(authToken.token)
end function
function VerifyTokenScope(token as string) as boolean
@@ -732,11 +732,11 @@ namespace Invidious
return validScopes
end function
function UnregisterToken(authToken as object) as object
url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
function UnregisterToken(instance as string, token as string) as object
url = `${instance}${Invidious.AUTH_TOKENS_UNREGISTER}`
request = HttpClient.Post(url, authToken.token)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request = HttpClient.Post(url, token)
request.Headers(m.GetAuthenticationHeaders(token))
request.Header("Content-Type", "application/json")
return request.Await()
@@ -763,52 +763,43 @@ namespace Invidious
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetSubscriptions(cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}`
function GetSubscriptions(auth as ProfileContentAuthTokenUtils.AccessTokenResult, cancellation = invalid as object) as object
url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
return request.Await()
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function
function Subscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
function Subscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object
url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "")
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
return request.Await()
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function
function Unsubscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.invidiousNode.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
function Unsubscribe(auth as ProfileContentAuthTokenUtils.AccessTokenResult, channelId as string, cancellation = invalid as object) as object
url = `${auth.serverUrl}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url)
if not StringUtils.IsNullOrEmpty(authToken.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", authToken.activeIdentifyToken)
if not StringUtils.IsNullOrEmpty(auth.activeIdentifyToken)
request.QueryParam("activeIdentifyToken", auth.activeIdentifyToken)
end if
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Headers(m.GetAuthenticationHeaders(auth.token))
request.Cancellation(cancellation)
return request.Await()
response = request.Await()
m.MarkNeedsReauthOn403(response, auth.profile)
return response
end function
end class
@@ -16,11 +16,7 @@ function ExecuteJob() as void
token = profileNode.accessToken
end if
authToken = {
instance: profileNode.serverUrl
token: token
}
response = service.UnregisterToken(authToken)
response = service.UnregisterToken(profileNode.serverUrl, token)
if not response.IsSuccess()
LogWarn(`Failed to unregister token: ${response.ErrorMessage()}`)
end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs"
import "pkg:/source/utils/ArrayUtils.bs"
@@ -68,6 +69,8 @@ function LoadProfilesFromRegistry()
profileNode.color = profile.color
profileNode.authState = ProfileContentAuthTokenUtils.DeriveAuthState(ValidString(profile.type), profile.accessToken, profile.refreshToken)
profileNodes.Push(profileNode)
end for
@@ -88,7 +91,6 @@ function LoadProfilesFromRegistry()
if profileNodes.Count() > 0
input = {
profilesService: m.top
invidious: m.invidious
profileNodes: profileNodes
}
@@ -231,6 +233,10 @@ function LoginWithProfile(newProfile as object)
newProfile.color = ColorUtils.RandomSoftColorHex()
m.profilesContent.insertChild(newProfile, 0)
end if
' The id-merge above reuses the existing node, which may carry NeedsReauth — re-derive.
newProfile.authState = ProfileContentAuthTokenUtils.DeriveAuthState(newProfile.type, newProfile.accessToken, newProfile.refreshToken)
SetCurrentProfile(newProfile)
end function
@@ -301,38 +307,11 @@ function LogoutWithProfiles(profiles as object) as void
JobSystem.QueueJob(m.jobQueue, Jobs.ProfilesInvidiousUnregisterTokenJob, input)
end function
function LogoutWithAccessToken(accessToken as dynamic) as void
if StringUtils.IsNullOrEmpty(accessToken)
return
end if
' We are not going to invalidate the token on the server
' because we are likely dealing with an invalid token
' in the first place. All we need to do is remove the
' profile from the list of profiles.
allProfiles = m.profilesContent.getChildren(-1, 0)
for each profile in allProfiles
if profile.accessToken = accessToken
m.profilesContent.removeChild(profile)
currentProfile = m.top.currentProfile
if currentProfile <> invalid and currentProfile.id = profile.id
SetCurrentProfile(invalid)
else
RefreshActiveProfileState(currentProfile)
SaveUserProfilesToRegistry(invalid)
end if
m.top.onProfileLogout = true
exit for
end if
end for
end function
function SetCurrentProfile(newActiveProfile as object) as void
if newActiveProfile = invalid
RefreshActiveProfileState(invalid)
m.top.currentProfile = invalid
m.invidious.authToken = invalid
m.top.currentProfileChanged = true
LogInfo("Current profile set to <invalid>")
SaveUserProfilesToRegistry(invalid)
return
@@ -341,13 +320,7 @@ function SetCurrentProfile(newActiveProfile as object) as void
RefreshActiveProfileState(newActiveProfile)
m.top.currentProfile = newActiveProfile
m.invidious.authToken = {
token: newActiveProfile.accessToken
instance: newActiveProfile.serverUrl
username: newActiveProfile.username
activeIdentifyToken: newActiveProfile.activeIdentifyToken
profileNode: newActiveProfile
}
m.top.currentProfileChanged = true
LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl)
SaveUserProfilesToRegistry(invalid)
end function
@@ -7,6 +7,7 @@
-->
<field id="__version" type="integer" value="1" />
<field id="currentProfile" type="node" />
<field id="currentProfileChanged" type="boolean" alwaysNotify="true" />
<field id="onProfileLogout" type="boolean" alwaysNotify="true" />
<field id="content" type="node" />
@@ -17,7 +18,6 @@
<function name="LoginWithProfile" />
<function name="LogoutWithProfile" />
<function name="LogoutWithProfiles" />
<function name="LogoutWithAccessToken" />
<function name="SetCurrentProfile" />
<function name="SaveUserProfilesToRegistry" />
</interface>
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/StringUtils.bs"
@@ -5,37 +6,21 @@ import "pkg:/source/utils/StringUtils.bs"
function ExecuteJob() as void
input = JobGetInput()
profilesNode = input.profilesService
invidiousNode = input.invidious
profileContentNodes = input.profileNodes
service = new Invidious.InvidiousService(invidiousNode)
invalidProfiles = []
for each profileNode in profileContentNodes
if not StringUtils.IsNullOrEmpty(profileNode.refreshToken)
if profileNode.type <> "invidious"
continue for
end if
if profileNode.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
continue for
end if
if not service.VerifyTokenScope(profileNode.accessToken)
invalidProfiles.push(profileNode)
' The stored token can't make authenticated calls anymore (e.g. scopes changed in an update).
profileNode@.MarkNeedsReauth()
end if
end for
if invalidProfiles.Count() = 0
return
end if
profilesNode@.LogoutWithProfiles(invalidProfiles)
profileNames = []
for each profileNode in invalidProfiles
profileNames.push(profileNode.username)
end for
profileNames = profileNames.join(", ")
message = Tr(Locale.Dialogs.UserLoggedOutMessage).Replace("\n", `\n`).Replace("%1", profileNames)
DialogUtils.ShowDialogEx({
message: message
title: Tr(Locale.Dialogs.UserLoggedOut)
})
end function
@@ -26,7 +26,7 @@ function OnNodeReady()
DisposableObserveField(m.top, "visible", FuncName(OnVisibilityChange))
' TODO:P1 Reload when subscriptions change
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(OnAuthTokenChange))
DisposableObserveFieldScoped(m.profilesService, "currentProfileChanged", FuncName(OnCurrentProfileChanged))
InitializeLongPress(["OK"])
end function
@@ -206,7 +206,7 @@ function Refresh(_unused as dynamic)
InitContent()
end function
function OnAuthTokenChange()
function OnCurrentProfileChanged()
' TODO:P2: Reload only content that is authenticated
' Should not reload if the page is not visible. Instead, capture state and reload when the page becomes visible
InitContent()
@@ -2,6 +2,7 @@
<interface>
<field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" />
<field id="profilesService" type="node" bind="/ProfilesService" />
<field id="videoQueue" type="node" bind="/VideoQueue" />
<field id="bookmarksService" type="node" bind="/BookmarksService" />
<field id="jobQueue" type="node" bind="/JobQueue" />
@@ -1,6 +1,8 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
@job("MarkVideoWatchedJob")
function ExecuteJob() as void
@@ -8,28 +10,37 @@ function ExecuteJob() as void
videoId = input.videoId
invidiousNode = input.invidious
authToken = input.authToken
profileType = input.profileType
profile = input.profile
playbackTrackingUrls = input.playbackTrackingUrls
cpn = input.cpn
cancellation = JobGetCancellation()
if profileType = "invidious"
service = new Invidious.InvidiousService(invidiousNode)
service.MarkVideoWatched(videoId, cancellation)
return
end if
if profileType <> "youtube"
profileType = profile.type
if profileType <> "invidious" and profileType <> "youtube"
JobError(`Unsupported profile type: ${profileType}`)
return
end if
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
if profileType = "invidious"
service = new Invidious.InvidiousService(invidiousNode)
service.MarkVideoWatched(auth, videoId, cancellation)
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
if playbackTrackingUrls = invalid or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsPlaybackUrl) or StringUtils.IsNullOrEmpty(playbackTrackingUrls.videostatsWatchtimeUrl)
playbackTrackingUrls = InnertubeService.AuthGetPlaybackTrackingUrls(videoId, {
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
accessToken: accessToken
onBehalfOfUser: onBehalfOfUser
cancellation: cancellation
})
end if
@@ -49,8 +60,8 @@ function ExecuteJob() as void
end if
markedAsWatched = InnertubeService.AuthMarkVideoWatched(playbackTrackingUrls.videostatsPlaybackUrl, {
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
accessToken: accessToken
onBehalfOfUser: onBehalfOfUser
cpn: cpn
cancellation: cancellation
})
@@ -72,33 +83,73 @@ function ExecuteJob() as void
port = CreateObject("roMessagePort")
callbackNode = JobGetCallbackNode()
MessagePortUtils.ObserveFieldScopedExSafe(callbackNode, "watchTime", port)
' authState, not refreshCompleted: EnsureFreshAccessToken below unobserves
' refreshCompleted component-wide, which would remove this observer with it.
MessagePortUtils.ObserveFieldScopedExSafe(profile, "authState", port)
CancellationUtils.ObserveCancellationScoped(cancellation, port)
successiveFailures = 0
while true
message = wait(60000, port)
message = wait(WatchTimeAuthWaitMs(freshUntilSeconds, refreshRequested), port)
if CancellationUtils.IsCancellationEvent(cancellation, message)
JobCancel()
return
end if
if message = invalid
if refreshRequested or WatchTimeAuthRefreshDue(freshUntilSeconds)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if
continue while
end if
' Drain the port to get the latest watch time
watchTime = invalid
if IsWatchTimeEvent(callbackNode, message)
watchTime = message.getData()
else if IsAuthStateEvent(profile, message)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if
' Drain the port to get the latest watch time and any credential transition.
newMessage = port.GetMessage()
while newMessage <> invalid
if CancellationUtils.IsCancellationEvent(cancellation, newMessage)
JobCancel()
return
else if IsWatchTimeEvent(callbackNode, newMessage)
watchTime = newMessage.getData()
else if IsAuthStateEvent(profile, newMessage)
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state <> ProfileContentAuthTokenUtils.AccessTokenState.Ok
return
end if
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
freshUntilSeconds = auth.freshUntilSeconds
refreshRequested = WatchTimeAuthRefreshDue(freshUntilSeconds)
end if
message = newMessage
newMessage = port.GetMessage()
end while
watchTime = message.getData()
if watchTime = invalid
continue while
end if
success = InnertubeService.AuthMarkVideoWatchTime(watchTime, playbackTrackingUrls.videostatsWatchtimeUrl, {
accessToken: authToken.token
onBehalfOfUser: authToken.activeIdentifyToken
accessToken: accessToken
onBehalfOfUser: onBehalfOfUser
cpn: cpn
' TODO:P1 if we pass cancellation here, http client will remove scoped
' observer, which is stored on the current node.
@@ -117,3 +168,41 @@ function ExecuteJob() as void
end if
end while
end function
function WatchTimeAuthRefreshDue(freshUntilSeconds as dynamic) as boolean
if not IsNumber(freshUntilSeconds) or freshUntilSeconds <= 0
return false
end if
return TimeUtils.Now().AsSeconds() >= freshUntilSeconds
end function
function WatchTimeAuthWaitMs(freshUntilSeconds as dynamic, refreshRequested as boolean) as integer
if refreshRequested or not IsNumber(freshUntilSeconds) or freshUntilSeconds <= 0
return 60000
end if
secondsUntilRefresh = freshUntilSeconds - TimeUtils.Now().AsSeconds()
if secondsUntilRefresh <= 0
return 1
end if
if secondsUntilRefresh > 60
return 60000
end if
return secondsUntilRefresh * 1000
end function
function IsWatchTimeEvent(callbackNode as object, message as dynamic) as boolean
if type(message) <> "roSGNodeEvent"
return false
end if
node = message.getRoSGNode()
return node <> invalid and node.isSameNode(callbackNode) and message.getField() = "watchTime"
end function
function IsAuthStateEvent(profile as object, message as dynamic) as boolean
if type(message) <> "roSGNodeEvent"
return false
end if
node = message.getRoSGNode()
return node <> invalid and node.isSameNode(profile) and message.getField() = "authState"
end function
@@ -1,6 +1,8 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Locale.bs"
import "pkg:/source/utils/MessagePortUtils.bs"
@job("VideoContentJob")
@@ -49,11 +51,18 @@ function ExecuteJob() as void
accessToken = invalid
onBehalfOfUser = invalid
profileNode = invalid
authToken = invidiousNode.authToken
if authToken <> invalid and authToken.profileNode <> invalid and authToken.profileNode.type = "youtube" and not StringUtils.IsNullOrEmpty(authToken.token)
accessToken = authToken.token
onBehalfOfUser = authToken.activeIdentifyToken
profileNode = authToken.profileNode
profile = profilesService.currentProfile
if profile <> invalid and profile.type = "youtube"
auth = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(profile)
if auth.state = ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth
JobError(Locale.Dialogs.ProfileNeedsReauthMessage)
return
end if
if auth.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
accessToken = auth.token
onBehalfOfUser = auth.activeIdentifyToken
profileNode = profile
end if
end if
metadata = InnertubeService.GetVideoMetadata(contentNode.videoId, {
@@ -1,5 +1,6 @@
#const DEBUG_LOG_VIDEO_QUALITY = false
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs"
@@ -359,9 +360,11 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
return
end if
invidious = m.top.invidious
authToken = invidious.authToken
if authToken = invalid
profile = m.top.profilesService.currentProfile
if profile = invalid
return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return
end if
@@ -369,13 +372,10 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
m.markVideoWatchedJob.cancel = true
end if
profileType = authToken.profileNode.type
input = {
videoId: videoId
invidious: invidious
authToken: authToken
profileType: profileType
invidious: m.top.invidious
profile: profile
playbackTrackingUrls: playbackTrackingUrls
cpn: cpn
}
@@ -384,7 +384,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
m.markVideoWatchedJob.addField("watchTime", "float", false)
JobSystem.QueueJob(m.jobQueue, Jobs.MarkVideoWatchedJob, input, m.markVideoWatchedJob)
if profileType <> "youtube"
if profile.type <> "youtube"
return
end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/JobSystem/Jobs.bs"
import "pkg:/components/JobSystem/JobSystem.bs"
@@ -1235,20 +1236,20 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
if StringUtils.IsNullOrEmpty(videoId)
return
end if
invidious = m.top.invidious
authToken = invidious.authToken
if authToken = invalid
profile = m.top.profilesService.currentProfile
if profile = invalid
return
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
return
end if
if m.markVideoWatchedJob <> invalid
m.markVideoWatchedJob.cancel = true
end if
profileType = authToken.profileNode.type
input = {
videoId: videoId
invidious: invidious
authToken: authToken
profileType: profileType
invidious: m.top.invidious
profile: profile
playbackTrackingUrls: playbackTrackingUrls
cpn: cpn
}
@@ -1258,7 +1259,7 @@ function MarkVideoWatched(videoId as dynamic, playbackTrackingUrls as dynamic, c
' only YouTube profiles take the periodic watch-time updates.
m.watchTimeMarker = -1
m.reportWatchTime = (profileType = "youtube")
m.reportWatchTime = (profile.type = "youtube")
end function
function SeekToInitialPosition(content as object) as void
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/PoTokens.bs"
@@ -160,8 +161,12 @@ namespace Http
}
currentProfile = m.profilesService.currentProfile
tokenResult = invalid
if currentProfile <> invalid and currentProfile.type = "youtube"
options["accessToken"] = currentProfile.accessToken
tokenResult = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(currentProfile)
end if
if tokenResult <> invalid and tokenResult.state = ProfileContentAuthTokenUtils.AccessTokenState.Ok
options["accessToken"] = tokenResult.token
else
options["visitorData"] = m.innertube.sessionData.visitorData
end if
@@ -1,3 +1,4 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.types.bs"
import "pkg:/components/Services/Invidious/InvidiousService.bs"
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
import "pkg:/source/utils/CryptoUtils.bs"
@@ -54,9 +55,13 @@ namespace Http
request = context.request
response = context.response
token = m.invidiousNode.authToken
if token = invalid
response.Default(403, "No token, not logged in")
profile = m.invidiousService.GetCurrentProfile()
if profile = invalid
response.Default(403, "Not logged in")
return true
end if
if profile.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
response.Default(403, "Session expired. Please sign in again.")
return true
end if
@@ -64,10 +64,6 @@
<source>Failed to load channel %1</source>
<translation>Der Kanal %1 konnte nicht geladen werden</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Es sieht so aus, als hätten Sie sich bei Invidious angemeldet, ohne jedoch die erforderlichen Berechtigungen zu besitzen.\nAus diesem Grund wurden Sie aus Folgenden Profilen ausgeloggt: %1\nBitte loggen Sie sich wieder ein.\nDies kann Folge eines Updates von Playlet sein.\nWir entschuldigen uns für entstandene Unannehmlichkeiten.</translation>
</message>
<message>
<source>Premieres in 1 minute</source>
<translation>Premiere in 1 Minute</translation>
@@ -428,10 +424,6 @@
<source>Failed to load feed</source>
<translation>Feed konnte nicht geladen werden</translation>
</message>
<message>
<source>User logged out</source>
<translation>Benutzer ausgellogt</translation>
</message>
<message>
<source>Failed to get screen ID. Please restart Playlet to use the cast function.</source>
<translation>Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können.</translation>
+12 -4
View File
@@ -225,12 +225,20 @@
<translation>Failed to load feed</translation>
</message>
<message>
<source>User logged out</source>
<translation>User logged out</translation>
<source>Session expired</source>
<translation>Session expired</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</translation>
<source>The session has expired. Please sign in again with this profile, or switch to another profile.</source>
<translation>The session has expired. Please sign in again with this profile, or switch to another profile.</translation>
</message>
<message>
<source>The session has expired.</source>
<translation>The session has expired.</translation>
</message>
<message>
<source>Please sign in again with this profile, or switch to another profile.</source>
<translation>Please sign in again with this profile, or switch to another profile.</translation>
</message>
<message>
<source>Lounge service setup error</source>
@@ -208,10 +208,6 @@
<source>Failed to load feed</source>
<translation>Fallo al cargar el feed</translation>
</message>
<message>
<source>User logged out</source>
<translation>Usuario desconectado</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Error de configuración del servicio Lounge</translation>
@@ -360,10 +356,6 @@
<source>Invalid JSON from %1 (couldn&apos;t read %2)</source>
<translation>JSON no válido para %1 (no se pudo leer %2)</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que has iniciado sesión en Invidious, pero no tienes los permisos necesarios.\nPor este motivo, hemos cerrado tu sesión en los siguientes perfiles: %1\nPor favor, inicia sesión de nuevo.\nEsto puede suceder cuando Playlet se actualiza con nuevas características.\nDisculpa las molestias.</translation>
</message>
<message>
<source>Refresh</source>
<translation>Recargar</translation>
@@ -828,10 +828,6 @@
<source>Playlist load error</source>
<translation>Error al cargar la playlist</translation>
</message>
<message>
<source>User logged out</source>
<translation>Usuario cerró sesión</translation>
</message>
<message>
<source>Failed to load playlist %1</source>
<translation>Error al cargar la playlist %1</translation>
@@ -924,10 +920,6 @@
<source>Tap &apos;Link with TV code&apos; and enter the code below.</source>
<translation>Presiona &quot;Vincular con código de TV&quot;, y luego, ingresa el código que se muestra abajo.</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que has iniciado sesión en Invidious, pero no tienes los permisos necesarios.\nPor esta razón, hemos cerrado tu sesión en los siguientes perfiles: %1\nPor favor, accede de nuevo.\nEsto puede pasar cuando Playlet es actualizado con nuevas características.\nLo sentimos por la inconveniencia.</translation>
</message>
<message>
<source>Tap the cast icon and select %1</source>
<translation>Presiona el ícono de transmisión y selecciona %1</translation>
@@ -208,14 +208,6 @@
<source>Failed to load feed</source>
<translation>Échec du chargement du flux</translation>
</message>
<message>
<source>User logged out</source>
<translation>Utilisateur déconnecté</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Il semble que vous soyez connecté à Invidious, mais n&apos;avez pas les permissions requises.\nPour cette raison, nous vous avons déconnecté des profils suivants : %1\nVeuillez vous reconnecter.\nCela peut se produire lorsque Playlet est mis à jour avec de nouvelles fonctionnalités.\nNous nous excusons pour la gêne occasionnée.</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Erreur de configuration du service Lounge</translation>
@@ -216,14 +216,6 @@
<source>Failed to load feed</source>
<translation>Erro ao carregar o feed</translation>
</message>
<message>
<source>User logged out</source>
<translation>Usuário desconectado</translation>
</message>
<message>
<source>It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience.</source>
<translation>Parece que você está logado no Invidious, mas não tem as permissões necessárias.\nPor esse motivo, nós o desconectamos dos seguintes perfis: %1\nPor favor, faça login novamente.\nIsso pode acontecer quando o Playlet é atualizado com novos recursos.\nPedimos desculpas pelo inconveniente.</translation>
</message>
<message>
<source>Lounge service setup error</source>
<translation>Erro ao configurar o serviço de lounge</translation>
@@ -0,0 +1,51 @@
import "pkg:/components/Services/Innertube/InnertubeService.bs"
import "pkg:/components/Services/Innertube/OAuth.bs"
import "pkg:/source/utils/StringUtils.bs"
namespace Tests
@tags("integration")
@suite
class InnertubeRefreshTokenIntegrationTests extends Rooibos.BaseTestSuite
protected override function setup()
m.logger = CreateObject("roSGNode", "Logger")
m.logger.logLevel = -1
' A failed refresh goes through HttpClient's retry loop, which emits a
' telemetry warning; give the stub a no-op telemetry sink to write to.
telemetry = CreateObject("roSGNode", "Node")
telemetry.addField("LogWarn", "string", false)
telemetry.addField("LogEvent", "assocarray", false)
m.global.addFields({ telemetry: telemetry })
end function
@describe("Innertube refresh-token terminal classification (live)")
@slow(20000)
@it("A dead refresh token throws an error classified terminal (so it is cleared + re-auth, not retry-stormed)")
function _()
' A real client_id/secret with an invalid refresh token gets a real invalid_grant from Google.
identity = Innertube.GetClientIdentity(invalid)
m.assertFalse(IsAssociativeArray(identity) and identity.DoesExist("error"), "GetClientIdentity failed: " + FormatJson(identity))
m.assertFalse(StringUtils.IsNullOrEmpty(identity.clientId), "no client id scraped")
accessTokenObject = {
clientId: identity.clientId
clientSecret: identity.clientSecret
refreshToken: "invalid-refresh-token"
}
threw = false
try
InnertubeService.AuthRefreshAccessToken(accessTokenObject, invalid)
catch error
threw = true
end try
m.assertTrue(threw, "a dead refresh token must surface as a thrown error")
m.assertTrue(ValidBool(accessTokenObject.terminalRefreshError), "a dead refresh token must flag terminalRefreshError on the shared accessToken object")
end function
end class
end namespace
@@ -0,0 +1,27 @@
import "pkg:/components/Services/Innertube/OAuth.bs"
namespace Tests
@suite
class InnertubeOAuthTerminalErrorTests extends Rooibos.BaseTestSuite
@describe("Innertube.IsTerminalRefreshError")
@it("Returns true for terminal OAuth error codes (RFC 6749 §5.2)")
function _()
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "invalid_grant" }))
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "invalid_client" }))
m.assertTrue(Innertube.IsTerminalRefreshError({ error: "unauthorized_client" }))
end function
@it("Returns false for transient, successful, or non-object bodies")
function _()
m.assertFalse(Innertube.IsTerminalRefreshError({ error: "authorization_pending" }))
m.assertFalse(Innertube.IsTerminalRefreshError({ access_token: "ya29.abc" }))
m.assertFalse(Innertube.IsTerminalRefreshError({}))
m.assertFalse(Innertube.IsTerminalRefreshError(invalid))
end function
end class
end namespace
@@ -0,0 +1,135 @@
import "pkg:/components/ContentNode/ProfileContentAuthTokenUtils.bs"
namespace Tests
@SGNode("Group")
@suite
class ProfileContentAuthTokenUtilsTests extends Rooibos.BaseTestSuite
@describe("ProfileContentAuthTokenUtils.DeriveAuthState")
@it("A YouTube profile with a refresh token is Authenticated, even with a stale access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("youtube", "", "rt"), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
end function
@it("A YouTube profile without a refresh token is NeedsReauth, even with an access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("youtube", "stale", ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious profile derives from its access token")
function _()
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", "token", ""), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", "", ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious token past its embedded expire is NeedsReauth")
function _()
nowSeconds = CreateObject("roDateTime").AsSeconds()
expired = FormatJson({ session: "v1:abc", expire: nowSeconds - 60, scopes: ["GET:subscriptions"], signature: "sig" })
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", expired, ""), ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@it("An Invidious token with a future expire is Authenticated")
function _()
nowSeconds = CreateObject("roDateTime").AsSeconds()
live = FormatJson({ session: "v1:abc", expire: nowSeconds + 3600, scopes: ["GET:subscriptions"], signature: "sig" })
m.assertEqual(ProfileContentAuthTokenUtils.DeriveAuthState("invidious", live, ""), ProfileContentAuthTokenUtils.ProfileAuthState.Authenticated)
end function
@describe("ProfileContentAuthTokenUtils.EnsureFreshAccessToken")
@it("Reports NeedsReauth for a NeedsReauth YouTube profile without starting a refresh")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(result.token, "")
end function
@it("Reports NeedsReauth for a NeedsReauth Invidious profile")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.authState = ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(result.token, "")
end function
@it("Returns the token of an authenticated Invidious profile")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.accessToken = "inv-token"
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.Ok)
m.assertEqual(result.token, "inv-token")
end function
@it("Carries the request context so consumers need no further profile reads")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "invidious"
node.accessToken = "inv-token"
node.serverUrl = "https://instance.example"
node.activeIdentifyToken = "delegation-token"
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.serverUrl, "https://instance.example")
m.assertEqual(result.activeIdentifyToken, "delegation-token")
m.assertTrue(result.profile.isSameNode(node))
end function
@it("Returns a still-valid YouTube token without refreshing")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.accessToken = "fresh-token"
node.refreshToken = "rt"
expiresTimestamp = CreateObject("roDateTime").AsSeconds() + 7200
node.expiresTimestamp = expiresTimestamp
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.Ok)
m.assertEqual(result.token, "fresh-token")
m.assertTrue(result.freshUntilSeconds = expiresTimestamp - 3600)
end function
@it("An empty access token with a live-looking expiry resolves immediately instead of waiting on a refresh that was never started")
function _()
' No current code writes this state; the registry is a shared boundary (other
' builds, tooling), and no stored state may park a waiter on a dead 30s wait.
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.accessToken = ""
node.refreshToken = ""
node.expiresTimestamp = CreateObject("roDateTime").AsSeconds() + 7200
result = ProfileContentAuthTokenUtils.EnsureFreshAccessToken(node)
m.assertEqual(result.state, ProfileContentAuthTokenUtils.AccessTokenState.NeedsReauth)
m.assertEqual(node.authState, ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
@describe("ProfileContentNode.MarkNeedsReauth")
@it("Clears the credential and marks the profile in one transition")
function _()
node = CreateObject("roSGNode", "ProfileContentNode")
node.type = "youtube"
node.username = "dying"
node.accessToken = "tok"
node.refreshToken = "rt"
node.expiresTimestamp = 12345
node@.MarkNeedsReauth()
m.assertEqual(node.accessToken, "")
m.assertEqual(node.refreshToken, "")
m.assertEqual(node.expiresTimestamp, 0&)
m.assertEqual(node.authState, ProfileContentAuthTokenUtils.ProfileAuthState.NeedsReauth)
end function
end class
end namespace
+4 -2
View File
@@ -76,8 +76,10 @@ namespace Locale
InvidiousPublicInstancesLoadError = "Invidious public instances load error"
FailedToLoadInvidiousPublicInstances = "Failed to load Invidious public instances"
FailedToLoadFeed = "Failed to load feed"
UserLoggedOut = "User logged out"
UserLoggedOutMessage = "It looks like you are logged in to Invidious, but do not have the required permissions.\nFor that reason, we have logged you out from the following profiles: %1\nPlease log in again.\nThis can happen when Playlet is updated with new features.\nWe apologize for the inconvenience."
ProfileNeedsReauthTitle = "Session expired"
ProfileNeedsReauthMessage = "The session has expired. Please sign in again with this profile, or switch to another profile."
ProfileNeedsReauthMessageLine1 = "The session has expired."
ProfileNeedsReauthMessageLine2 = "Please sign in again with this profile, or switch to another profile."
LoungeServiceSetupError = "Lounge service setup error"
LoungeFailedToGetScreenId = "Failed to get screen ID. Please restart Playlet to use the cast function."
LoungeNotAValidScreenId = "Not a valid screen id: %1"