Use living room potoken identity

This commit is contained in:
Brahim Hadriche committed 2026-06-28 14:56:17 -04:00
1 parent 5c5fe19440
commit 4754e1620b
18 files changed
+233 -253

No files matched your search

@@ -51,12 +51,13 @@ namespace Innertube
function CreateContext(client as Innertube.ClientType, deviceInfo as object, options = invalid as object) as object
contextClient = invalid
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
if client = ClientType.Web
contextClient = CreateContextClientWeb(deviceInfo)
else if client = ClientType.IOS
contextClient = CreateContextClientIOS(deviceInfo)
else if client = ClientType.Tv or client = ClientType.TvDowngraded
contextClient = CreateContextClientTv(deviceInfo, client)
contextClient = CreateContextClientTv(deviceInfo, client, livingRoomPoTokenId)
else
throw "Invalid client type"
end if
@@ -163,12 +164,12 @@ namespace Innertube
}
end function
function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType) as object
function CreateContextClientTv(deviceInfo as object, client as Innertube.ClientType, livingRoomPoTokenId = "" as dynamic) as object
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION
if client = ClientType.TvDowngraded
tvClientVersion = INNERTUBE_TV_CLIENT_VERSION_DOWNGRADED
end if
return {
contextClient = {
"hl": GetCurrentLocale(deviceInfo)
"gl": GetContentRegion(deviceInfo)
"remoteHost": ""
@@ -205,6 +206,10 @@ namespace Innertube
"playerType": "UNIPLAYER"
"connectionType": "CONN_CELLULAR_4G"
}
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
contextClient.tvAppInfo["livingRoomPoTokenId"] = livingRoomPoTokenId
end if
return contextClient
end function
function GetCurrentLocale(deviceInfo as object) as string
@@ -4,29 +4,23 @@ import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/source/utils/StringUtils.bs"
function Init()
m.top.observeField("requestVisitorData", FuncName(OnRequestVisitorData))
m.top.observeField("requestSessionData", FuncName(OnRequestSessionData))
end function
function OnNodeReady()
OnRequestVisitorData()
QueueSessionDataJob()
end function
function OnRequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
function OnRequestSessionData() as void
sessionData = m.top.sessionData
if IsAssociativeArray(sessionData) and not StringUtils.IsNullOrEmpty(sessionData.visitorData) and not StringUtils.IsNullOrEmpty(sessionData.livingRoomPoTokenId)
return
end if
RequestVisitorData()
QueueSessionDataJob()
end function
function RequestVisitorData() as void
if m.innertubeSessionDataJob <> invalid
m.innertubeSessionDataJob.cancel = true
m.innertubeSessionDataJob = invalid
end if
visitorData = m.top.visitorData
if not StringUtils.IsNullOrEmpty(visitorData)
function QueueSessionDataJob() as void
if m.innertubeSessionDataJob <> invalid and not m.innertubeSessionDataJob.done
return
end if
@@ -41,8 +35,4 @@ end function
function OnInnertubeSessionDataJobDone(event as object) as void
JobSystem.UnobserveCallback(event.getRoSGNode())
m.innertubeSessionDataJob = invalid
if StringUtils.IsNullOrEmpty(m.top.visitorData)
' Trigger observers in case the job threw an error and didn't set the visitorData
m.top.visitorData = ""
end if
end function
@@ -1,8 +1,7 @@
<component name="Innertube" extends="Node" includes="AutoBind">
<interface>
<field id="timestamp" type="int" />
<field id="visitorData" type="string" alwaysNotify="true" />
<field id="requestVisitorData" type="boolean" alwaysNotify="true" />
<field id="sessionData" type="assocarray" alwaysNotify="true" />
<field id="requestSessionData" type="boolean" alwaysNotify="true" />
<field id="jobQueue" type="node" />
</interface>
</component>
@@ -28,13 +28,6 @@ namespace InnertubeService
accessToken = OptionUtils.Get(options, "accessToken")
raw = OptionUtils.GetOrDefault(options, "raw", false)
if not StringUtils.IsNullOrEmpty(accessToken)
profileNode = OptionUtils.Get(options, "profileNode")
if profileNode <> invalid
options["datasyncIdToken"] = GetProfileDatasyncIdToken(profileNode, accessToken, OptionUtils.Get(options, "profilesService"), cancellation)
end if
end if
nextRequest = invalid
if fetchNext
nextRequest = Innertube.CreateNextRequest({ "videoId": videoId }, options)
@@ -767,53 +760,6 @@ namespace InnertubeService
return Innertube.ListAccounts(accessToken, cancellation)
end function
function GetProfileDatasyncIdToken(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as string
endpoint = profileNode.selectActiveIdentityEndpoint
if not IsAssociativeArray(endpoint) or endpoint.Count() = 0
endpoint = BackfillSelectActiveIdentityEndpoint(profileNode, accessToken, profilesService, cancellation)
end if
return Innertube.GetDatasyncIdToken(endpoint)
end function
' The identity used to bind GVS poTokens: the signed-in profile's datasyncIdToken,
' falling back to visitorData when logged out (or when no datasyncIdToken is available).
function GetCurrentPoTokenIdentity(profilesService as object, innertubeNode as object) as string
currentProfile = profilesService.currentProfile
if currentProfile <> invalid and currentProfile.type = "youtube"
accessToken = currentProfile.accessToken
if not StringUtils.IsNullOrEmpty(accessToken)
' Signed in: bind to the datasyncIdToken, matching the decipher request's identity.
return GetProfileDatasyncIdToken(currentProfile, accessToken, profilesService, invalid)
end if
end if
return innertubeNode.visitorData
end function
function BackfillSelectActiveIdentityEndpoint(profileNode as object, accessToken as string, profilesService as object, cancellation as object) as object
LogInfo("Backfilling selectActiveIdentityEndpoint for signed-in profile")
accounts = Innertube.ListAccounts(accessToken, cancellation)
if not IsArray(accounts)
return invalid
end if
for each account in accounts
if account.activeIdentifyToken <> profileNode.activeIdentifyToken
continue for
end if
endpoint = account.selectActiveIdentityEndpoint
if IsAssociativeArray(endpoint) and endpoint.Count() > 0
profileNode.selectActiveIdentityEndpoint = endpoint
if profilesService <> invalid
profilesService@.SaveUserProfilesToRegistry()
end if
return endpoint
end if
exit for
end for
return invalid
end function
function GetDrmLicense(options as object) as dynamic
request = Innertube.CreateGetDrmLicenceRequest(options)
@@ -6,23 +6,50 @@ function ExecuteJob() as void
innertubeNode = JobGetInput().innertube
cached = Innertube.ReadSessionDataFromRegistry()
if cached <> invalid and not StringUtils.IsNullOrEmpty(cached.visitorData)
if IsInt(cached.timestamp)
innertubeNode.timestamp = cached.timestamp
end if
innertubeNode.visitorData = cached.visitorData
if Innertube.IsSessionDataFresh(cached)
return
end if
cachedVisitorData = ""
cachedLivingRoomPoTokenId = ""
if IsAssociativeArray(cached)
cachedVisitorData = ValidString(cached.visitorData)
cachedLivingRoomPoTokenId = ValidString(cached.livingRoomPoTokenId)
end if
fetched = Innertube.RequestSessionData(JobGetCancellation())
if fetched <> invalid
Innertube.SaveSessionDataToRegistry(fetched)
innertubeNode.timestamp = fetched.timestamp
innertubeNode.visitorData = fetched.visitorData
else if StringUtils.IsNullOrEmpty(innertubeNode.visitorData)
' Refresh failed and we never had an id — wake a cold waiter to fail. Never blank a valid id.
innertubeNode.visitorData = ""
' Publish the cached values immediately so playback isn't blocked while /tv is fetched.
innertubeNode.sessionData = {
"visitorData": cachedVisitorData
"livingRoomPoTokenId": cachedLivingRoomPoTokenId
}
fresh = Innertube.RequestTvClientData(JobGetCancellation())
if fresh = invalid
return
end if
visitorData = cachedVisitorData
timestamp = 0
if Innertube.IsVisitorDataFresh(cached)
visitorData = cached.visitorData
timestamp = cached.timestamp
else if not StringUtils.IsNullOrEmpty(fresh.visitorData)
visitorData = fresh.visitorData
timestamp = fresh.timestamp
else if not StringUtils.IsNullOrEmpty(cachedVisitorData)
visitorData = cachedVisitorData
timestamp = cached.timestamp
end if
livingRoomPoTokenId = cachedLivingRoomPoTokenId
if not StringUtils.IsNullOrEmpty(fresh.livingRoomPoTokenId)
livingRoomPoTokenId = fresh.livingRoomPoTokenId
end if
Innertube.SaveSessionDataToRegistry({
"timestamp": timestamp
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
})
innertubeNode.sessionData = {
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
}
end function
@@ -248,7 +248,6 @@ namespace Innertube
"accountByline": ParseText(accountItem["accountByline"])
"channelHandle": ParseText(accountItem["channelHandle"])
"activeIdentifyToken": ParseAccountItemIdentityToken(accountItem)
"selectActiveIdentityEndpoint": ValidAssociativeArray(ObjectUtils.Dig(accountItem, ["serviceEndpoint", "selectActiveIdentityEndpoint"]))
}
parsedAccounts.Push(parsedAccount)
end for
@@ -298,26 +297,6 @@ namespace Innertube
return ""
end function
function GetDatasyncIdToken(selectActiveIdentityEndpoint as object) as string
supportedTokens = ObjectUtils.Dig(selectActiveIdentityEndpoint, ["supportedTokens"])
if not IsArray(supportedTokens)
return ""
end if
for each supportedToken in supportedTokens
if not IsAssociativeArray(supportedToken)
continue for
end if
datasyncIdToken = ObjectUtils.Dig(supportedToken, ["datasyncIdToken", "datasyncIdToken"])
if not StringUtils.IsNullOrEmpty(datasyncIdToken)
return datasyncIdToken
end if
end for
return ""
end function
function ToCamelCase(obj as object) as object
if not IsAssociativeArray(obj)
return obj
@@ -15,7 +15,7 @@ namespace Innertube
cancellation = OptionUtils.Get(options, "cancellation")
visitorData = OptionUtils.Get(options, "visitorData")
accessToken = OptionUtils.Get(options, "accessToken")
datasyncIdToken = OptionUtils.Get(options, "datasyncIdToken")
livingRoomPoTokenId = OptionUtils.Get(options, "livingRoomPoTokenId")
cpn = InnertubeService.CreateClientPlaybackNonce()
isTv = (client = Innertube.ClientType.Tv or client = Innertube.ClientType.TvDowngraded)
@@ -68,12 +68,15 @@ namespace Innertube
if not StringUtils.IsNullOrEmpty(visitorData) and not useAccessToken
request.Header("x-goog-visitor-id", visitorData)
request.poTokenIdentity = visitorData
else if useAccessToken and not StringUtils.IsNullOrEmpty(datasyncIdToken)
request.poTokenIdentity = datasyncIdToken
end if
if not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
request.poTokenIdentity = livingRoomPoTokenId
end if
if not StringUtils.IsNullOrEmpty(request.poTokenIdentity)
' NOTE: local potoken (browser-minted) is currently not in use.
' GetValidPoTokenForIdentity should return "", and the backend would mint the potoken.
request.poToken = Innertube.PoTokens.GetValidPoTokenForIdentity(request.poTokenIdentity)
end if
@@ -1,7 +1,8 @@
import "pkg:/components/Services/Innertube/Constants.bs"
import "pkg:/components/Services/Innertube/Context.bs"
import "pkg:/source/services/HttpClient.bs"
import "pkg:/source/utils/CancellationUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/ObjectUtils.bs"
import "pkg:/source/utils/RegistryUtils.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/TimeUtils.bs"
@@ -10,8 +11,9 @@ namespace Innertube
const SESSION_DATA_VERSION = 1
const INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS = 60 * 60 * 24 * 14 ' 14 days
const TV_CLIENT_DATA_MAX_ATTEMPTS = 3
function IsSessionDataFresh(sessionData as object) as boolean
function IsVisitorDataFresh(sessionData as object) as boolean
if sessionData = invalid or not IsInt(sessionData.timestamp)
return false
end if
@@ -19,48 +21,79 @@ namespace Innertube
return nowSeconds - sessionData.timestamp <= INNERTUBE_VISITOR_DATA_LIFESPAN_SECONDS
end function
function RequestSessionData(cancellation = invalid as object) as object
request = HttpClient.Get("https://www.youtube.com/sw.js_data")
request.Headers({
"Accept-Language": "en-US,en;q=0.9"
"User-Agent": INNERTUBE_WEB_USER_AGENT
"Accept": "*/*"
"Referer": "https://www.youtube.com/sw.js"
})
request.Cancellation(cancellation)
request.TryCount(2)
request.NoCache()
function RequestTvClientData(cancellation = invalid as object) as object
visitorData = ""
livingRoomPoTokenId = ""
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch session data: " + response.ErrorMessage())
return invalid
end if
for attempt = 1 to TV_CLIENT_DATA_MAX_ATTEMPTS
text = FetchTvClientPage(cancellation)
if text <> invalid
if StringUtils.IsNullOrEmpty(visitorData)
visitorData = ExtractEscapedJsonString(text, "visitorData")
end if
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
livingRoomPoTokenId = ExtractEscapedJsonString(text, "LIVING_ROOM_PO_TOKEN_ID")
end if
if not StringUtils.IsNullOrEmpty(visitorData) and not StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
exit for
end if
end if
if CancellationUtils.IsCancelled(cancellation)
exit for
end if
if attempt < TV_CLIENT_DATA_MAX_ATTEMPTS
sleep(attempt * 1000)
end if
end for
text = response.Text()
text = text.Replace(`)]}'`, "")
json = StringUtils.ParseJsonSafe(text)
if json = invalid
LogError("Failed to parse session data: " + text)
return invalid
end if
visitorData = ObjectUtils.Dig(json, [0, 2, 0, 0, 13])
if StringUtils.IsNullOrEmpty(visitorData)
LogError("Failed to find visitorData in session data: " + text)
LogError("Could not extract visitorData from tv client data")
end if
if StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
LogError("Could not extract livingRoomPoTokenId from tv client data")
end if
if StringUtils.IsNullOrEmpty(visitorData) and StringUtils.IsNullOrEmpty(livingRoomPoTokenId)
return invalid
end if
return {
"timestamp": TimeUtils.Now().AsSeconds()
"visitorData": visitorData
"livingRoomPoTokenId": livingRoomPoTokenId
}
end function
function FetchTvClientPage(cancellation as object) as dynamic
request = HttpClient.Get("https://www.youtube.com/tv")
headers = Innertube.CreateHeaders(Innertube.ClientType.Tv)
headers["Referer"] = "https://www.youtube.com/tv"
request.Headers(headers)
request.Cancellation(cancellation)
request.NoCache()
response = request.Await()
if not response.IsSuccess()
LogError("Failed to fetch tv client data:", response.ErrorMessage())
return invalid
end if
return response.Text()
end function
function ExtractEscapedJsonString(text as string, key as string) as string
regex = CreateObject("roRegex", `"${key}":"([^"]*)"`, "")
match = regex.Match(text)
if match.Count() < 2
return ""
end if
decoded = StringUtils.ParseJsonSafe(`["${match[1]}"]`)
if not IsArray(decoded) or decoded.Count() <> 1
return ""
end if
return decoded[0]
end function
function SaveSessionDataToRegistry(sessionData as object) as void
sessionData.__version = SESSION_DATA_VERSION
RegistryUtils.Write(RegistryUtils.INNERTUBE_SESSION_DATA, FormatJson(sessionData))
end function
@@ -70,13 +103,7 @@ namespace Innertube
return invalid
end if
sessionData = StringUtils.ParseJsonSafe(sessionData)
if sessionData = invalid
RegistryUtils.Delete(RegistryUtils.INNERTUBE_SESSION_DATA)
return invalid
end if
return sessionData
return StringUtils.ParseJsonSafe(sessionData)
end function
end namespace
@@ -58,7 +58,6 @@ function LoadProfilesFromRegistry()
profileNode.accessToken = profile.accessToken
profileNode.activeIdentifyToken = profile.activeIdentifyToken
profileNode.selectActiveIdentityEndpoint = profile.selectActiveIdentityEndpoint
profileNode.refreshToken = profile.refreshToken
profileNode.scope = profile.scope
profileNode.tokenType = profile.tokenType
@@ -183,7 +182,6 @@ function GetProfilesDto(includeAccessToken as boolean) as object
profile["expiresTimestamp"] = profileNode.expiresTimestamp
profile["clientId"] = profileNode.clientId
profile["clientSecret"] = profileNode.clientSecret
profile["selectActiveIdentityEndpoint"] = ValidAssociativeArray(profileNode.selectActiveIdentityEndpoint)
end if
userProfiles.profiles.Push(profile)