From 6cb5bfe985bf987f056f6360585f2ed9894e3819 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Fri, 3 Jul 2026 21:34:35 -0400 Subject: [PATCH] oauth refactor --- CHANGELOG.md | 4 +- config/bsconfig.tests.base.jsonc | 1 + .../src/components/ChannelView/ChannelView.bs | 25 ++- .../components/ChannelView/ChannelView.xml | 1 + .../ChannelView/FetchSubscriptionStatusJob.bs | 19 +- .../components/ChannelView/SubscribeJob.bs | 13 +- .../ProfileContentAuthTokenUtils.bs | 46 +++++ .../ProfileContentAuthTokenUtils.types.bs | 23 +++ .../ContentNode/ProfileContentNode.bs | 119 ++++++++++--- .../ContentNode/ProfileContentNode.xml | 11 +- .../ContentNode/ProfileRefreshTokenJob.bs | 19 +- .../components/Dialog/InvidiousLoginDialog.bs | 6 +- .../Dialog/InvidiousLoginDialog.xml | 2 +- .../ProfileScreen/ProfileView/ProfileView.bs | 16 ++ .../ProfileScreen/ProfileView/ProfileView.xml | 22 ++- .../components/Services/Innertube/OAuth.bs | 31 ++++ .../Services/Invidious/Invidious.xml | 1 - .../Services/Invidious/InvidiousService.bs | 163 +++++++++--------- .../ProfilesInvidiousUnregisterTokenJob.bs | 6 +- .../ProfilesService/ProfilesService.bs | 45 +---- .../ProfilesService/ProfilesService.xml | 2 +- .../ProfilesVerifyTokensJob.bs | 29 +--- .../src/components/VideoFeed/VideoRowList.bs | 4 +- .../src/components/VideoFeed/VideoRowList.xml | 1 + .../VideoPlayer/MarkVideoWatchedJob.bs | 127 ++++++++++++-- .../components/VideoPlayer/VideoContentJob.bs | 19 +- .../src/components/VideoPlayer/VideoPlayer.bs | 18 +- .../VideoPlayerDev/VideoPlayerDev.bs | 17 +- .../Middleware/InnertubeRouter.bs | 7 +- .../Middleware/InvidiousRouter.bs | 11 +- playlet-lib/src/locale/de_DE/translations.ts | 8 - playlet-lib/src/locale/en_US/translations.ts | 16 +- playlet-lib/src/locale/es_ES/translations.ts | 8 - playlet-lib/src/locale/es_MX/translations.ts | 8 - playlet-lib/src/locale/fr_CA/translations.ts | 8 - playlet-lib/src/locale/pt_BR/translations.ts | 8 - .../InnertubeRefreshTokenIntegration.spec.bs | 51 ++++++ .../src/source/components/tests/OAuth.spec.bs | 27 +++ .../ProfileContentAuthTokenUtils.spec.bs | 135 +++++++++++++++ playlet-lib/src/source/utils/Locale.bs | 6 +- 40 files changed, 782 insertions(+), 301 deletions(-) create mode 100644 playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.bs create mode 100644 playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.types.bs create mode 100644 playlet-lib/src/source/components/tests/InnertubeRefreshTokenIntegration.spec.bs create mode 100644 playlet-lib/src/source/components/tests/OAuth.spec.bs create mode 100644 playlet-lib/src/source/components/tests/ProfileContentAuthTokenUtils.spec.bs diff --git a/CHANGELOG.md b/CHANGELOG.md index d4fb5688..abecf93c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/config/bsconfig.tests.base.jsonc b/config/bsconfig.tests.base.jsonc index ef4c5a51..4912d0f8 100644 --- a/config/bsconfig.tests.base.jsonc +++ b/config/bsconfig.tests.base.jsonc @@ -34,6 +34,7 @@ ], "rooibos": { "logLevel": 2, + "tags": ["!integration"], "isRecordingCodeCoverage": false, "printTestTimes": true, "showOnlyFailures": true, diff --git a/playlet-lib/src/components/ChannelView/ChannelView.bs b/playlet-lib/src/components/ChannelView/ChannelView.bs index c7ea5a3f..b6f1af5d 100644 --- a/playlet-lib/src/components/ChannelView/ChannelView.bs +++ b/playlet-lib/src/components/ChannelView/ChannelView.bs @@ -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 } diff --git a/playlet-lib/src/components/ChannelView/ChannelView.xml b/playlet-lib/src/components/ChannelView/ChannelView.xml index e0da0239..2b1eec46 100644 --- a/playlet-lib/src/components/ChannelView/ChannelView.xml +++ b/playlet-lib/src/components/ChannelView/ChannelView.xml @@ -5,6 +5,7 @@ + diff --git a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs index fe0d21ef..399dc0d3 100644 --- a/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs +++ b/playlet-lib/src/components/ChannelView/FetchSubscriptionStatusJob.bs @@ -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 diff --git a/playlet-lib/src/components/ChannelView/SubscribeJob.bs b/playlet-lib/src/components/ChannelView/SubscribeJob.bs index 3bacc82b..062032e9 100644 --- a/playlet-lib/src/components/ChannelView/SubscribeJob.bs +++ b/playlet-lib/src/components/ChannelView/SubscribeJob.bs @@ -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() diff --git a/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.bs b/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.bs new file mode 100644 index 00000000..5eed64e5 --- /dev/null +++ b/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.bs @@ -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 diff --git a/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.types.bs b/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.types.bs new file mode 100644 index 00000000..8fe658f5 --- /dev/null +++ b/playlet-lib/src/components/ContentNode/ProfileContentAuthTokenUtils.types.bs @@ -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 diff --git a/playlet-lib/src/components/ContentNode/ProfileContentNode.bs b/playlet-lib/src/components/ContentNode/ProfileContentNode.bs index 92691dee..c35d608f 100644 --- a/playlet-lib/src/components/ContentNode/ProfileContentNode.bs +++ b/playlet-lib/src/components/ContentNode/ProfileContentNode.bs @@ -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 diff --git a/playlet-lib/src/components/ContentNode/ProfileContentNode.xml b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml index 28494b6f..fe1097a4 100644 --- a/playlet-lib/src/components/ContentNode/ProfileContentNode.xml +++ b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml @@ -21,6 +21,13 @@ - + + + + + + + - \ No newline at end of file + diff --git a/playlet-lib/src/components/ContentNode/ProfileRefreshTokenJob.bs b/playlet-lib/src/components/ContentNode/ProfileRefreshTokenJob.bs index 59395731..26c9ece5 100644 --- a/playlet-lib/src/components/ContentNode/ProfileRefreshTokenJob.bs +++ b/playlet-lib/src/components/ContentNode/ProfileRefreshTokenJob.bs @@ -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 diff --git a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs index f97d67e0..4ac008d7 100644 --- a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs +++ b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs @@ -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 diff --git a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml index d67cb0e8..44488566 100644 --- a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml +++ b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml @@ -1,7 +1,7 @@ - + diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.bs b/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.bs index 80264f58..1591304a 100644 --- a/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.bs +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.bs @@ -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 diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.xml b/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.xml index 83bdb0fa..f1d59740 100644 --- a/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.xml +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileView/ProfileView.xml @@ -21,11 +21,11 @@ - + + translation="[520,142]" /> + translation="[520,220]" /> + translation="[520,298]" /> + + diff --git a/playlet-lib/src/components/Services/Innertube/OAuth.bs b/playlet-lib/src/components/Services/Innertube/OAuth.bs index cb4cafa4..636fbcf7 100644 --- a/playlet-lib/src/components/Services/Innertube/OAuth.bs +++ b/playlet-lib/src/components/Services/Innertube/OAuth.bs @@ -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 diff --git a/playlet-lib/src/components/Services/Invidious/Invidious.xml b/playlet-lib/src/components/Services/Invidious/Invidious.xml index 8d3a6376..3a293aa6 100644 --- a/playlet-lib/src/components/Services/Invidious/Invidious.xml +++ b/playlet-lib/src/components/Services/Invidious/Invidious.xml @@ -5,7 +5,6 @@ - diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index 15ee8234..625b510b 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -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 diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesInvidiousUnregisterTokenJob.bs b/playlet-lib/src/components/Services/ProfilesService/ProfilesInvidiousUnregisterTokenJob.bs index 843cb1fc..bce9d25d 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesInvidiousUnregisterTokenJob.bs +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesInvidiousUnregisterTokenJob.bs @@ -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 diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs index 2b7c7310..fb1fc87a 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.bs @@ -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 ") 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 diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.xml b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.xml index d4a0c574..2ab4e366 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesService.xml +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesService.xml @@ -7,6 +7,7 @@ --> + @@ -17,7 +18,6 @@ - diff --git a/playlet-lib/src/components/Services/ProfilesService/ProfilesVerifyTokensJob.bs b/playlet-lib/src/components/Services/ProfilesService/ProfilesVerifyTokensJob.bs index f6d078e0..3d2d81bf 100644 --- a/playlet-lib/src/components/Services/ProfilesService/ProfilesVerifyTokensJob.bs +++ b/playlet-lib/src/components/Services/ProfilesService/ProfilesVerifyTokensJob.bs @@ -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 diff --git a/playlet-lib/src/components/VideoFeed/VideoRowList.bs b/playlet-lib/src/components/VideoFeed/VideoRowList.bs index 27e5c035..538965de 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowList.bs +++ b/playlet-lib/src/components/VideoFeed/VideoRowList.bs @@ -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() diff --git a/playlet-lib/src/components/VideoFeed/VideoRowList.xml b/playlet-lib/src/components/VideoFeed/VideoRowList.xml index 30f9e084..80f5b2bf 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowList.xml +++ b/playlet-lib/src/components/VideoFeed/VideoRowList.xml @@ -2,6 +2,7 @@ + diff --git a/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedJob.bs b/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedJob.bs index 7c754aa1..afd00ff7 100644 --- a/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedJob.bs +++ b/playlet-lib/src/components/VideoPlayer/MarkVideoWatchedJob.bs @@ -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 diff --git a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs index 451a27da..64605be4 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoContentJob.bs @@ -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, { diff --git a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs index de5ae8d4..32177fec 100644 --- a/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs +++ b/playlet-lib/src/components/VideoPlayer/VideoPlayer.bs @@ -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 diff --git a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs index f091e35b..2fcd4181 100644 --- a/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs +++ b/playlet-lib/src/components/VideoPlayerDev/VideoPlayerDev.bs @@ -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 diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs index 10596426..8176e701 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs @@ -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 diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs index 470b68d0..d62a7b04 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs @@ -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 diff --git a/playlet-lib/src/locale/de_DE/translations.ts b/playlet-lib/src/locale/de_DE/translations.ts index 27e84e6a..68ed19d4 100644 --- a/playlet-lib/src/locale/de_DE/translations.ts +++ b/playlet-lib/src/locale/de_DE/translations.ts @@ -64,10 +64,6 @@ Failed to load channel %1 Der Kanal %1 konnte nicht geladen werden - - 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. - 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. - Premieres in 1 minute Premiere in 1 Minute @@ -428,10 +424,6 @@ Failed to load feed Feed konnte nicht geladen werden - - User logged out - Benutzer ausgellogt - Failed to get screen ID. Please restart Playlet to use the cast function. Bildschirm ID konnte nicht gefunden werden. Bitte starten sie Playlet neu, um die Cast-Funktion nutzen zu können. diff --git a/playlet-lib/src/locale/en_US/translations.ts b/playlet-lib/src/locale/en_US/translations.ts index 0d37bdcb..bfaf56eb 100644 --- a/playlet-lib/src/locale/en_US/translations.ts +++ b/playlet-lib/src/locale/en_US/translations.ts @@ -225,12 +225,20 @@ Failed to load feed - User logged out - User logged out + Session expired + Session expired - 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. - 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. + The session has expired. Please sign in again with this profile, or switch to another profile. + The session has expired. Please sign in again with this profile, or switch to another profile. + + + The session has expired. + The session has expired. + + + Please sign in again with this profile, or switch to another profile. + Please sign in again with this profile, or switch to another profile. Lounge service setup error diff --git a/playlet-lib/src/locale/es_ES/translations.ts b/playlet-lib/src/locale/es_ES/translations.ts index bf0cbe17..9bde37d8 100644 --- a/playlet-lib/src/locale/es_ES/translations.ts +++ b/playlet-lib/src/locale/es_ES/translations.ts @@ -208,10 +208,6 @@ Failed to load feed Fallo al cargar el feed - - User logged out - Usuario desconectado - Lounge service setup error Error de configuración del servicio Lounge @@ -360,10 +356,6 @@ Invalid JSON from %1 (couldn't read %2) JSON no válido para %1 (no se pudo leer %2) - - 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. - 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. - Refresh Recargar diff --git a/playlet-lib/src/locale/es_MX/translations.ts b/playlet-lib/src/locale/es_MX/translations.ts index fe0bc770..9ebc185c 100644 --- a/playlet-lib/src/locale/es_MX/translations.ts +++ b/playlet-lib/src/locale/es_MX/translations.ts @@ -828,10 +828,6 @@ Playlist load error Error al cargar la playlist - - User logged out - Usuario cerró sesión - Failed to load playlist %1 Error al cargar la playlist %1 @@ -924,10 +920,6 @@ Tap 'Link with TV code' and enter the code below. Presiona "Vincular con código de TV", y luego, ingresa el código que se muestra abajo. - - 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. - 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. - Tap the cast icon and select %1 Presiona el ícono de transmisión y selecciona %1 diff --git a/playlet-lib/src/locale/fr_CA/translations.ts b/playlet-lib/src/locale/fr_CA/translations.ts index fd4ed6c7..49e4e49c 100644 --- a/playlet-lib/src/locale/fr_CA/translations.ts +++ b/playlet-lib/src/locale/fr_CA/translations.ts @@ -208,14 +208,6 @@ Failed to load feed Échec du chargement du flux - - User logged out - Utilisateur déconnecté - - - 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. - Il semble que vous soyez connecté à Invidious, mais n'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. - Lounge service setup error Erreur de configuration du service Lounge diff --git a/playlet-lib/src/locale/pt_BR/translations.ts b/playlet-lib/src/locale/pt_BR/translations.ts index b90ad90c..6aca1eea 100644 --- a/playlet-lib/src/locale/pt_BR/translations.ts +++ b/playlet-lib/src/locale/pt_BR/translations.ts @@ -216,14 +216,6 @@ Failed to load feed Erro ao carregar o feed - - User logged out - Usuário desconectado - - - 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. - 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. - Lounge service setup error Erro ao configurar o serviço de lounge diff --git a/playlet-lib/src/source/components/tests/InnertubeRefreshTokenIntegration.spec.bs b/playlet-lib/src/source/components/tests/InnertubeRefreshTokenIntegration.spec.bs new file mode 100644 index 00000000..af09ec4b --- /dev/null +++ b/playlet-lib/src/source/components/tests/InnertubeRefreshTokenIntegration.spec.bs @@ -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 diff --git a/playlet-lib/src/source/components/tests/OAuth.spec.bs b/playlet-lib/src/source/components/tests/OAuth.spec.bs new file mode 100644 index 00000000..2adf43db --- /dev/null +++ b/playlet-lib/src/source/components/tests/OAuth.spec.bs @@ -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 diff --git a/playlet-lib/src/source/components/tests/ProfileContentAuthTokenUtils.spec.bs b/playlet-lib/src/source/components/tests/ProfileContentAuthTokenUtils.spec.bs new file mode 100644 index 00000000..7b475c69 --- /dev/null +++ b/playlet-lib/src/source/components/tests/ProfileContentAuthTokenUtils.spec.bs @@ -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 diff --git a/playlet-lib/src/source/utils/Locale.bs b/playlet-lib/src/source/utils/Locale.bs index 4f03daec..001da540 100644 --- a/playlet-lib/src/source/utils/Locale.bs +++ b/playlet-lib/src/source/utils/Locale.bs @@ -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"