Csrf middleware
This commit is contained in:
1 parent
b02d5d6a10
commit
fe15ea177b
6 files changed
+137
-40
No files matched your search
@@ -17,6 +17,7 @@ import "pkg:/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs"
|
|||||||
import "pkg:/components/Web/PlayletWebServer/Middleware/VideoQueueRouter.bs"
|
import "pkg:/components/Web/PlayletWebServer/Middleware/VideoQueueRouter.bs"
|
||||||
import "pkg:/components/Web/PlayletWebServer/Middleware/ViewRouter.bs"
|
import "pkg:/components/Web/PlayletWebServer/Middleware/ViewRouter.bs"
|
||||||
import "pkg:/components/Web/WebServer/Middleware/CorsMiddleware.bs"
|
import "pkg:/components/Web/WebServer/Middleware/CorsMiddleware.bs"
|
||||||
|
import "pkg:/components/Web/WebServer/Middleware/CsrfMiddleware.bs"
|
||||||
import "pkg:/components/Web/WebServer/Middleware/EtagMiddleware.bs"
|
import "pkg:/components/Web/WebServer/Middleware/EtagMiddleware.bs"
|
||||||
import "pkg:/components/Web/WebServer/Middleware/HttpStaticFilesRouter.bs"
|
import "pkg:/components/Web/WebServer/Middleware/HttpStaticFilesRouter.bs"
|
||||||
import "pkg:/components/Web/WebServer/WebSockets/WebSocketMiddleware.bs"
|
import "pkg:/components/Web/WebServer/WebSockets/WebSocketMiddleware.bs"
|
||||||
@@ -54,8 +55,17 @@ function SetupRoutes(server as object)
|
|||||||
'CORS is mostly for developing the web app
|
'CORS is mostly for developing the web app
|
||||||
server.UseRouter(new Http.CorsMiddleware())
|
server.UseRouter(new Http.CorsMiddleware())
|
||||||
#else
|
#else
|
||||||
|
' CsrfMiddleware relies on this: a page whose origin is allowed can send its header.
|
||||||
server.UseRouter(new Http.CorsMiddleware(""))
|
server.UseRouter(new Http.CorsMiddleware(""))
|
||||||
#end if
|
#end if
|
||||||
|
server.UseRouter(new Http.CsrfMiddleware("X-Playlet", [
|
||||||
|
' Phones and smart speakers can't send the header.
|
||||||
|
"/dial/"
|
||||||
|
' The player's license requests change nothing on the device, and a page can't read the license.
|
||||||
|
"/api/innertube/get_drm_license"
|
||||||
|
' Every write needs the caller's bearer token.
|
||||||
|
"/playlet-invidious-backend/"
|
||||||
|
]))
|
||||||
if server.settings.WebSocketsEnabled
|
if server.settings.WebSocketsEnabled
|
||||||
server.UseRouter(new Http.WebSocketMiddleware())
|
server.UseRouter(new Http.WebSocketMiddleware())
|
||||||
end if
|
end if
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import "pkg:/components/Web/WebServer/Http/HttpRouter.bs"
|
||||||
|
|
||||||
|
namespace Http
|
||||||
|
|
||||||
|
class CsrfMiddleware extends HttpRouter
|
||||||
|
private headerName
|
||||||
|
private exemptRoutePrefixes
|
||||||
|
|
||||||
|
function new(headerName as string, exemptRoutePrefixes as object)
|
||||||
|
super()
|
||||||
|
|
||||||
|
m.headerName = headerName
|
||||||
|
m.exemptRoutePrefixes = exemptRoutePrefixes
|
||||||
|
end function
|
||||||
|
|
||||||
|
@all("*")
|
||||||
|
function RequireHeader(context as object) as boolean
|
||||||
|
request = context.request
|
||||||
|
|
||||||
|
method = request.method
|
||||||
|
if method = "GET" or method = "HEAD" or method = "OPTIONS"
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
|
||||||
|
if request.headers[m.headerName] <> invalid
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
|
||||||
|
for each prefix in m.exemptRoutePrefixes
|
||||||
|
if request.route.StartsWith(prefix)
|
||||||
|
return false
|
||||||
|
end if
|
||||||
|
end for
|
||||||
|
|
||||||
|
context.response.Default(403, `Missing ${m.headerName} header`)
|
||||||
|
return true
|
||||||
|
end function
|
||||||
|
end class
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import "pkg:/components/Web/WebServer/Middleware/CsrfMiddleware.bs"
|
||||||
|
import "pkg:/source/tests/LoggingGlobals.bs"
|
||||||
|
|
||||||
|
namespace Tests
|
||||||
|
|
||||||
|
@suite
|
||||||
|
class CsrfMiddlewareTests extends Rooibos.BaseTestSuite
|
||||||
|
|
||||||
|
protected override function beforeEach()
|
||||||
|
Tests.SetUpLoggingGlobals()
|
||||||
|
m.middleware = new Http.CsrfMiddleware("X-Playlet", ["/dial/"])
|
||||||
|
end function
|
||||||
|
|
||||||
|
function Check(method as string, route as string, headers as object) as object
|
||||||
|
context = {
|
||||||
|
request: { method: method, route: route, headers: headers }
|
||||||
|
response: {
|
||||||
|
code: invalid
|
||||||
|
Default: function(code as integer, _text as string)
|
||||||
|
m.code = code
|
||||||
|
end function
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handled = m.middleware.RequireHeader(context)
|
||||||
|
return { handled: handled, code: context.response.code }
|
||||||
|
end function
|
||||||
|
|
||||||
|
@describe("CsrfMiddleware.RequireHeader")
|
||||||
|
|
||||||
|
@it("lets reads through without the header")
|
||||||
|
function _()
|
||||||
|
for each method in ["GET", "HEAD", "OPTIONS"]
|
||||||
|
m.assertFalse(m.Check(method, "/api/state", {}).handled)
|
||||||
|
end for
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("rejects writes without the header")
|
||||||
|
function _()
|
||||||
|
for each method in ["POST", "PUT", "DELETE"]
|
||||||
|
result = m.Check(method, "/api/playlet-lib-urls", {})
|
||||||
|
m.assertTrue(result.handled)
|
||||||
|
m.assertEqual(result.code, 403)
|
||||||
|
end for
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("lets writes through with the header, in any case")
|
||||||
|
function _()
|
||||||
|
m.assertFalse(m.Check("POST", "/api/queue", { "x-playlet": "1" }).handled)
|
||||||
|
end function
|
||||||
|
|
||||||
|
@it("lets writes to an exempt prefix through without the header")
|
||||||
|
function _()
|
||||||
|
m.assertFalse(m.Check("POST", "/dial/abc/YouTube", {}).handled)
|
||||||
|
end function
|
||||||
|
end class
|
||||||
|
|
||||||
|
end namespace
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { getHost } from "lib/Api/Host";
|
import { getHost } from "lib/Api/Host";
|
||||||
|
|
||||||
|
const CsrfHeader = "X-Playlet";
|
||||||
|
|
||||||
export class PlayletApi {
|
export class PlayletApi {
|
||||||
static host = () => `http://${getHost()}`
|
static host = () => `http://${getHost()}`
|
||||||
|
|
||||||
@@ -56,7 +58,7 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async saveUserPreference(key, value) {
|
static async saveUserPreference(key, value) {
|
||||||
const response = await this.putJson(`${PlayletApi.host()}/api/preferences`, { [key]: value });
|
const response = await PlayletApi.send("PUT", `${PlayletApi.host()}/api/preferences`, { [key]: value });
|
||||||
return await response;
|
return await response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,11 +68,11 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async activateProfile(profileId) {
|
static async activateProfile(profileId) {
|
||||||
await this.postJson(`${PlayletApi.host()}/api/profiles/activate`, { id: profileId });
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/profiles/activate`, { id: profileId });
|
||||||
}
|
}
|
||||||
|
|
||||||
static async logout(profileId) {
|
static async logout(profileId) {
|
||||||
return await fetch(`${PlayletApi.host()}/api/profiles?id=${profileId}`, { method: "DELETE" });
|
return await PlayletApi.send("DELETE", `${PlayletApi.host()}/api/profiles?id=${profileId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async playVideo(args) {
|
static async playVideo(args) {
|
||||||
@@ -90,7 +92,7 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue/play`, args);
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/queue/play`, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async playPlaylist(args) {
|
static async playPlaylist(args) {
|
||||||
@@ -98,7 +100,7 @@ export class PlayletApi {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue/play`, args);
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/queue/play`, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async queueVideo(args) {
|
static async queueVideo(args) {
|
||||||
@@ -118,14 +120,14 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue`, args);
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/queue`, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async queuePlaylist(args) {
|
static async queuePlaylist(args) {
|
||||||
if (!args.playlistId) {
|
if (!args.playlistId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue`, args);
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/queue`, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async openPlaylist(playlistId, continuationVideoId) {
|
static async openPlaylist(playlistId, continuationVideoId) {
|
||||||
@@ -152,16 +154,16 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async addSearchHistory(query: string) {
|
static async addSearchHistory(query: string) {
|
||||||
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/search-history`, { query });
|
const response = await PlayletApi.send("POST", `${PlayletApi.host()}/api/search-history`, { query });
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
static async clearSearchHistory() {
|
static async clearSearchHistory() {
|
||||||
return await fetch(`${PlayletApi.host()}/api/search-history`, { method: "DELETE" });
|
return await PlayletApi.send("DELETE", `${PlayletApi.host()}/api/search-history`);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async clearCache() {
|
static async clearCache() {
|
||||||
return await fetch(`${PlayletApi.host()}/api/cache`, { method: "DELETE" });
|
return await PlayletApi.send("DELETE", `${PlayletApi.host()}/api/cache`);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getDevicePoToken() {
|
static async getDevicePoToken() {
|
||||||
@@ -174,7 +176,7 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async sendPoToken(identity: string, poToken: string, mintedAt: number, expiresAt: number) {
|
static async sendPoToken(identity: string, poToken: string, mintedAt: number, expiresAt: number) {
|
||||||
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/innertube/potoken`, { identity, poToken, mintedAt, expiresAt });
|
const response = await PlayletApi.send("POST", `${PlayletApi.host()}/api/innertube/potoken`, { identity, poToken, mintedAt, expiresAt });
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = await response.text().catch(() => "");
|
const body = await response.text().catch(() => "");
|
||||||
throw new Error(`Device rejected poToken (HTTP ${response.status}): ${body}`);
|
throw new Error(`Device rejected poToken (HTTP ${response.status}): ${body}`);
|
||||||
@@ -182,7 +184,7 @@ export class PlayletApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async clearPoTokens() {
|
static async clearPoTokens() {
|
||||||
return await fetch(`${PlayletApi.host()}/api/innertube/potoken/all`, { method: "DELETE" });
|
return await PlayletApi.send("DELETE", `${PlayletApi.host()}/api/innertube/potoken/all`);
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getBookmarkFeeds() {
|
static async getBookmarkFeeds() {
|
||||||
@@ -236,29 +238,18 @@ export class PlayletApi {
|
|||||||
type: 'custom'
|
type: 'custom'
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
await PlayletApi.postJson(`${PlayletApi.host()}/api/playlet-lib-urls`, urls);
|
await PlayletApi.send("POST", `${PlayletApi.host()}/api/playlet-lib-urls`, urls);
|
||||||
} else {
|
} else {
|
||||||
return await fetch(`${PlayletApi.host()}/api/playlet-lib-urls`, { method: "DELETE" });
|
return await PlayletApi.send("DELETE", `${PlayletApi.host()}/api/playlet-lib-urls`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static postJson(url, payload) {
|
static send(method: "POST" | "PUT" | "DELETE", url: string, payload?: unknown) {
|
||||||
return fetch(url, {
|
const headers: Record<string, string> = { [CsrfHeader]: "1" };
|
||||||
headers: {
|
if (payload === undefined) {
|
||||||
'Content-Type': 'application/json'
|
return fetch(url, { method, headers });
|
||||||
},
|
}
|
||||||
method: "POST",
|
headers["Content-Type"] = "application/json";
|
||||||
body: JSON.stringify(payload)
|
return fetch(url, { method, headers, body: JSON.stringify(payload) });
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private static putJson(url, payload) {
|
|
||||||
return fetch(url, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify(payload)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { getHost } from "lib/Api/Host";
|
|
||||||
import { PlayletApi } from "lib/Api/PlayletApi";
|
import { PlayletApi } from "lib/Api/PlayletApi";
|
||||||
import { BotGuardClient, getChallenge } from "bgutils-js/botguard";
|
import { BotGuardClient, getChallenge } from "bgutils-js/botguard";
|
||||||
import { WebPoMinter } from "bgutils-js/webpo";
|
import { WebPoMinter } from "bgutils-js/webpo";
|
||||||
@@ -65,13 +64,7 @@ export class PoTokenMinter {
|
|||||||
CacheSeconds: -1,
|
CacheSeconds: -1,
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await fetch(`http://${getHost()}/api/innertube/proxy`, {
|
const response = await PlayletApi.send("POST", `${PlayletApi.host()}/api/innertube/proxy`, args);
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(args)
|
|
||||||
});
|
|
||||||
|
|
||||||
const responseData = await response.json();
|
const responseData = await response.json();
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ const fs = require('fs');
|
|||||||
const { ArgumentParser, BooleanOptionalAction } = require('argparse');
|
const { ArgumentParser, BooleanOptionalAction } = require('argparse');
|
||||||
const getEnvVars = require('./get-env-vars');
|
const getEnvVars = require('./get-env-vars');
|
||||||
|
|
||||||
|
const CsrfHeader = 'X-Playlet';
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const parser = new ArgumentParser({
|
const parser = new ArgumentParser({
|
||||||
description: 'Manage registry'
|
description: 'Manage registry'
|
||||||
@@ -46,6 +48,7 @@ const getEnvVars = require('./get-env-vars');
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
[CsrfHeader]: '1',
|
||||||
},
|
},
|
||||||
body: JSON.stringify(registry),
|
body: JSON.stringify(registry),
|
||||||
});
|
});
|
||||||
@@ -83,6 +86,9 @@ const getEnvVars = require('./get-env-vars');
|
|||||||
else if (clear) {
|
else if (clear) {
|
||||||
const response = await fetch(playletServer, {
|
const response = await fetch(playletServer, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
[CsrfHeader]: '1',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
Reference in new issue
Block a user