Files
playlet-piped/playlet-lib/src/components/Web/PlayletWebServer/Middleware/PipedLoginRouter.bs
T

467 lines
20 KiB
Plaintext

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=<uuid>&nonce=<n> -> 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("&", "&amp;")
out = out.Replace("<", "&lt;")
out = out.Replace(">", "&gt;")
out = out.Replace(chr(34), "&quot;")
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
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 `
<div class="card">
<h1>Piped</h1>
<p class="muted">Instance: ${m.Xml(instance)}</p>
<a class="btn primary" href="${ssoLink}">Sign in with SSO (Authentik)</a>
<div class="sep">or use a Piped account</div>
<form method="POST" action="/piped/login">
<input name="username" type="text" placeholder="username" autocomplete="username" required>
<input name="password" type="password" placeholder="password" autocomplete="current-password" required>
<input type="hidden" name="nonce" value="${nonce}">
<button class="btn" type="submit">Sign in</button>
</form>
<p class="muted small">This signs in the TV only. Your phone browser session is untouched. SSO accounts have no password; use the SSO button.</p>
</div>`
end function
' ---------------- GET /piped/login/sso ----------------
function RedirectToSso(context as object) as boolean
request = context.request
response = context.response
reqNonce = ValidString(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 = ValidString(fields.nonce)
if nonce <> "" and m.KnownNonceIdx(nonce) < 0
response.Default(400, m.ErrorPage(`Stale login page. <a href="/piped/login">Start again</a>`))
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 + " <a href='/piped/login'>Try again</a>"))
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. <a href="/piped/login">Start again</a>`))
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)
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 `<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${m.Xml(title)} - Piped on TV</title>
<style>
body{font:16px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0f1115;color:#e6e8eb;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;padding:16px}
.card{width:min(420px,100%);background:#171a21;border:1px solid #262b36;border-radius:14px;padding:28px;text-align:center}
h1{margin:0 0 4px;font-size:1.4rem;color:#38bdf8}
.muted{color:#98a2b3}.small{font-size:.85rem}
.btn{display:block;width:100%;box-sizing:border-box;margin:10px 0;padding:12px;border-radius:10px;border:1px solid #3b4353;background:#232833;color:#e6e8eb;font-size:1rem;text-decoration:none;cursor:pointer}
.btn.primary{background:#0ea5e9;border-color:#0ea5e9;color:#04121d;font-weight:600}
input{display:block;width:100%;box-sizing:border-box;margin:10px 0;padding:12px;border-radius:10px;border:1px solid #3b4353;background:#0f1115;color:#e6e8eb;font-size:1rem}
.sep{color:#67707f;font-size:.85rem;margin:18px 0 4px;text-transform:uppercase;letter-spacing:.06em}
.ok{font-size:2.2rem;color:#34d399;margin:0}
a{color:#38bdf8}
</style></head><body>${body}</body></html>`
end function
function SuccessBody(username as string) as string
return `
<div class="card">
<p class="ok">&#10003;</p>
<h1>Signed in to the TV</h1>
<p class="muted">Account: ${m.Xml(username)}</p>
<p class="muted small">You can close this page and grab the remote. The Piped app on your TV now has your subscriptions, playlists and recommended feed.</p>
</div>`
end function
function ErrorPage(message as string) as string
return `<div class="card"><h1>Not signed in</h1><p>${message}</p></div>`
end function
end class
end namespace