Lightpanda: the headless browser designed for AI and automation
webdriver: add cookie and viewport endpoints to http/bidi webdriver
Karl Seguin0909838d1103
diff --git a/src/browser/Viewport.zig b/src/browser/Viewport.zigindex 959021ebc..b4f58f2c2 100644--- a/src/browser/Viewport.zig+++ b/src/browser/Viewport.zig@@ -24,6 +24,19 @@ scale: f32 = 1.0, // CSS px to device px// window.screen dimensions; null means the same as the viewport.screen_width: ?u32 = null,screen_height: ?u32 = null,+orientation: ?Orientation = null,++pub const Orientation = struct {+ type: Type,+ angle: u16,++ pub const Type = enum {+ @"portrait-primary",+ @"portrait-secondary",+ @"landscape-primary",+ @"landscape-secondary",+ };+};pub const default = Viewport{.width = 1920,diff --git a/src/browser/webapi/Screen.zig b/src/browser/webapi/Screen.zigindex 4a9dddb06..09788874a 100644--- a/src/browser/webapi/Screen.zig+++ b/src/browser/webapi/Screen.zig@@ -90,6 +90,16 @@ pub const Orientation = struct {return self._proto;}+ pub fn getType(_: *const Orientation, frame: *Frame) []const u8 {+ const orientation = frame.page.getViewport().orientation orelse return "landscape-primary";+ return @tagName(orientation.type);+ }++ pub fn getAngle(_: *const Orientation, frame: *Frame) u16 {+ const orientation = frame.page.getViewport().orientation orelse return 0;+ return orientation.angle;+ }+pub const JsApi = struct {pub const bridge = js.Bridge(Orientation);@@ -99,7 +109,7 @@ pub const Orientation = struct {pub var class_id: bridge.ClassId = undefined;};- pub const angle = bridge.property(0, .{ .template = false });- pub const @"type" = bridge.property("landscape-primary", .{ .template = false });+ pub const angle = bridge.accessor(Orientation.getAngle, null, .{});+ pub const @"type" = bridge.accessor(Orientation.getType, null, .{});};};diff --git a/src/browser/webapi/storage/Cookie.zig b/src/browser/webapi/storage/Cookie.zigindex f3ccf19c2..789f58b0a 100644--- a/src/browser/webapi/storage/Cookie.zig+++ b/src/browser/webapi/storage/Cookie.zig@@ -339,6 +339,14 @@ pub fn parseDomain(arena: Allocator, url_: ?[:0]const u8, explicit_domain: ?[]cotry std.Uri.Component.percentEncode(&aw.writer, no_leading_dot, isHostChar);const owned_domain = toLower(aw.written());+ if (isIpLiteral(owned_domain[1..]) or (encoded_host != null and isIpLiteral(encoded_host.?))) {+ const host = encoded_host orelse return owned_domain[1..];+ if (std.mem.eql(u8, host, owned_domain[1..])) {+ return owned_domain[1..];+ }+ return error.InvalidDomain;+ }+if (std.mem.indexOfScalarPos(u8, owned_domain, 1, '.') == null and std.mem.eql(u8, "localhost", owned_domain[1..]) == false) {// can't set a cookie for a TLDreturn error.InvalidDomain;@@ -380,6 +388,11 @@ pub fn parseDomain(arena: Allocator, url_: ?[:0]const u8, explicit_domain: ?[]coreturn error.InvalidDomain;}+fn isIpLiteral(host: []const u8) bool {+ _ = std.Io.net.IpAddress.parseLiteral(host) catch return false;+ return true;+}+pub fn percentEncode(arena: Allocator, part: []const u8, comptime isValidChar: fn (u8) bool) ![]u8 {var aw = try std.Io.Writer.Allocating.initCapacity(arena, part.len);try std.Uri.Component.percentEncode(&aw.writer, part, isValidChar);@@ -1465,12 +1478,16 @@ test "Cookie: parse domain" {try expectAttribute(.{ .domain = ".lightpanda.io" }, "http://dev.lightpanda.io/", "b;domain=.lightpanda.io");try expectAttribute(.{ .domain = ".localhost" }, "http://localhost/", "b;domain=localhost");try expectAttribute(.{ .domain = ".localhost" }, "http://localhost/", "b;domain=.localhost");+ try expectAttribute(.{ .domain = "127.0.0.1" }, "http://127.0.0.1/", "b;domain=127.0.0.1");+ try expectAttribute(.{ .domain = "127.0.0.1" }, "http://127.0.0.1/", "b;domain=.127.0.0.1");try expectError(error.InvalidDomain, "http://lightpanda.io/", "b;domain=io");try expectError(error.InvalidDomain, "http://lightpanda.io/", "b;domain=.io");try expectError(error.InvalidDomain, "http://lightpanda.io/", "b;domain=other.lightpanda.io");try expectError(error.InvalidDomain, "http://lightpanda.io/", "b;domain=other.lightpanda.com");try expectError(error.InvalidDomain, "http://lightpanda.io/", "b;domain=other.example.com");+ try expectError(error.InvalidDomain, "http://127.0.0.1/", "b;domain=0.0.1");+ try expectError(error.InvalidDomain, "http://127.0.0.1/", "b;domain=127.0.0.2");try expectError(error.InvalidDomain, "http://attackerexample.com/", "b;domain=example.com");try expectError(error.InvalidDomain, "http://attackerexample.com/", "b;domain=.example.com");diff --git a/src/server/Server.zig b/src/server/Server.zigindex af2888694..3a1003f39 100644--- a/src/server/Server.zig+++ b/src/server/Server.zig@@ -1724,8 +1724,8 @@ test "server: bidi errors" {try c.bidiCommand("{\"id\":5,\"method\":\"session.over9000\"}");try assertBidiMessage(&c, .{ .type = "error", .id = 5, .@"error" = "unknown command", .message = "session.over9000" });- try c.bidiCommand("{\"id\":6,\"method\":\"storage.getCookies\"}");- try assertBidiMessage(&c, .{ .type = "error", .id = 6, .@"error" = "unknown command", .message = "storage.getCookies" });+ try c.bidiCommand("{\"id\":6,\"method\":\"network.addIntercept\"}");+ try assertBidiMessage(&c, .{ .type = "error", .id = 6, .@"error" = "unknown command", .message = "network.addIntercept" });try c.bidiCommand("{\"id\":7,\"method\":\"nodothere\"}");try assertBidiMessage(&c, .{ .type = "error", .id = 7, .@"error" = "unknown command", .message = "nodothere" });@@ -2609,6 +2609,83 @@ fn expectWebsocketContains(ws: *TestClient, expected: []const u8) !void {}}+test "server: HTTP cookies" {+ const session_id = try createHTTPSession("{\"capabilities\":{}}", false);+ defer deleteHTTPSession(&session_id, true) catch |err| @panic(@errorName(err));++ var c = try createTestClient();+ defer c.deinit();++ {+ const res = try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"a\",\"value\":\"1\"}}");+ try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 400 Bad Request\r\n"));+ try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"invalid cookie domain\"") != null);+ }++ const url = "http://127.0.0.1:9582/src/browser/tests/webdriver/elements.html";+ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/url", "{\"url\":\"" ++ url ++ "\"}")));++ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"a\",\"value\":\"1\",\"secure\":false}}")));+ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"b\",\"value\":\"2\",\"domain\":\"127.0.0.1\",\"httpOnly\":true,\"expiry\":4102444800,\"sameSite\":\"Strict\"}}")));+ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"c\",\"value\":\"3\",\"path\":\"/elsewhere\"}}")));+ {+ const res = try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"d\",\"value\":\"4\",\"domain\":\"example.com\"}}");+ try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 400 Bad Request\r\n"));+ try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"invalid cookie domain\"") != null);+ }+ {+ const res = try sessionCommand(&c, "POST", &session_id, "/cookie", "{\"cookie\":{\"name\":\"d\",\"value\":\"4\",\"sameSite\":\"None\"}}");+ try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 500 Internal Server Error\r\n"));+ try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"unable to set cookie\"") != null);+ }++ // c's path doesn't cover the document, so it isn't the document's+ const a_json = "{\"name\":\"a\",\"value\":\"1\",\"path\":\"/\",\"domain\":\"127.0.0.1\",\"secure\":false,\"httpOnly\":false,\"sameSite\":\"Lax\"}";+ const b_json = "{\"name\":\"b\",\"value\":\"2\",\"path\":\"/\",\"domain\":\"127.0.0.1\",\"secure\":false,\"httpOnly\":true,\"expiry\":4102444800,\"sameSite\":\"Strict\"}";+ try testing.expectEqual("{\"value\":[" ++ a_json ++ "," ++ b_json ++ "]}", responseBody(try sessionCommand(&c, "GET", &session_id, "/cookie", "")));+ try testing.expectEqual("{\"value\":" ++ b_json ++ "}", responseBody(try sessionCommand(&c, "GET", &session_id, "/cookie/b", "")));+ for ([_][]const u8{ "/cookie/c", "/cookie/nope" }) |path| {+ const res = try sessionCommand(&c, "GET", &session_id, path, "");+ try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 404 Not Found\r\n"));+ try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"no such cookie\"") != null);+ }++ // the page sees them, bar the HttpOnly one+ try testing.expectEqual("{\"value\":\"a=1\"}", try executeSync(&c, &session_id, "return document.cookie", "[]"));++ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "DELETE", &session_id, "/cookie/a", "")));+ try testing.expectEqual("{\"value\":[" ++ b_json ++ "]}", responseBody(try sessionCommand(&c, "GET", &session_id, "/cookie", "")));+ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "DELETE", &session_id, "/cookie", "")));+ try testing.expectEqual("{\"value\":[]}", responseBody(try sessionCommand(&c, "GET", &session_id, "/cookie", "")));+}++test "server: HTTP window rect" {+ const session_id = try createHTTPSession("{\"capabilities\":{}}", false);+ defer deleteHTTPSession(&session_id, true) catch |err| @panic(@errorName(err));++ var c = try createTestClient();+ defer c.deinit();++ try testing.expectEqual("{\"value\":{\"x\":0,\"y\":0,\"width\":1920,\"height\":1080}}", responseBody(try sessionCommand(&c, "GET", &session_id, "/window/rect", "")));++ const url = "http://127.0.0.1:9582/src/browser/tests/webdriver/elements.html";+ try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/url", "{\"url\":\"" ++ url ++ "\"}")));++ const small = "{\"value\":{\"x\":0,\"y\":0,\"width\":375,\"height\":812}}";+ try testing.expectEqual(small, responseBody(try sessionCommand(&c, "POST", &session_id, "/window/rect", "{\"x\":10,\"y\":10,\"width\":375,\"height\":812}")));+ try testing.expectEqual("{\"value\":\"375x812\"}", try executeSync(&c, &session_id, "return innerWidth + 'x' + innerHeight", "[]"));++ // a partial update keeps the rest+ try testing.expectEqual("{\"value\":{\"x\":0,\"y\":0,\"width\":400,\"height\":812}}", responseBody(try sessionCommand(&c, "POST", &session_id, "/window/rect", "{\"width\":400}")));++ for ([_][]const u8{ "/window/maximize", "/window/minimize", "/window/fullscreen" }) |path| {+ try testing.expectEqual("{\"value\":{\"x\":0,\"y\":0,\"width\":400,\"height\":812}}", responseBody(try sessionCommand(&c, "POST", &session_id, path, "{}")));+ }++ const res = try sessionCommand(&c, "POST", &session_id, "/window/rect", "{\"width\":1.5}");+ try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 400 Bad Request\r\n"));+}+test "server: HTTP command errors" {{var c = try createTestClient();diff --git a/src/server/bidi/BiDi.zig b/src/server/bidi/BiDi.zigindex 9724eed81..1347767b1 100644--- a/src/server/bidi/BiDi.zig+++ b/src/server/bidi/BiDi.zig@@ -331,6 +331,8 @@ pub fn onMessage(self: *BiDi, data: []const u8) anyerror!void {browser,browsingContext,input,+ storage,+ emulation,}, method[0..i]) orelse return unknownCommand(&cmd, method);// Only the session module is reachable without a session (it's what@@ -346,6 +348,8 @@ pub fn onMessage(self: *BiDi, data: []const u8) anyerror!void {.browser => @import("browser.zig").processMessage(&cmd, action),.browsingContext => @import("browsing_context.zig").processMessage(&cmd, action),.input => @import("input.zig").processMessage(&cmd, action),+ .storage => @import("storage.zig").processMessage(&cmd, action),+ .emulation => @import("emulation.zig").processMessage(&cmd, action),};result catch |err| {if (err == error.UnknownCommand and cmd.answered == false) {diff --git a/src/server/bidi/browsing_context.zig b/src/server/bidi/browsing_context.zigindex bc4b02d66..64d7062a1 100644--- a/src/server/bidi/browsing_context.zig+++ b/src/server/bidi/browsing_context.zig@@ -25,6 +25,7 @@ const js = @import("../../browser/js/js.zig");const URL = @import("../../browser/URL.zig");const Node = @import("../../browser/webapi/Node.zig");const Frame = @import("../../browser/Frame.zig");+const Viewport = @import("../../browser/Viewport.zig");const Selector = @import("../../browser/webapi/selector/Selector.zig");const xpath = @import("../../browser/xpath/Evaluator.zig");const XPathParser = @import("../../browser/xpath/Parser.zig");@@ -73,6 +74,7 @@ pub fn processMessage(cmd: *BiDi.Command, action: []const u8) !void {navigate,close,locateNodes,+ setViewport,}, action) orelse return error.UnknownCommand;switch (command) {@@ -81,6 +83,7 @@ pub fn processMessage(cmd: *BiDi.Command, action: []const u8) !void {.navigate => return bidiNavigate(cmd),.close => return close(cmd),.locateNodes => return locateNodes(cmd),+ .setViewport => return setViewport(cmd),}}@@ -496,6 +499,72 @@ fn appendNodes(remotes: *std.ArrayList(remote_value.Remote), arena: std.mem.Allo}}+fn setViewport(cmd: *BiDi.Command) !void {+ const p = try cmd.params(struct {+ context: ?[]const u8 = null,+ userContexts: ?[]const []const u8 = null,+ viewport: Setting(struct { width: u32, height: u32 }) = .keep,+ devicePixelRatio: Setting(f32) = .keep,+ });++ const bidi = cmd.bidi;+ if ((p.context == null) == (p.userContexts == null)) {+ return cmd.sendError("invalid argument", "exactly one of context and userContexts is required");+ }+ if (p.context) |context| {+ _ = (try requireContext(cmd, context)) orelse return;+ }+ if (p.userContexts) |user_contexts| {+ for (user_contexts) |user_context| {+ if (std.mem.eql(u8, user_context, bidi.user_context.id()) == false) {+ return cmd.sendError("no such user context", "unknown user context");+ }+ }+ }++ var viewport = bidi.browser.getViewport();+ switch (p.viewport) {+ .keep => {},+ .reset => {+ viewport.width = Viewport.default.width;+ viewport.height = Viewport.default.height;+ },+ .set => |size| {+ if (size.width == 0 or size.height == 0) {+ return cmd.sendError("invalid argument", "viewport dimensions must be positive");+ }+ viewport.width = size.width;+ viewport.height = size.height;+ },+ }+ switch (p.devicePixelRatio) {+ .keep => {},+ .reset => viewport.scale = Viewport.default.scale,+ .set => |scale| {+ if (scale <= 0) {+ return cmd.sendError("invalid argument", "devicePixelRatio must be positive");+ }+ viewport.scale = scale;+ },+ }+ bidi.browser.setViewportOverride(viewport);+ return cmd.sendDone();+}++// A parameter that's left alone when absent, and reset to its default by null.+fn Setting(comptime T: type) type {+ return union(enum) {+ keep,+ reset,+ set: T,++ pub fn jsonParse(arena: std.mem.Allocator, source: anytype, opts: std.json.ParseOptions) !@This() {+ const value = try std.json.innerParse(?T, arena, source, opts);+ return if (value) |v| .{ .set = v } else .reset;+ }+ };+}+pub fn requireContext(cmd: *BiDi.Command, context: []const u8) !?*Context {if (cmd.bidi.browsing_context) |*ctx| {if (std.mem.eql(u8, &ctx.id, context)) {@@ -842,3 +911,48 @@ test "bidi.browsing_context: window realm lifecycle" {try ctx.expectSentEvent("script.realmCreated", .{ .realm = realm2, .type = "window", .context = context_id, .origin = "http://127.0.0.1:9582" });try ctx.expectSentResult(.{ .navigation = &bc.navigation_id }, .{ .id = 3 });}++test "bidi.browsing_context: setViewport" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "browsingContext.setViewport",+ .params = .{ .context = context_id, .viewport = .{ .width = 375, .height = 812 }, .devicePixelRatio = 3 },+ });+ try ctx.expectSentResult(null, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{ .expression = "`${innerWidth}x${innerHeight}@${devicePixelRatio}`", .awaitPromise = false, .target = .{ .context = context_id } },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "string", .value = "375x812@3" } }, .{ .id = 2 });++ // an absent field is kept, a null one is reset+ try ctx.processMessage(.{+ .id = 3,+ .method = "browsingContext.setViewport",+ .params = .{ .userContexts = .{"default"}, .viewport = null },+ });+ try ctx.expectSentResult(null, .{ .id = 3 });+ const viewport = ctx.bidi().browser.getViewport();+ try testing.expectEqual(Viewport.default.width, viewport.width);+ try testing.expectEqual(Viewport.default.height, viewport.height);+ try testing.expectEqual(3, viewport.scale);++ try ctx.processMessage(.{ .id = 4, .method = "browsingContext.setViewport", .params = .{ .viewport = null } });+ try ctx.expectSentError("invalid argument", null, .{ .id = 4 });+ try ctx.processMessage(.{ .id = 5, .method = "browsingContext.setViewport", .params = .{ .context = "nope" } });+ try ctx.expectSentError("no such frame", null, .{ .id = 5 });+ try ctx.processMessage(.{ .id = 6, .method = "browsingContext.setViewport", .params = .{ .userContexts = .{"nope"} } });+ try ctx.expectSentError("no such user context", null, .{ .id = 6 });+ try ctx.processMessage(.{+ .id = 7,+ .method = "browsingContext.setViewport",+ .params = .{ .context = context_id, .viewport = .{ .width = 0, .height = 10 } },+ });+ try ctx.expectSentError("invalid argument", null, .{ .id = 7 });+}diff --git a/src/server/bidi/emulation.zig b/src/server/bidi/emulation.zignew file mode 100644index 000000000..585171373--- /dev/null+++ b/src/server/bidi/emulation.zig@@ -0,0 +1,124 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");++const Viewport = @import("../../browser/Viewport.zig");++const BiDi = @import("BiDi.zig");+const browsing_context = @import("browsing_context.zig");++pub fn processMessage(cmd: *BiDi.Command, action: []const u8) !void {+ const command = std.meta.stringToEnum(enum {+ setScreenOrientationOverride,+ }, action) orelse return error.UnknownCommand;++ switch (command) {+ .setScreenOrientationOverride => return setScreenOrientationOverride(cmd),+ }+}++// Like the viewport, the orientation belongs to the Browser.+fn setScreenOrientationOverride(cmd: *BiDi.Command) !void {+ const p = try cmd.params(struct {+ screenOrientation: ?struct {+ natural: enum { portrait, landscape },+ type: Viewport.Orientation.Type,+ },+ contexts: ?[]const []const u8 = null,+ userContexts: ?[]const []const u8 = null,+ });+ if ((try requireTargets(cmd, p.contexts, p.userContexts)) == false) {+ return;+ }++ const browser = &cmd.bidi.browser;+ var viewport = browser.getViewport();+ viewport.orientation = if (p.screenOrientation) |o| .{+ .type = o.type,+ // quarter turns away from the natural orientation's primary+ .angle = switch (o.natural) {+ .portrait => switch (o.type) {+ .@"portrait-primary" => 0,+ .@"landscape-primary" => 90,+ .@"portrait-secondary" => 180,+ .@"landscape-secondary" => 270,+ },+ .landscape => switch (o.type) {+ .@"landscape-primary" => 0,+ .@"portrait-primary" => 90,+ .@"landscape-secondary" => 180,+ .@"portrait-secondary" => 270,+ },+ },+ } else null;+ browser.setViewportOverride(viewport);+ return cmd.sendDone();+}++fn requireTargets(cmd: *BiDi.Command, contexts: ?[]const []const u8, user_contexts: ?[]const []const u8) !bool {+ if (contexts != null and user_contexts != null) {+ try cmd.sendError("invalid argument", "contexts and userContexts are mutually exclusive");+ return false;+ }+ for (contexts orelse &.{}) |context| {+ _ = (try browsing_context.requireContext(cmd, context)) orelse return false;+ }+ for (user_contexts orelse &.{}) |user_context| {+ if (std.mem.eql(u8, user_context, cmd.bidi.user_context.id()) == false) {+ try cmd.sendError("no such user context", "unknown user context");+ return false;+ }+ }+ return true;+}++const testing = @import("testing.zig");+test "bidi.emulation: setScreenOrientationOverride" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "emulation.setScreenOrientationOverride",+ .params = .{ .contexts = .{context_id}, .screenOrientation = .{ .natural = "landscape", .type = "portrait-primary" } },+ });+ try ctx.expectSentResult(null, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{ .expression = "`${screen.orientation.type}@${screen.orientation.angle}`", .awaitPromise = false, .target = .{ .context = context_id } },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "string", .value = "portrait-primary@90" } }, .{ .id = 2 });++ // null clears it+ try ctx.processMessage(.{ .id = 3, .method = "emulation.setScreenOrientationOverride", .params = .{ .screenOrientation = null } });+ try ctx.expectSentResult(null, .{ .id = 3 });+ try testing.expectEqual(null, ctx.bidi().browser.getViewport().orientation);++ try ctx.processMessage(.{ .id = 4, .method = "emulation.setScreenOrientationOverride", .params = .{ .screenOrientation = null, .contexts = .{"nope"} } });+ try ctx.expectSentError("no such frame", null, .{ .id = 4 });+ try ctx.processMessage(.{+ .id = 5,+ .method = "emulation.setScreenOrientationOverride",+ .params = .{ .screenOrientation = .{ .natural = "portrait", .type = "sideways" } },+ });+ try ctx.expectSentError("invalid argument", null, .{ .id = 5 });+}diff --git a/src/server/bidi/http_command.zig b/src/server/bidi/http_command.zigindex a59e80921..201bf24cf 100644--- a/src/server/bidi/http_command.zig+++ b/src/server/bidi/http_command.zig@@ -26,12 +26,14 @@ const lp = @import("lightpanda");const js = @import("../../browser/js/js.zig");const Frame = @import("../../browser/Frame.zig");const Node = @import("../../browser/webapi/Node.zig");+const Viewport = @import("../../browser/Viewport.zig");const NodeRegistry = @import("../../NodeRegistry.zig");const Method = @import("../http.zig").Connection.Method;const BiDi = @import("BiDi.zig");const input = @import("input.zig");+const storage = @import("storage.zig");const execute = @import("execute.zig");const remote_value = @import("remote_value.zig");const browsing_context = @import("browsing_context.zig");@@ -49,6 +51,11 @@ pub const Command = union(enum) {get_title,get_window_handle,get_window_handles,+ get_window_rect,+ set_window_rect: SetWindowRect,+ maximize_window,+ minimize_window,+ fullscreen_window,get_page_source,take_screenshot,perform_actions: PerformActions,@@ -73,6 +80,11 @@ pub const Command = union(enum) {execute_async_script: execute.Script,get_timeouts,set_timeouts: SetTimeouts,+ get_all_cookies,+ get_named_cookie: CookieName,+ add_cookie: AddCookie,+ delete_cookie: CookieName,+ delete_all_cookies,};// A command's path parameters are its leading fields (see `parse`); the rest@@ -133,6 +145,7 @@ const Route = struct {};fn init(comptime method: Method, comptime path: []const u8, comptime command: std.meta.Tag(Command)) Route {+ @setEvalBranchQuota(10_000);comptime var segments: []const Segment = &.{};comptime var parameters: []const []const u8 = &.{};var it = std.mem.splitScalar(u8, path, '/');@@ -195,7 +208,7 @@ const Route = struct {var value: T = undefined;inline for (self.parameters, 0..) |parameter, i| {// path is the connection's read buffer, reused once the request is parked- @field(value, parameter) = try arena.dupe(u8, captured[i]);+ @field(value, parameter) = std.Uri.percentDecodeInPlace(try arena.dupe(u8, captured[i]));}const parsed = try parseBody(Body(T, self.parameters), arena, body);inline for (@typeInfo(@TypeOf(parsed)).@"struct".fields) |field| {@@ -213,6 +226,11 @@ const routes = [_]Route{.init(.GET, "/title", .get_title),.init(.GET, "/window", .get_window_handle),.init(.GET, "/window/handles", .get_window_handles),+ .init(.GET, "/window/rect", .get_window_rect),+ .init(.POST, "/window/rect", .set_window_rect),+ .init(.POST, "/window/maximize", .maximize_window),+ .init(.POST, "/window/minimize", .minimize_window),+ .init(.POST, "/window/fullscreen", .fullscreen_window),.init(.GET, "/source", .get_page_source),.init(.GET, "/screenshot", .take_screenshot),.init(.POST, "/actions", .perform_actions),@@ -237,6 +255,11 @@ const routes = [_]Route{.init(.POST, "/execute/async", .execute_async_script),.init(.GET, "/timeouts", .get_timeouts),.init(.POST, "/timeouts", .set_timeouts),+ .init(.GET, "/cookie", .get_all_cookies),+ .init(.POST, "/cookie", .add_cookie),+ .init(.DELETE, "/cookie", .delete_all_cookies),+ .init(.GET, "/cookie/{name}", .get_named_cookie),+ .init(.DELETE, "/cookie/{name}", .delete_cookie),};pub const ParseError = error{@@ -315,6 +338,8 @@ pub fn process(cmd: *BiDi.Command) !void {.get_title => return getTitle(cmd),.get_window_handle => return getWindowHandle(cmd),.get_window_handles => return getWindowHandles(cmd),+ .get_window_rect, .maximize_window, .minimize_window, .fullscreen_window => return getWindowRect(cmd),+ .set_window_rect => |p| return setWindowRect(cmd, p),.get_page_source => return getPageSource(cmd),.take_screenshot => return takeScreenshot(cmd),.perform_actions => |p| return performActions(cmd, p),@@ -339,6 +364,11 @@ pub fn process(cmd: *BiDi.Command) !void {.execute_async_script => |p| return executeScript(cmd, p, .async),.get_timeouts => return getTimeouts(cmd),.set_timeouts => |p| return setTimeouts(cmd, p),+ .get_all_cookies => return getAllCookies(cmd),+ .get_named_cookie => |p| return getNamedCookie(cmd, p),+ .add_cookie => |p| return addCookie(cmd, p),+ .delete_cookie => |p| return deleteCookies(cmd, p.name),+ .delete_all_cookies => return deleteCookies(cmd, null),}}@@ -381,6 +411,37 @@ fn getWindowHandles(cmd: *BiDi.Command) !void {return cmd.sendResult(&[_][]const u8{&ctx.id});}+// GET /session/{id}/window/rect+fn getWindowRect(cmd: *BiDi.Command) !void {+ _ = (try currentContext(cmd)) orelse return;+ return cmd.sendResult(windowRect(cmd.bidi.browser.getViewport()));+}++fn windowRect(viewport: Viewport) struct { x: i32, y: i32, width: u32, height: u32 } {+ return .{ .x = 0, .y = 0, .width = viewport.width, .height = viewport.height };+}++// POST /session/{id}/window/rect.+pub const SetWindowRect = struct {+ x: ?i32 = null,+ y: ?i32 = null,+ width: ?u31 = null,+ height: ?u31 = null,+};+fn setWindowRect(cmd: *BiDi.Command, p: SetWindowRect) !void {+ _ = (try currentContext(cmd)) orelse return;+ const browser = &cmd.bidi.browser;+ var viewport = browser.getViewport();+ if (p.width) |width| {+ viewport.width = @max(width, 1);+ }+ if (p.height) |height| {+ viewport.height = @max(height, 1);+ }+ browser.setViewportOverride(viewport);+ return cmd.sendResult(windowRect(viewport));+}+// GET /session/{id}/sourcefn getPageSource(cmd: *BiDi.Command) !void {const frame = (try currentFrame(cmd)) orelse return;@@ -756,6 +817,90 @@ fn setTimeouts(cmd: *BiDi.Command, p: SetTimeouts) !void {return cmd.sendDone();}+// GET /session/{id}/cookie+fn getAllCookies(cmd: *BiDi.Command) !void {+ const frame = (try currentFrame(cmd)) orelse return;+ const jar = &cmd.bidi.user_context.session.cookie_jar;+ jar.removeExpired(null);++ const associated: storage.Associated = .init(frame.url, null);+ var cookies: std.ArrayList(storage.HttpCookie) = .empty;+ for (jar.cookies.items) |*cookie| {+ if (associated.has(cookie)) {+ try cookies.append(cmd.arena, .{ .cookie = cookie });+ }+ }+ return cmd.sendResult(cookies.items);+}++// GET /session/{id}/cookie/{name}+pub const CookieName = struct {+ name: []const u8,+};+fn getNamedCookie(cmd: *BiDi.Command, p: CookieName) !void {+ const frame = (try currentFrame(cmd)) orelse return;+ const jar = &cmd.bidi.user_context.session.cookie_jar;+ jar.removeExpired(null);++ const associated: storage.Associated = .init(frame.url, p.name);+ for (jar.cookies.items) |*cookie| {+ if (associated.has(cookie)) {+ return cmd.sendResult(storage.HttpCookie{ .cookie = cookie });+ }+ }+ return cmd.sendError("no such cookie", "no cookie with that name");+}++// POST /session/{id}/cookie+pub const AddCookie = struct {+ cookie: struct {+ name: []const u8,+ value: []const u8,+ path: ?[]const u8 = null,+ domain: ?[]const u8 = null,+ secure: bool = false,+ httpOnly: bool = false,+ expiry: ?u64 = null,+ sameSite: ?enum { Strict, Lax, None } = null,+ },+};+fn addCookie(cmd: *BiDi.Command, p: AddCookie) !void {+ const frame = (try currentFrame(cmd)) orelse return;+ if (std.mem.startsWith(u8, frame.url, "http:") == false and std.mem.startsWith(u8, frame.url, "https:") == false) {+ return cmd.sendError("invalid cookie domain", "the current document can't have cookies");+ }++ const c = p.cookie;+ const spec: storage.Spec = .{+ .name = c.name,+ .value = c.value,+ .domain = c.domain,+ .path = c.path,+ .secure = c.secure,+ .http_only = c.httpOnly,+ .expiry = c.expiry,+ .same_site = if (c.sameSite) |same_site| switch (same_site) {+ .Strict => .strict,+ .Lax => .lax,+ .None => .none,+ } else null,+ };+ storage.add(&cmd.bidi.user_context.session.cookie_jar, spec, frame.url) catch |err| switch (err) {+ error.OutOfMemory => return err,+ error.InvalidDomain => return cmd.sendError("invalid cookie domain", "the domain doesn't match the current document"),+ error.UnableToSetCookie => return cmd.sendError("unable to set cookie", "the cookie was rejected"),+ };+ return cmd.sendDone();+}++// DELETE /session/{id}/cookie/{name}, DELETE /session/{id}/cookie+fn deleteCookies(cmd: *BiDi.Command, name: ?[]const u8) !void {+ const frame = (try currentFrame(cmd)) orelse return;+ const associated: storage.Associated = .init(frame.url, name);+ storage.remove(&cmd.bidi.user_context.session.cookie_jar, &associated, storage.Associated.has);+ return cmd.sendDone();+}+// {"element-6066-…": "<sharedId>"}: a WebDriver element reference is the// node registry's id, the same one BiDi hands out.pub const Reference = struct {@@ -928,6 +1073,29 @@ test "bidi.http_command: parse" {try testing.expectEqual("7", (try parse(arena, .POST, "/element/7/clear", "{}")).element_clear.id);try testing.expectError(error.InvalidArgument, parse(arena, .POST, "/element/7/value", "{}"));+ {+ const command = try parse(arena, .POST, "/cookie", "{\"cookie\":{\"name\":\"a\",\"value\":\"1\",\"secure\":false,\"sameSite\":\"Lax\"}}");+ try testing.expectEqual("a", command.add_cookie.cookie.name);+ try testing.expectEqual(.Lax, command.add_cookie.cookie.sameSite.?);+ try testing.expectEqual(null, command.add_cookie.cookie.expiry);+ }+ try testing.expectError(error.InvalidArgument, parse(arena, .POST, "/cookie", "{\"cookie\":{\"name\":\"a\",\"value\":\"1\",\"sameSite\":\"lax\"}}"));+ try testing.expectError(error.InvalidArgument, parse(arena, .POST, "/cookie", "{\"name\":\"a\",\"value\":\"1\"}"));+ try testing.expect(try parse(arena, .GET, "/cookie", "") == .get_all_cookies);+ try testing.expect(try parse(arena, .DELETE, "/cookie", "") == .delete_all_cookies);+ // path parameters are percent-decoded+ try testing.expectEqual("a b", (try parse(arena, .GET, "/cookie/a%20b", "")).get_named_cookie.name);+ try testing.expectEqual("a", (try parse(arena, .DELETE, "/cookie/a", "")).delete_cookie.name);++ try testing.expect(try parse(arena, .GET, "/window/rect", "") == .get_window_rect);+ try testing.expect(try parse(arena, .POST, "/window/maximize", "{}") == .maximize_window);+ {+ const command = try parse(arena, .POST, "/window/rect", "{\"width\":375,\"height\":812,\"x\":null}");+ try testing.expectEqual(375, command.set_window_rect.width.?);+ try testing.expectEqual(null, command.set_window_rect.x);+ }+ try testing.expectError(error.InvalidArgument, parse(arena, .POST, "/window/rect", "{\"width\":-1}"));+try testing.expect(try parse(arena, .GET, "/timeouts", "") == .get_timeouts);try testing.expectError(error.InvalidArgument, parse(arena, .POST, "/execute/sync", "{}"));diff --git a/src/server/bidi/storage.zig b/src/server/bidi/storage.zignew file mode 100644index 000000000..18062d18e--- /dev/null+++ b/src/server/bidi/storage.zig@@ -0,0 +1,476 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++// Cookies: the storage module, and the core the HTTP session's /cookie+// commands share with it. There's one cookie jar per user context and no+// partitioning by site, so a partition resolves to the current user context.++const std = @import("std");+const lp = @import("lightpanda");++const Cookie = @import("../../browser/webapi/storage/Cookie.zig");++const BiDi = @import("BiDi.zig");+const browsing_context = @import("browsing_context.zig");++const Allocator = std.mem.Allocator;++pub fn processMessage(cmd: *BiDi.Command, action: []const u8) !void {+ const command = std.meta.stringToEnum(enum {+ getCookies,+ setCookie,+ deleteCookies,+ }, action) orelse return error.UnknownCommand;++ switch (command) {+ .getCookies => return getCookies(cmd),+ .setCookie => return setCookie(cmd),+ .deleteCookies => return deleteCookies(cmd),+ }+}++// A cookie as a driver hands it over.+pub const Spec = struct {+ name: []const u8,+ value: []const u8,+ domain: ?[]const u8 = null,+ path: ?[]const u8 = null,+ secure: bool = false,+ http_only: bool = false,+ expiry: ?u64 = null, // seconds since the epoch, null for a session cookie+ same_site: ?Cookie.SameSite = null, // null: unspecified, Lax by default+};++pub fn add(jar: *Cookie.Jar, spec: Spec, url: ?[:0]const u8) !void {+ const cookie: Cookie = blk: {+ if (isValidPart(spec.name, "=;") == false or isValidPart(spec.value, ";") == false) {+ return error.UnableToSetCookie;+ }+ if (spec.same_site == .none and spec.secure == false) {+ // the store refuses SameSite=None without Secure, as Set-Cookie does+ return error.UnableToSetCookie;+ }++ var arena = std.heap.ArenaAllocator.init(jar.allocator);+ errdefer arena.deinit();+ const a = arena.allocator();++ // Allocate before the struct literal copies `arena` into the result.+ const name = try a.dupe(u8, spec.name);+ const value = try a.dupe(u8, spec.value);+ const domain = Cookie.parseDomain(a, url, spec.domain) catch |err| switch (err) {+ error.OutOfMemory => return error.OutOfMemory,+ else => return error.InvalidDomain,+ };+ const path = Cookie.parsePath(a, null, spec.path) catch return error.OutOfMemory;++ break :blk .{+ .arena = arena,+ .name = name,+ .value = value,+ .domain = domain,+ .path = path,+ .expires = if (spec.expiry) |expiry| @floatFromInt(expiry) else null,+ .secure = spec.secure,+ .http_only = spec.http_only,+ .same_site = spec.same_site orelse .lax,+ .same_site_default = spec.same_site == null,+ };+ };++ jar.add(cookie, lp.datetime.timestamp(.real), true) catch |err| switch (err) {+ error.OutOfMemory => return error.OutOfMemory,+ else => return error.UnableToSetCookie,+ };+}++// What Cookie.parse accepts, minus the separators a Cookie header would+// read differently.+fn isValidPart(part: []const u8, comptime separators: []const u8) bool {+ for (part) |c| {+ if ((c < 32 and c != '\t') or c > 126) {+ return false;+ }+ if (std.mem.indexOfScalar(u8, separators, c) != null) {+ return false;+ }+ }+ return true;+}++// The cookies a navigation to `url` would carry, HttpOnly ones included:+// what the HTTP session's cookie commands see and delete. Optionally, only+// those called `name`.+pub const Associated = struct {+ url: Cookie.PreparedUri,+ name: ?[]const u8,++ pub fn init(url: [:0]const u8, name: ?[]const u8) Associated {+ return .{ .url = .init(url), .name = name };+ }++ pub fn has(self: *const Associated, cookie: *const Cookie) bool {+ if (self.name) |name| {+ if (std.mem.eql(u8, name, cookie.name) == false) {+ return false;+ }+ }+ return cookie.appliesTo(&self.url, .{ .same_site = true, .is_http = true, .kind = .navigation });+ }+};++// Removes the cookies `matches` accepts, `context` being its first argument.+pub fn remove(jar: *Cookie.Jar, context: anytype, comptime matches: fn (@TypeOf(context), *const Cookie) bool) void {+ const cookies = &jar.cookies;+ var i = cookies.items.len;+ while (i > 0) {+ i -= 1;+ if (matches(context, &cookies.items[i])) {+ cookies.swapRemove(i).deinit();+ }+ }+}++// A cookie in the HTTP session's shape.+pub const HttpCookie = struct {+ cookie: *const Cookie,++ pub fn jsonStringify(self: HttpCookie, jws: anytype) !void {+ const cookie = self.cookie;+ try jws.beginObject();+ try jws.objectField("name");+ try jws.write(cookie.name);+ try jws.objectField("value");+ try jws.write(cookie.value);+ try jws.objectField("path");+ try jws.write(cookie.path);+ try jws.objectField("domain");+ try jws.write(cookie.domain);+ try jws.objectField("secure");+ try jws.write(cookie.secure);+ try jws.objectField("httpOnly");+ try jws.write(cookie.http_only);+ if (cookie.expires) |expires| {+ try jws.objectField("expiry");+ try jws.write(@as(i64, @intFromFloat(expires)));+ }+ try jws.objectField("sameSite");+ try jws.write(switch (cookie.same_site) {+ .strict => "Strict",+ .lax => "Lax",+ .none => "None",+ });+ try jws.endObject();+ }+};++// A network.Cookie.+const BiDiCookie = struct {+ cookie: *const Cookie,++ pub fn jsonStringify(self: BiDiCookie, jws: anytype) !void {+ const cookie = self.cookie;+ try jws.beginObject();+ try jws.objectField("name");+ try jws.write(cookie.name);+ try jws.objectField("value");+ try jws.write(.{ .type = "string", .value = cookie.value });+ try jws.objectField("domain");+ try jws.write(cookie.domain);+ try jws.objectField("path");+ try jws.write(cookie.path);+ try jws.objectField("size");+ try jws.write(cookie.name.len + cookie.value.len);+ try jws.objectField("httpOnly");+ try jws.write(cookie.http_only);+ try jws.objectField("secure");+ try jws.write(cookie.secure);+ try jws.objectField("sameSite");+ try jws.write(@tagName(sameSite(cookie)));+ if (cookie.expires) |expires| {+ try jws.objectField("expiry");+ try jws.write(@as(i64, @intFromFloat(expires)));+ }+ try jws.endObject();+ }+};++const SameSite = enum { strict, lax, none, default };++fn sameSite(cookie: *const Cookie) SameSite {+ if (cookie.same_site_default) {+ return .default;+ }+ return switch (cookie.same_site) {+ inline else => |tag| @field(SameSite, @tagName(tag)),+ };+}++// network.BytesValue+const BytesValue = struct {+ type: enum { string, base64 },+ value: []const u8,++ fn decode(self: BytesValue, arena: Allocator) ![]const u8 {+ switch (self.type) {+ .string => return self.value,+ .base64 => {+ const decoder = std.base64.standard.Decoder;+ const buf = try arena.alloc(u8, try decoder.calcSizeForSlice(self.value));+ try decoder.decode(buf, self.value);+ return buf;+ },+ }+ }+};++const PartitionDescriptor = struct {+ type: enum { context, storageKey },+ context: ?[]const u8 = null,+ userContext: ?[]const u8 = null,+ sourceOrigin: ?[]const u8 = null,+};++// The partition key of the user context `partition` names. Answers the+// command and returns null when it names something we don't have.+fn resolvePartition(cmd: *BiDi.Command, partition: ?PartitionDescriptor) !?[]const u8 {+ const bidi = cmd.bidi;+ const current = bidi.user_context.id();++ const p = partition orelse return try requireUserContext(cmd, "default");+ switch (p.type) {+ .context => {+ const context = p.context orelse {+ try cmd.sendError("invalid argument", "partition.context is required");+ return null;+ };+ _ = (try browsing_context.requireContext(cmd, context)) orelse return null;+ return current;+ },+ .storageKey => return try requireUserContext(cmd, p.userContext orelse "default"),+ }+}++fn requireUserContext(cmd: *BiDi.Command, id: []const u8) !?[]const u8 {+ const current = cmd.bidi.user_context.id();+ if (std.mem.eql(u8, id, current)) {+ return current;+ }+ if (std.mem.eql(u8, id, "default")) {+ // replaced by the one createUserContext made, which has the jar+ try cmd.sendError("unsupported operation", "only the current user context's cookies are reachable");+ return null;+ }+ try cmd.sendError("no such user context", "unknown user context");+ return null;+}++// storage.CookieFilter: a cookie matches when every field given is equal.+const Filter = struct {+ name: ?[]const u8 = null,+ value: ?BytesValue = null,+ domain: ?[]const u8 = null,+ path: ?[]const u8 = null,+ size: ?u64 = null,+ httpOnly: ?bool = null,+ secure: ?bool = null,+ sameSite: ?SameSite = null,+ expiry: ?u64 = null,++ // so that `matches` compares strings+ fn decode(self: *Filter, arena: Allocator) !void {+ if (self.value) |value| {+ self.value = .{ .type = .string, .value = try value.decode(arena) };+ }+ }++ fn matches(self: *const Filter, cookie: *const Cookie) bool {+ if (self.name) |name| if (std.mem.eql(u8, name, cookie.name) == false) return false;+ if (self.value) |value| if (std.mem.eql(u8, value.value, cookie.value) == false) return false;+ if (self.domain) |domain| if (std.mem.eql(u8, domain, cookie.domain) == false) return false;+ if (self.path) |path| if (std.mem.eql(u8, path, cookie.path) == false) return false;+ if (self.size) |size| if (size != cookie.name.len + cookie.value.len) return false;+ if (self.httpOnly) |http_only| if (http_only != cookie.http_only) return false;+ if (self.secure) |secure| if (secure != cookie.secure) return false;+ if (self.sameSite) |same_site| if (same_site != sameSite(cookie)) return false;+ if (self.expiry) |expiry| {+ const expires = cookie.expires orelse return false;+ if (@as(f64, @floatFromInt(expiry)) != expires) return false;+ }+ return true;+ }+};++fn getCookies(cmd: *BiDi.Command) !void {+ const p = try cmd.params(struct {+ filter: Filter = .{},+ partition: ?PartitionDescriptor = null,+ });+ const user_context = (try resolvePartition(cmd, p.partition)) orelse return;++ var filter = p.filter;+ filter.decode(cmd.arena) catch return cmd.sendError("invalid argument", "invalid filter.value");++ const jar = &cmd.bidi.user_context.session.cookie_jar;+ jar.removeExpired(null);++ var cookies: std.ArrayList(BiDiCookie) = .empty;+ for (jar.cookies.items) |*cookie| {+ if (filter.matches(cookie)) {+ try cookies.append(cmd.arena, .{ .cookie = cookie });+ }+ }+ return cmd.sendResult(.{+ .cookies = cookies.items,+ .partitionKey = .{ .userContext = user_context },+ });+}++fn setCookie(cmd: *BiDi.Command) !void {+ const p = try cmd.params(struct {+ cookie: struct {+ name: []const u8,+ value: BytesValue,+ domain: []const u8,+ path: ?[]const u8 = null,+ httpOnly: bool = false,+ secure: bool = false,+ sameSite: ?SameSite = null,+ expiry: ?u64 = null,+ },+ partition: ?PartitionDescriptor = null,+ });+ const user_context = (try resolvePartition(cmd, p.partition)) orelse return;++ const c = p.cookie;+ const value = c.value.decode(cmd.arena) catch return cmd.sendError("invalid argument", "invalid cookie.value");+ const spec: Spec = .{+ .name = c.name,+ .value = value,+ .domain = c.domain,+ .path = c.path,+ .secure = c.secure,+ .http_only = c.httpOnly,+ .expiry = c.expiry,+ .same_site = if (c.sameSite) |same_site| switch (same_site) {+ .default => null,+ inline else => |tag| @field(Cookie.SameSite, @tagName(tag)),+ } else null,+ };++ add(&cmd.bidi.user_context.session.cookie_jar, spec, null) catch |err| switch (err) {+ error.OutOfMemory => return err,+ error.InvalidDomain, error.UnableToSetCookie => return cmd.sendError("unable to set cookie", @errorName(err)),+ };+ return cmd.sendResult(.{ .partitionKey = .{ .userContext = user_context } });+}++fn deleteCookies(cmd: *BiDi.Command) !void {+ const p = try cmd.params(struct {+ filter: Filter = .{},+ partition: ?PartitionDescriptor = null,+ });+ const user_context = (try resolvePartition(cmd, p.partition)) orelse return;++ var filter = p.filter;+ filter.decode(cmd.arena) catch return cmd.sendError("invalid argument", "invalid filter.value");++ remove(&cmd.bidi.user_context.session.cookie_jar, &filter, Filter.matches);+ return cmd.sendResult(.{ .partitionKey = .{ .userContext = user_context } });+}++const testing = @import("testing.zig");+test "bidi.storage: cookies" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const context_id = try ctx.createContext(.{});++ try ctx.processMessage(.{+ .id = 1,+ .method = "storage.setCookie",+ .params = .{ .cookie = .{+ .name = "a",+ .value = .{ .type = "string", .value = "1" },+ .domain = "example.com",+ .path = "/app",+ .httpOnly = true,+ .expiry = 4102444800,+ } },+ });+ try ctx.expectSentResult(.{ .partitionKey = .{ .userContext = "default" } }, .{ .id = 1 });++ // base64 value, explicit partition+ try ctx.processMessage(.{+ .id = 2,+ .method = "storage.setCookie",+ .params = .{+ .cookie = .{ .name = "b", .value = .{ .type = "base64", .value = "Mg==" }, .domain = "other.com", .sameSite = "strict" },+ .partition = .{ .type = "context", .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .partitionKey = .{ .userContext = "default" } }, .{ .id = 2 });++ try ctx.processMessage(.{ .id = 3, .method = "storage.getCookies", .params = struct {}{} });+ try ctx.expectSentResult(.{+ .cookies = .{+ .{ .name = "a", .value = .{ .type = "string", .value = "1" }, .domain = ".example.com", .path = "/app", .size = 2, .httpOnly = true, .secure = false, .sameSite = "default", .expiry = 4102444800 },+ .{ .name = "b", .value = .{ .type = "string", .value = "2" }, .domain = ".other.com", .path = "/", .sameSite = "strict" },+ },+ .partitionKey = .{ .userContext = "default" },+ }, .{ .id = 3 });++ try ctx.processMessage(.{ .id = 4, .method = "storage.getCookies", .params = .{ .filter = .{ .value = .{ .type = "base64", .value = "Mg==" } } } });+ try ctx.expectSentResult(.{ .cookies = .{.{ .name = "b" }} }, .{ .id = 4 });++ try ctx.processMessage(.{ .id = 5, .method = "storage.deleteCookies", .params = .{ .filter = .{ .name = "a" } } });+ try ctx.expectSentResult(.{ .partitionKey = .{ .userContext = "default" } }, .{ .id = 5 });+ try testing.expectEqual(1, ctx.bidi().user_context.session.cookie_jar.cookies.items.len);+ try testing.expectEqual("b", ctx.bidi().user_context.session.cookie_jar.cookies.items[0].name);++ // SameSite=None needs Secure+ try ctx.processMessage(.{+ .id = 6,+ .method = "storage.setCookie",+ .params = .{ .cookie = .{ .name = "c", .value = .{ .type = "string", .value = "3" }, .domain = "example.com", .sameSite = "none" } },+ });+ try ctx.expectSentError("unable to set cookie", null, .{ .id = 6 });++ // a separator in the name, a public suffix for a domain+ try ctx.processMessage(.{+ .id = 7,+ .method = "storage.setCookie",+ .params = .{ .cookie = .{ .name = "c;d", .value = .{ .type = "string", .value = "3" }, .domain = "example.com" } },+ });+ try ctx.expectSentError("unable to set cookie", null, .{ .id = 7 });+ try ctx.processMessage(.{+ .id = 8,+ .method = "storage.setCookie",+ .params = .{ .cookie = .{ .name = "c", .value = .{ .type = "string", .value = "3" }, .domain = "com" } },+ });+ try ctx.expectSentError("unable to set cookie", null, .{ .id = 8 });++ try ctx.processMessage(.{ .id = 9, .method = "storage.getCookies", .params = .{ .partition = .{ .type = "context", .context = "nope" } } });+ try ctx.expectSentError("no such frame", null, .{ .id = 9 });+ try ctx.processMessage(.{ .id = 10, .method = "storage.getCookies", .params = .{ .partition = .{ .type = "storageKey", .userContext = "nope" } } });+ try ctx.expectSentError("no such user context", null, .{ .id = 10 });++ // clears the rest+ try ctx.processMessage(.{ .id = 11, .method = "storage.deleteCookies", .params = struct {}{} });+ try ctx.expectSentResult(.{ .partitionKey = .{ .userContext = "default" } }, .{ .id = 11 });+ try testing.expectEqual(0, ctx.bidi().user_context.session.cookie_jar.cookies.items.len);+}