import "pkg:/components/Services/Piped/PipedToInvidious.bs" import "pkg:/source/services/HttpClient.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" import "pkg:/source/utils/UrlUtils.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/components/Web/WebServer/Http/HttpRouter.bs" namespace Http ' Phone-side login page for the Piped backend, mirroring InvidiousRouter's ' QR login flow. Served on the TV's local web server: ' GET /piped/login -> HTML page (SSO link + user/pass form) ' POST /piped/login -> {username,password} form -> Piped /login ' GET /piped/login/sso -> 302 to the instance's SSO broker (?next=/sso-tv...) ' GET /piped/token_callback -> ?token=&nonce= -> stores profile ' GET /piped/login/status -> JSON {waiting, username} for polling ' The login dialog on the TV closes itself when currentProfileChanged fires; ' this router only needs to create the profile via profilesService. class PipedLoginRouter extends HttpRouter function new(server as object) super() m.server = server m.profilesNode = server.sceneNodes.profilesService m.preferences = server.sceneNodes.preferences m.routes.push({ method: "GET", path: "/piped/login", router: m, func: "LoginPage" }) m.routes.push({ method: "POST", path: "/piped/login", router: m, func: "SubmitPassword" }) m.routes.push({ method: "GET", path: "/piped/login/sso", router: m, func: "RedirectToSso" }) m.routes.push({ method: "GET", path: "/piped/token_callback", router: m, func: "TokenCallback" }) m.routes.push({ method: "GET", path: "/piped/login/status", router: m, func: "LoginStatus" }) m.routes.push({ method: "GET", path: "/piped/login/debug", router: m, func: "DebugToken" }) m.routes.push({ method: "GET", path: "/piped/login/verify", router: m, func: "VerifyProbe" }) end function ' ---------------- shared ---------------- function Xml(text as string) as string out = text.Replace("&", "&") out = out.Replace("<", "<") out = out.Replace(">", ">") out = out.Replace(chr(34), """) return out end function function GetInstance() as string return ValidString(m.preferences["piped.instance"]) end function function GetTvBaseUrl() as dynamic ' m.server is the HttpServer class; its .task is the PlayletWebServer ' SGTask which owns GetServerAddress (DialRouter uses the same task). if m.server.task = invalid return invalid end if return m.server.task@.GetServerAddress() end function ' A small rolling window of issued nonces: the page may be reloaded, ' the QR rescanned, or a second phone pointed at the same dialog. A ' single-slot nonce made any of those (or a health probe) race the ' real login out of existence. ' Every page request issues a fresh nonce and keeps the three most ' recent valid, so whichever link/QR the phone actually holds still ' works - and a cached page response can never hand out a stale, ' already-consumed nonce. ' Every page request issues a fresh nonce. Nonces live in a fixed ' 4-slot ring so no roArray resize methods (removeIdx/deleteIdx/ ' subArray, which vary by firmware) are ever needed - only plain ' index assignment. The three most recent nonces stay valid, so a ' reloaded page, a rescanned QR, or a health probe can never race ' the real login out of existence; older ones fall out of the ring. ' The ring lives in the registry so an app restart (or a redeploy) ' mid-login cannot 403 a callback whose nonce was issued before it: ' the phone may sit on the SSO provider's page for minutes while the ' TV side churns. Load once, save on every mutation. function LoadNonceRing() as void if m.loginNonces <> invalid return end if m.loginNonces = ["", "", "", ""] m.loginNonceSlot = 0 reg = CreateObject("roRegistrySection", "piped_login") if reg.Exists("nonces") stored = reg.Read("nonces").Split("|") slot = Val(ValidString(reg.Read("slot"))) if slot >= 0 and slot < 4 m.loginNonceSlot = slot end if for i = 0 to 3 if i < stored.Count() and stored[i] <> invalid m.loginNonces[i] = ValidString(stored[i]) end if end for end if end function function SaveNonceRing() as void reg = CreateObject("roRegistrySection", "piped_login") reg.Write("nonces", m.loginNonces[0] + "|" + m.loginNonces[1] + "|" + m.loginNonces[2] + "|" + m.loginNonces[3]) reg.Write("slot", Str(m.loginNonceSlot).Replace(" ", "")) reg.Flush() end function function ClearNonceRing() as void m.loginNonces = ["", "", "", ""] m.loginNonceSlot = 0 m.SaveNonceRing() end function function EnsureLoginNonce() as string m.LoadNonceRing() nonce = CreateObject("roDeviceInfo").GetRandomUUID() m.loginNonces[m.loginNonceSlot] = nonce m.loginNonceSlot = (m.loginNonceSlot + 1) mod 4 m.SaveNonceRing() return nonce end function function KnownNonceIdx(nonce as string) as integer m.LoadNonceRing() if nonce = "" return -1 end if for i = 0 to 3 if m.loginNonces[i] = nonce return i end if end for return -1 end function ' Put a nonce into the ring (no-op if already present). The SSO ' redirect re-registers the nonce its URL carries so a login that ' started before an app restart - which wipes the in-memory ring - ' can still complete its callback instead of 403ing. function RegisterNonce(nonce as string) as void m.LoadNonceRing() for i = 0 to 3 if m.loginNonces[i] = nonce return end if end for m.loginNonces[m.loginNonceSlot] = nonce m.loginNonceSlot = (m.loginNonceSlot + 1) mod 4 end function ' The gate script appends token+nonce to the cb URL while the cb ' template already carries a nonce, so the callback can arrive with ' the key twice; Playlet's query parser turns duplicate keys into an ' ARRAY and ValidString(array) is "" -> the nonce looked unknown. function FirstStr(v as dynamic) as string if GetInterface(v, "ifArray") <> invalid if v.Count() > 0 return ValidString(v[0]) end if return "" end if return ValidString(v) end function function ReadLastSession() as string reg = CreateObject("roRegistrySection", "piped_login") if reg.Exists("current") return reg.Read("current") end if return "" end function function WriteLastSession(sessionUuid as string) as void reg = CreateObject("roRegistrySection", "piped_login") reg.Write("current", sessionUuid) reg.Flush() end function function SetLoggedInProfile(username as string, sessionUuid as string) as void instance = m.GetInstance() port = Str(m.server.task.port).Replace(" ", "") serverUrl = "http://127.0.0.1:" + port + "/playlet-piped-backend" tokenJson = PipedToInvidious.MakePipedTokenJson(username, sessionUuid, instance) profile = CreateObject("roSGNode", "ProfileContentNode") profile.type = "invidious" profile.username = username profile.accessToken = tokenJson profile.serverUrl = serverUrl m.profilesNode@.LoginWithProfile(profile) m.loggedInUsername = username end function ' ---------------- GET /piped/login ---------------- function LoginPage(context as object) as boolean response = context.response nonce = m.EnsureLoginNonce() instance = m.GetInstance() html = m.PageShell("Sign in to Piped", m.Body(instance, nonce)) response.http_code = 200 response.headers["Cache-Control"] = "no-store, max-age=0" response.ContentType("text/html") response.SetBodyDataString(html) return true end function function Body(instance as string, nonce as string) as string ssoLink = "/piped/login/sso?nonce=" + nonce return `

Piped

Instance: ${m.Xml(instance)}

Sign in with SSO (Authentik)
or use a Piped account

This signs in the TV only. Your phone browser session is untouched. SSO accounts have no password; use the SSO button.

` end function ' ---------------- GET /piped/login/sso ---------------- function RedirectToSso(context as object) as boolean request = context.request response = context.response reqNonce = m.FirstStr(request.query.nonce) if reqNonce <> "" ' The phone clicked the link the login page handed out; keep ' that nonce valid for the callback this redirect starts, ' even if the app restarted (ring wiped) in between. nonce = reqNonce m.RegisterNonce(reqNonce) else nonce = m.EnsureLoginNonce() end if instance = m.GetInstance() if StringUtils.IsNullOrEmpty(instance) response.Default(503, "Piped instance not configured") return true end if tv = m.GetTvBaseUrl() if tv = invalid response.Default(503, "TV address not available") return true end if callback = `${tv}/piped/token_callback?nonce=${nonce}` ' The SSO broker lives on the API origin (SSO_PUBLIC_ORIGIN) under /sso broker = instance if Right(broker, 1) = "/" broker = broker.Left(broker.Len() - 1) end if ' next must be a same-origin path on the Piped frontend; the gate ' script special-cases the /sso-tv path and bounces the phone here. nextPath = "/sso-tv?cb=" + callback.EncodeUriComponent() + "&nonce=" + nonce.EncodeUriComponent() ssoUrl = `${broker}/sso/?next=${nextPath.EncodeUriComponent()}` response.Redirect(ssoUrl, 302) return true end function ' ---------------- POST /piped/login (username/password) ---------------- function SubmitPassword(context as object) as boolean request = context.request response = context.response fields = m.ParseFormBody(ValidString(request.BodyText())) username = ValidString(fields.username) password = ValidString(fields.password) nonce = m.FirstStr(fields.nonce) if nonce <> "" and m.KnownNonceIdx(nonce) < 0 response.Default(400, m.ErrorPage(`Stale login page. Start again`)) return true end if if StringUtils.IsNullOrEmpty(username) or StringUtils.IsNullOrEmpty(password) response.Default(400, m.ErrorPage("Username and password are required.")) return true end if instance = m.GetInstance() if StringUtils.IsNullOrEmpty(instance) response.Default(503, m.ErrorPage("Piped instance not configured on the TV.")) return true end if body = FormatJson({ username: username, password: password }) httpRequest = HttpClient.Post(`${instance}/login`) httpRequest.Header("Content-Type", "application/json") res = httpRequest.TextBody(body).Await() data = res.Json() if not res.IsSuccess() or not IsAssociativeArray(data) or StringUtils.IsNullOrEmpty(ValidString(data.token)) detail = "Login failed." if IsAssociativeArray(data) and not StringUtils.IsNullOrEmpty(ValidString(data.error)) detail = ValidString(data.error) end if response.http_code = 200 response.headers["Cache-Control"] = "no-store, max-age=0" response.ContentType("text/html") response.SetBodyDataString(m.ErrorPage(detail + " Try again")) return true end if m.SetLoggedInProfile(username, ValidString(data.token)) response.http_code = 200 response.headers["Cache-Control"] = "no-store, max-age=0" response.ContentType("text/html") response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(username))) return true end function function ParseFormBody(form as string) as object fields = {} for each pair in form.Split("&") eq = pair.InStr("=") if eq <= 1 continue for end if key = pair.Left(eq - 1).DecodeUriComponent() value = pair.Mid(eq + 1).DecodeUriComponent() fields[key] = value end for return fields end function ' ---------------- GET /piped/token_callback (SSO handoff) ---------------- function TokenCallback(context as object) as boolean request = context.request response = context.response token = m.FirstStr(request.query.token) nonce = m.FirstStr(request.query.nonce) if StringUtils.IsNullOrEmpty(token) response.Default(400, m.ErrorPage("Missing token.")) return true end if ' Only accept a login this device handed out (a nonce from the ' rolling window above). Consume it so each link is single-use. idx = m.KnownNonceIdx(nonce) if idx < 0 ' A consumed nonce arriving with the SAME session we just ' installed is a retry/replay of a login that already ' succeeded (the gate script can bounce the phone twice) - ' show success, not an error the user cannot act on. if nonce <> "" and token = m.ReadLastSession() response.http_code = 200 response.headers["Cache-Control"] = "no-store, max-age=0" response.ContentType("text/html") response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(m.LookupUsername(token)))) return true end if response.Default(403, m.ErrorPage(`Login link expired or already used. Start again`)) return true end if ' consume: blank the slot (roArray splice ops vary by firmware) m.loginNonces[idx] = "" m.SaveNonceRing() ' Resolve the username for the session, best effort. username = m.LookupUsername(token) m.SetLoggedInProfile(username, token) m.WriteLastSession(token) response.http_code = 200 response.headers["Cache-Control"] = "no-store, max-age=0" response.ContentType("text/html") response.SetBodyDataString(m.PageShell("Signed in", m.SuccessBody(username))) return true end function ' The fork has no /user endpoint, but the authenticated RSS feed names ' the account: its is "Piped's RSS subscription feed for ' .". Read the username from there; fall back to a stable ' uuid label if the shape ever changes. (The profile name is cosmetic.) function LookupUsername(sessionUuid as string) as string instance = m.GetInstance() if StringUtils.IsNullOrEmpty(instance) return "piped" end if ' /feed/rss authenticates via ?authToken= (same contract as /feed). ' The pb nonce keeps this off Piped's ThrottlingCache replay keys. nonce = CreateObject("roDeviceInfo").GetRandomUUID() url = `${instance}/feed/rss?authToken=${sessionUuid}&pb=${nonce}` res = HttpClient.Get(url).Await() xml = "" if res.IsSuccess() xml = res.Text() end if if not StringUtils.IsNullOrEmpty(xml) ' Split instead of Mid/InStr: substring indexing disagreed with ' the docs on this firmware (both off-by-one directions shipped ' wrong results); Split boundaries are unambiguous. marker = "feed for " parts = xml.Split(marker) if parts.Count() > 1 tail = ValidString(parts[1]) name = ValidString(tail.Split(".")[0]) if name.Len() > 0 and name.Len() < 25 return name end if end if end if return "piped-" + Left(sessionUuid, 8) end function ' ---------------- GET /piped/login/status ---------------- function LoginStatus(context as object) as boolean response = context.response response.Json({ "waiting": m.loginNonces <> invalid and m.loginNonces.Count() > 0 "username": ValidString(m.loggedInUsername) }) return true end function function DebugToken(context as object) as boolean tj = PipedToInvidious.MakePipedTokenJson("u1", "abc-def", "https://api.piped.spaghet.io") parsed = StringUtils.ParseJsonSafe(tj) extracted = PipedToInvidious.ExtractPipedSession(tj) context.response.http_code = 200 context.response.Json({ "tokenJsonType": type(tj) "tokenJsonLen": Str(tj.Len()) "tokenJson": tj "parsedOk": IsAssociativeArray(parsed) "extracted": extracted }) return true end function ' Replays the two boot-time checks Playlet applies to a stored ' invidious profile token (DeriveAuthState + VerifyTokenScope) and ' reports each step, to find why a freshly stored Piped token gets ' marked NeedsReauth after an app restart. function VerifyProbe(context as object) as boolean response = context.response profiles = m.profilesNode@.GetProfilesDto(true) out = { "steps": [] } for each profile in profiles.profiles tok = ValidString(profile.accessToken) s = { "username": ValidString(profile.username) "tokLen": Len(tok) "tokHead": Left(tok, 40) } parsed = StringUtils.ParseJsonSafe(tok) s["parsed"] = IsAssociativeArray(parsed) if IsAssociativeArray(parsed) scopes = parsed.scopes s["scopesIsArray"] = IsArray(scopes) if IsArray(scopes) joined = scopes.Join(",") s["scopesMatch"] = (joined = "GET:feed,GET:playlists*,POST:tokens/*,:history*,:subscriptions*") s["scopesJoined"] = joined end if s["expireType"] = type(parsed.expire) s["expireIsNumber"] = IsNumber(parsed.expire) nowS = TimeUtils.Now().AsSeconds() s["expireVal"] = Str(parsed.expire) s["nowVal"] = Str(nowS) s["expired"] = (IsNumber(parsed.expire) and parsed.expire <= nowS) end if out.steps.push(s) end for response.http_code = 200 response.Json(out) return true end function ' ---------------- HTML ---------------- function PageShell(title as string, body as string) as string return ` ${m.Xml(title)} - Piped on TV ${body}` end function function SuccessBody(username as string) as string return `

✓

Signed in to the TV

Account: ${m.Xml(username)}

You can close this page and grab the remote. The Piped app on your TV now has your subscriptions, playlists and recommended feed.

` end function function ErrorPage(message as string) as string return `

Not signed in

${message}

` end function end class end namespace