diff --git a/playlet-app/src/manifest b/playlet-app/src/manifest index 7c489154..2249a1f5 100644 --- a/playlet-app/src/manifest +++ b/playlet-app/src/manifest @@ -40,7 +40,7 @@ requires_widevine_version=1.0 playlet_lib_squashfs_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.squashfs.pkg playlet_lib_zip_remote_url=https://github.com/iBicha/playlet/releases/latest/download/playlet-lib.zip playlet_lib_zip_embedded_url=pkg:/lib/playlet-lib.zip -playlet_lib_zip_debug_url=https://gitea.spaghet.io/spaghet/playlet-piped/raw/branch/main/piped/playlet-lib-1795462373.zip +playlet_lib_zip_debug_url=https://gitea.spaghet.io/spaghet/playlet-piped/raw/branch/main/piped/playlet-lib-1795488106.zip git_commit_sha=unknown diff --git a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs index c6106bb3..0b72f76c 100644 --- a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs +++ b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.bs @@ -7,6 +7,12 @@ function Init() m.urlLabel = m.top.findNode("urlLabel") m.qrCode = m.top.findNode("QrCodePoster") + if ValidString(m.top.loginKind) = "piped" + m.top.findNode("dlgTitle").primaryTitle = "Login to Piped" + m.top.findNode("bodyLine1").text = "Login to Piped in order to view Subscriptions and Playlists." + m.top.findNode("bodyLine2").text = "Sign in from your phone with SSO, or with a Piped username and password." + end if + m.top.width = "920" m.top.observeFieldScoped("buttonSelected", FuncName(Close)) @@ -18,7 +24,12 @@ function OnNodeReady() address = m.webserver@.GetServerAddress() isValidAddress = not StringUtils.IsNullOrEmpty(address) if isValidAddress - url = `${address}/invidious/login` + loginKind = ValidString(m.top.loginKind) + if loginKind = "piped" + url = `${address}/piped/login` + else + url = `${address}/invidious/login` + end if profileId = m.top.profileId if not StringUtils.IsNullOrEmpty(profileId) url = UrlUtils.AppendQueryParams(url, { profile: profileId }) diff --git a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml index fff03170..94397996 100644 --- a/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml +++ b/playlet-lib/src/components/Dialog/InvidiousLoginDialog.xml @@ -4,13 +4,14 @@ + - + - - + + diff --git a/playlet-lib/src/components/Screens/ProfileScreen/BackendTypeSelectionView/BackendTypeSelectionView.xml b/playlet-lib/src/components/Screens/ProfileScreen/BackendTypeSelectionView/BackendTypeSelectionView.xml index a462cce8..e1433c20 100644 --- a/playlet-lib/src/components/Screens/ProfileScreen/BackendTypeSelectionView/BackendTypeSelectionView.xml +++ b/playlet-lib/src/components/Screens/ProfileScreen/BackendTypeSelectionView/BackendTypeSelectionView.xml @@ -40,6 +40,8 @@ + + diff --git a/playlet-lib/src/components/Screens/ProfileScreen/LoginUtils.bs b/playlet-lib/src/components/Screens/ProfileScreen/LoginUtils.bs index 640d89d1..332038d2 100644 --- a/playlet-lib/src/components/Screens/ProfileScreen/LoginUtils.bs +++ b/playlet-lib/src/components/Screens/ProfileScreen/LoginUtils.bs @@ -11,6 +11,14 @@ namespace LoginUtils m.top.getScene().dialog = dialog end function + function ShowPipedLoginDialog(profileId = "" as string) as void + dialog = CreateObject("roSGNode", "InvidiousLoginDialog") + dialog.profileId = profileId + dialog.loginKind = "piped" + dialog@.BindNode() + m.top.getScene().dialog = dialog + end function + function ShowLoginWithYouTubeDisclaimerDialog() as void dialog = DialogUtils.ShowDialogEx({ title: Tr(Locale.Dialogs.Disclaimer) diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs index 91819a28..edc61bcf 100644 --- a/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs @@ -56,6 +56,8 @@ function OnBackEndSelected(event as object) as void selectedBackendType = event.getData() if selectedBackendType = "BackendTypeInvidious" OnLoginWithInvidiousSelected() + else if selectedBackendType = "BackendTypePiped" + LoginUtils.ShowPipedLoginDialog() else if selectedBackendType = "BackendTypeYouTube" LoginUtils.ShowLoginWithYouTubeDisclaimerDialog() else diff --git a/playlet-lib/src/components/Services/Piped/PipedToInvidious.bs b/playlet-lib/src/components/Services/Piped/PipedToInvidious.bs index 641bc641..1051388e 100644 --- a/playlet-lib/src/components/Services/Piped/PipedToInvidious.bs +++ b/playlet-lib/src/components/Services/Piped/PipedToInvidious.bs @@ -1,5 +1,6 @@ import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" +import "pkg:/source/utils/TimeUtils.bs" ' Converts Piped API responses (https://github.com/TeamPiped/Piped) into ' the JSON shapes Playlet expects from an Invidious /api/v1 backend. @@ -650,4 +651,94 @@ namespace PipedToInvidious return bytes.ToAsciiString() end function + ' ---------------- auth/profile token shapes ---------------- + + ' Playlet stores invidious profile tokens as signed JSON and validates the + ' scopes array + expire field client-side (VerifyTokenScope / + ' DeriveAuthState). Piped's credential is a bare session UUID, so we wrap + ' it in the same JSON shape here; the TV-side router unwraps it again + ' before talking to Piped. The client only ever sends this blob to the + ' local router, never to Piped itself. + function MakePipedTokenJson(username as string, sessionUuid as string, instance as string) as string + nowSeconds = TimeUtils.Now().AsSeconds() + expire = nowSeconds + 60 * 60 * 24 * 365 * 2 + token = { + "token": sessionUuid + "user": ValidString(username) + "scopes": ["GET:feed", "GET:playlists*", "POST:tokens/*", ":history*", ":subscriptions*"] + "expire": expire + "lastUsed": nowSeconds * 1000 + "createdAt": nowSeconds * 1000 + } + return FormatJson(token) + end function + + ' Accepts either the wrapped JSON or a bare UUID (defensive: manual seeding). + function ExtractPipedSession(accessToken as dynamic) as string + token = StringUtils.ParseJsonSafe(ValidString(accessToken)) + if IsAssociativeArray(token) and not StringUtils.IsNullOrEmpty(ValidString(token.token)) + return ValidString(token.token) + end if + s = ValidString(accessToken) + if not StringUtils.IsNullOrEmpty(s) and InStr(s, "{") = 0 + return s + end if + return "" + end function + + function ExtractPipedUsername(accessToken as dynamic) as string + token = StringUtils.ParseJsonSafe(ValidString(accessToken)) + if IsAssociativeArray(token) + return ValidString(token.user) + end if + return "" + end function + + ' Piped /subscriptions item {url:/channel/UC.., name, avatar, verified} + ' -> Invidious subscription {author, authorId, url, avatarURL, ...} + function SubscriptionsFromPiped(list as dynamic) as object + out = [] + for each item in EnsureArray(list) + if not IsAssociativeArray(item) + continue for + end if + channelId = ExtractChannelId(ValidString(item.url)) + out.push({ + "author": ValidString(item.name) + "authorId": channelId + "url": `/api/v1/channels/${channelId}` + "avatarURL": ValidString(item.avatar) + "notifications": false + "playlistID": "" + }) + end for + return out + end function + + ' Piped /user/playlists item {id, name, thumbnail, videos?, updated?} + ' -> Invidious playlist list item + function AuthPlaylistsFromPiped(list as dynamic) as object + out = [] + for each item in EnsureArray(list) + if not IsAssociativeArray(item) + continue for + end if + updated = ValidInt(item.updated) + out.push({ + "id": ValidString(item.id) + "type": "invidiousPlaylist" + "title": ValidString(item.name) + "url": `/playlist?list=${ValidString(item.id)}` + "author": "" + "authorId": "" + "description": ValidString(item.shortDescription) + "thumbnail": ValidString(item.thumbnail) + "videos": ValidInt(item.videos) + "updated": updated + "viewCount": 0 + }) + end for + return out + end function + end namespace diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs index 89e1dc19..9e0554d1 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs @@ -1,11 +1,11 @@ import "pkg:/components/Services/Piped/PipedToInvidious.bs" +import "pkg:/components/Services/Invidious/InvidiousService.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" -import "pkg:/components/Web/PlayletWebServer/Middleware/HlsRouter.bs" ' Serves the Invidious /api/v1 JSON shapes that Playlet's client expects, ' translated from a real Piped instance (https://github.com/TeamPiped/Piped). @@ -121,8 +121,15 @@ namespace Http return result end function + function AuthLogSnapshot() as object + if m.authLog = invalid + return [] + end if + return m.authLog + end function + function LibBuildTag() as string - return "PIPED-LIB-14" + return "PIPED-LIB-17" end function function FetchJson(path as string, params = invalid as object) as dynamic @@ -206,7 +213,7 @@ namespace Http context.playlistId = parts[1] return m.GetPlaylist(context) else if head = "auth" - return m.UnsupportedAuth(context) + return m.GetAuth(context) end if return false @@ -217,7 +224,7 @@ namespace Http @post("*") function PostAll(context as object) as boolean if context.request.route.StartsWith("/playlet-piped-backend/api/v1/auth/") - return m.UnsupportedAuth(context) + return m.PostAuth(context) end if return false end function @@ -225,11 +232,337 @@ namespace Http @delete("*") function DeleteAll(context as object) as boolean if context.request.route.StartsWith("/playlet-piped-backend/api/v1/auth/") - return m.UnsupportedAuth(context) + return m.DeleteAuth(context) end if return false end function + ' ---------------- auth: token plumbing ---------------- + + ' The client sends the profile accessToken as our wrapped JSON + ' (PipedToInvidious.MakePipedTokenJson); Piped itself wants the bare + ' session UUID in a raw Authorization header (no Bearer prefix - + ' verified against api.piped.spaghet.io), or ?authToken= for /feed. + function GetAccessToken(request as object) as dynamic + header = ValidString(request.headers["Authorization"]) + if StringUtils.IsNullOrEmpty(header) + header = ValidString(request.headers["authorization"]) + end if + if StringUtils.IsNullOrEmpty(header) + return invalid + end if + if header.StartsWith("Bearer ") + header = header.Mid(7) + end if + session = PipedToInvidious.ExtractPipedSession(header) + if StringUtils.IsNullOrEmpty(session) + return invalid + end if + return session + end function + + function RequireAccessToken(context as object) as dynamic + request = context.request + response = context.response + + token = m.GetAccessToken(request) + m.LogAuthRequest(request.route, "tok-" + Left(ValidString(token), 9)) + if token = invalid + m.LogAuthRequest(request.route, "403-no-token") + response.Json({ "error": Invidious.ERROR_NOT_AUTHENTICATED }) + response.http_code = 403 + end if + return token + end function + + ' rolling window of auth calls for field debugging (exposed via stats) + function LogAuthRequest(route as string, outcome as string) as void + if m.authLog = invalid + m.authLog = [] + end if + m.authLog.push(ValidString(route) + " => " + outcome) + if m.authLog.Count() > 12 + trimmed = [] + for t = m.authLog.Count() - 12 to m.authLog.Count() - 1 + trimmed.push(m.authLog[t]) + end for + m.authLog = trimmed + end if + end function + + function PipedAuthGet(path as string, session as dynamic, params = invalid as object) as dynamic + request = HttpClient.Get(m.GetBaseUrl() + path) + if session <> invalid + if path = "/feed" + request.QueryParam("authToken", session) + else + request.Header("Authorization", session) + end if + end if + ' Piped's ThrottlingCache keys on path+query and replays cached + ' error responses (re-seeding them on every hit), so one genuine + ' 401 - e.g. right after the broker rotates a session - poisons + ' this exact URL for the TV for as long as it keeps polling. A + ' per-call nonce makes every authenticated upstream GET a fresh + ' key and a real lookup; the fork's handlers ignore unknown params. + request.QueryParam("pb", CreateObject("roDeviceInfo").GetRandomUUID()) + if params <> invalid + for each key in params + value = params[key] + if value <> invalid and value <> "" + request.QueryParam(key, value) + end if + end for + end if + return request.Await() + end function + + function PipedAuthPost(path as string, body as object, session as dynamic) as dynamic + request = HttpClient.Post(m.GetBaseUrl() + path) + request.Header("Content-Type", "application/json") + if session <> invalid + request.Header("Authorization", session) + end if + request.JsonBody(body) + return request.Await() + end function + + ' ---------------- auth handlers ---------------- + + ' GET /api/v1/auth/ + function GetAuth(context as object) as boolean + route = context.request.route + tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len()) + parts = tail.Split("/") + head = "" + if parts.Count() > 0 + head = parts[0] + end if + + if head = "feed" + return m.GetAuthFeed(context) + else if head = "subscriptions" + return m.GetAuthSubscriptions(context) + else if head = "playlists" + if parts.Count() >= 2 + context.playlistId = parts[1] + return m.GetAuthPlaylist(context) + end if + return m.GetAuthPlaylists(context) + else if head = "history" + ' Piped (this fork) has no server-side watch history; the + ' browser keeps it in IndexedDB. Return empty, not an error. + m.SendJson(context.response, { "items": [], "continuation": "" }) + return true + end if + + return m.UnsupportedAuth(context) + end function + + ' POST /api/v1/auth/history (mark watched) + /auth/subscriptions/ (subscribe) + function PostAuth(context as object) as boolean + route = context.request.route + tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len()) + + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + if tail = "history" or Left(tail, 8) = "history/" + ' no server-side history on this Piped fork: accept silently + m.SendJson(context.response, { "status": "ok" }) + return true + end if + + if tail = "subscriptions" or Left(tail, 14) = "subscriptions/" + ' Playlet's Subscribe posts to /auth/subscriptions/ + channelId = "" + if tail.Len() > 14 + channelId = tail.Mid(14) + end if + if StringUtils.IsNullOrEmpty(channelId) + m.SendJson(context.response, { "error": "Missing channelId" }, 400) + return true + end if + + res = m.PipedAuthPost("/subscribe", { channelId: channelId }, session) + if not res.IsSuccess() + LogWarn("Piped backend: subscribe failed", res.StatusCode()) + m.SendJson(context.response, { "error": "Subscribe failed" }, 502) + return true + end if + m.SendJson(context.response, { "status": "ok" }) + return true + end if + + ' tokens/register etc. - accept, Piped sessions need no registration + m.SendJson(context.response, { "status": "ok" }) + return true + end function + + ' DELETE /api/v1/auth/subscriptions/ + function DeleteAuth(context as object) as boolean + route = context.request.route + tail = route.Mid("/playlet-piped-backend/api/v1/auth/".Len()) + + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + if Left(tail, 14) = "subscriptions/" + channelId = tail.Mid(14) + res = m.PipedAuthPost("/unsubscribe", { channelId: channelId }, session) + if not res.IsSuccess() + LogWarn("Piped backend: unsubscribe failed", res.StatusCode()) + m.SendJson(context.response, { "error": "Unsubscribe failed" }, 502) + return true + end if + m.SendJson(context.response, { "status": "ok" }) + return true + end if + + ' logout/unregister: do NOT call Piped /logout - the same session + ' is in use by the user's browser, and logging out would kill it. + m.SendJson(context.response, { "status": "ok" }) + return true + end function + + function GetAuthFeed(context as object) as boolean + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + res = m.PipedAuthGet("/feed", session) + if not res.IsSuccess() + m.LogAuthRequest(context.request.route, `feed-upstream-${res.StatusCode()}`) + LogWarn("Piped backend: auth feed failed", res.StatusCode()) + if m.IsSessionRejected(res, session) + m.SendSessionRejected(context.response) + else + m.SendJson(context.response, { "error": "Feed unavailable" }, 502) + end if + return true + end if + + m.LogAuthRequest(context.request.route, "feed-ok") + items = PipedToInvidious.VideosFromPiped(res.Json()) + m.SendJson(context.response, { "videos": items }) + return true + end function + + function GetAuthSubscriptions(context as object) as boolean + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + res = m.PipedAuthGet("/subscriptions", session) + if not res.IsSuccess() + m.LogAuthRequest(context.request.route, `subs-upstream-${res.StatusCode()}`) + LogWarn("Piped backend: subscriptions failed", res.StatusCode()) + if m.IsSessionRejected(res, session) + m.SendSessionRejected(context.response) + else + m.SendJson(context.response, { "error": "Subscriptions unavailable" }, 502) + end if + return true + end if + + subsData = res.Json() + subsCount = 0 + if IsArray(subsData) + subsCount = subsData.Count() + end if + m.LogAuthRequest(context.request.route, `subs-ok-${subsCount}`) + m.SendJson(context.response, PipedToInvidious.SubscriptionsFromPiped(res.Json())) + return true + end function + + function GetAuthPlaylists(context as object) as boolean + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + res = m.PipedAuthGet("/user/playlists", session) + if not res.IsSuccess() + m.LogAuthRequest(context.request.route, `playlists-upstream-${res.StatusCode()}`) + LogWarn("Piped backend: playlists failed", res.StatusCode()) + if m.IsSessionRejected(res, session) + m.SendSessionRejected(context.response) + else + m.SendJson(context.response, { "error": "Playlists unavailable" }, 502) + end if + return true + end if + + m.SendJson(context.response, PipedToInvidious.AuthPlaylistsFromPiped(res.Json())) + return true + end function + + function GetAuthPlaylist(context as object) as boolean + session = m.RequireAccessToken(context) + if session = invalid + return true + end if + + playlistId = ValidString(context.playlistId) + res = m.PipedAuthGet(`/playlists/${playlistId}`, session) + if not res.IsSuccess() + m.SendJson(context.response, { "error": "Playlist unavailable" }, 502) + return true + end if + + m.SendJson(context.response, PipedToInvidious.PlaylistFromPiped(res.Json(), playlistId)) + return true + end function + + ' Piped rejects a rotated/dead session with 401 "An invalid Session ID + ' was provided." Playlet's MarkNeedsReauthIfCredentialsRejected only + ' fires on a 403 whose body contains this exact Invidious phrasing, + ' so translate: broker rotation then cleanly re-arms the TV login. + function SendSessionRejected(response as object) as void + response.Json({ "error": "Request must be authenticated" }) + response.http_code = 403 + end function + + ' Piped's ThrottlingCache replays error responses per path (and can + ' answer a live session with a stale 401 for minutes), so a 401 here + ' is NOT proof of death. Confirm against two independent endpoints; + ' only if BOTH also reject is the session truly gone. When the picture + ' stays ambiguous, callers get a 502 instead: the row shows "failed to + ' load" and retries on the next refresh, but the stored profile - and + ' its token - survive, instead of MarkNeedsReauth wiping a live login. + function IsSessionRejected(res as object, session as dynamic) as boolean + if res.StatusCode() <> 401 and not (res.StatusCode() = 400 and res.Text().InStr("session is a required parameter") > 0) + return false + end if + if session = invalid + return true + end if + probe1 = m.PipedAuthGet("/subscriptions", session) + m.LogAuthRequest("probe1", `subs-${probe1.StatusCode()}`) + if probe1.IsSuccess() + return false + end if + probe2 = m.PipedAuthGet("/user/playlists", session) + m.LogAuthRequest("probe2", `playlists-${probe2.StatusCode()}`) + if probe2.IsSuccess() + return false + end if + ' Both probes rejected too - but they can replay throttle 401s as + ' well. One last delay-and-retry on the primary probe distinguishes + ' a throttle window (persists ~minutes) from... nothing; if the + ' retry still 401s we accept the verdict and ask for re-login. + wait(3000, CreateObject("roMessagePort")) + probe3 = m.PipedAuthGet("/subscriptions", session) + m.LogAuthRequest("probe3", `subs-retry-${probe3.StatusCode()}`) + return not probe3.IsSuccess() + end function + function UnsupportedAuth(context as object) as boolean m.SendJson(context.response, { "error": "Piped backend accounts are not supported yet. Browse anonymously, or log in to your Piped instance in a browser." @@ -249,6 +582,7 @@ namespace Http m.SendJson(response, { "buildTag": m.LibBuildTag() + "authLog": m.AuthLogSnapshot() "software": "piped" "version": ValidString(stats.version) diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs new file mode 100644 index 00000000..7deaa6ad --- /dev/null +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs @@ -0,0 +1,410 @@ +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. + function EnsureLoginNonce() as string + if m.loginNonces = invalid + m.loginNonces = ["", "", "", ""] + m.loginNonceSlot = 0 + end if + nonce = CreateObject("roDeviceInfo").GetRandomUUID() + m.loginNonces[m.loginNonceSlot] = nonce + m.loginNonceSlot = (m.loginNonceSlot + 1) mod 4 + return nonce + end function + + function KnownNonceIdx(nonce as string) as integer + if m.loginNonces = invalid or 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 + + 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 + + nonce = m.EnsureLoginNonce() + reqNonce = ValidString(request.query.nonce) + if reqNonce <> "" and reqNonce <> nonce + ' The TV dialog re-rendered; the link the phone holds is stale + nonce = reqNonce + m.loginNonce = reqNonce + 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 = ValidString(fields.nonce) + + if nonce <> "" and m.loginNonce <> invalid and nonce <> m.loginNonce + response.Default(400, m.ErrorPage("Stale login page. Open the code on the TV 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 = ValidString(request.query.token) + nonce = ValidString(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 + response.Default(403, m.ErrorPage("Login link expired or already used. Start again on the TV.")) + return true + end if + ' consume: blank the slot (roArray splice ops vary by firmware) + m.loginNonces[idx] = "" + + ' Resolve the username for the session, best effort. + username = m.LookupUsername(token) + + m.SetLoggedInProfile(username, 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 LookupUsername(sessionUuid as string) as string + instance = m.GetInstance() + if StringUtils.IsNullOrEmpty(instance) + return "piped" + end if + + res = HttpClient.Get(`${instance}/subscriptions`).Header("Authorization", sessionUuid).Await() + if res.IsSuccess() + ' no username in the body; just prove the session works + end if + + ' Piped has no /user endpoint on this fork; the SSO broker's username + ' equals the Authentik identity, which we can't see here. Fall back + ' to a stable label. (The profile display name is cosmetic.) + 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 diff --git a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs index 9c02e9d0..0152191f 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs @@ -9,6 +9,7 @@ import "pkg:/components/Web/PlayletWebServer/Middleware/InnertubeRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletInvidiousBackendRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PipedBackendRouter.bs" +import "pkg:/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs" @@ -66,6 +67,9 @@ function SetupRoutes(server as object) "/api/innertube/get_drm_license" ' Every write needs the caller's bearer token. "/playlet-invidious-backend/" + "/playlet-piped-backend/" + ' The Piped phone login page posts a plain HTML form. + "/piped/" ])) if server.settings.WebSocketsEnabled server.UseRouter(new Http.WebSocketMiddleware()) @@ -87,6 +91,7 @@ function SetupRoutes(server as object) server.UseRouter(new Http.CacheRouter(server)) server.UseRouter(new Http.RegistryRouter()) server.UseRouter(new Http.PlayletInvidiousBackendRouter(server)) + server.UseRouter(new Http.PipedLoginRouter(server)) server.UseRouter(new Http.PipedBackendRouter(server)) server.UseRouter(new Http.InnertubeRouter(server)) diff --git a/playlet-lib/src/images/piped-logo.png b/playlet-lib/src/images/piped-logo.png new file mode 100644 index 00000000..8a3a968f Binary files /dev/null and b/playlet-lib/src/images/piped-logo.png differ