╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
177 session_cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 178 user_id = user_id_buf[0..evt.event_id_size]; 179 } 180 } 181 login_failure = if (getCookieValue(request, login_failure_cookie)) |raw| 182 if (std.mem.eql(u8, raw, "unknown_user")) 183 .unknown_user 184 else if (std.mem.eql(u8, raw, "wrong_password")) 185 .wrong_password 186 else 187 null 188 else 189 null; 190 }, 191 .local => {}, 192 } 193 194 const html = renderIndexHtml(io, allocator, host, .{ 195 .user_id = user_id, 196 .login_failure = login_failure, 197 .current_page = current_page, 198 .is_local = host == .local, 199 }) catch |err| switch (err) { 200 error.NotFound => { 201 try request.respond("not found", .{ 202 .status = .not_found, 203 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 204 }); 205 return; 206 }, 207 else => |e| return e, 208 }; 209 defer allocator.free(html); 210 211 var header_buf: [3]std.http.Header = undefined; 212 var headers: std.ArrayList(std.http.Header) = .initBuffer(&header_buf); 213 headers.appendAssumeCapacity(.{ .name = "content-type", .value = "text/html; charset=utf-8" }); 214 // expire the flash cookie on the way out so a refresh doesn't keep 215 // showing the failure label 216 if (login_failure != null) headers.appendAssumeCapacity(.{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }); 217 if (session_cookie) |cookie| headers.appendAssumeCapacity(.{ .name = "set-cookie", .value = cookie }); 218 try request.respond(html, .{ .extra_headers = headers.items }); 219 return; 220 } 221 222 const embed = findEmbed(path) orelse { 223 try request.respond("not found", .{ 224 .status = .not_found, 225 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 226 }); 227 return; 228 }; 229 230 // the embeds change with every build, so the browser must revalidate 231 // rather than heuristically cache them across server restarts 232 try request.respond(embed.body, .{ 233 .extra_headers = &.{ 234 .{ .name = "content-type", .value = embed.content_type }, 235 .{ .name = "cache-control", .value = "no-cache" }, 236 }, 237 }); 238 } 239 240 fn handleLogin( 241 io: std.Io, 242 request: *std.http.Server.Request, 243 allocator: std.mem.Allocator, 244 base: []const u8, 245 admin_repo_path: []const u8, 246 session_store: SessionStore, 247 ) !void { 248 var body_buf: [256]u8 = undefined; 249 const reader = request.readerExpectNone(&body_buf); 250 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 251 defer allocator.free(body); 252 253 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 254 defer allocator.free(username); 255 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 256 defer allocator.free(password); 257 258 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 259 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 260 defer repo.deinit(io, allocator); 261 262 var arena = std.heap.ArenaAllocator.init(allocator); 263 defer arena.deinit(); 264 265 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 266 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 267 268 // on success, return to the page the login came from (base, or "/" at the 269 // root); on failure, stay on its auth tab to surface the error. 270 const success_location: []const u8 = if (base.len == 0) "/" else base; 271 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{base}); 272 273 switch (result) { 274 .success => |user_id| { 275 const token = try session_store.create(&user_id); 276 var cookie_buf: [256]u8 = undefined; 277 const cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 278 try request.respond("", .{ 279 .status = .see_other, 280 .extra_headers = &.{ 281 .{ .name = "location", .value = success_location }, 282 .{ .name = "set-cookie", .value = cookie }, 283 }, 284 }); 285 }, 286 .unknown_user => { 287 try request.respond("", .{ 288 .status = .see_other, 289 .extra_headers = &.{ 290 .{ .name = "location", .value = failure_location }, 291 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 292 }, 293 }); 294 }, 295 .wrong_password => { 296 try request.respond("", .{ 297 .status = .see_other, 298 .extra_headers = &.{ 299 .{ .name = "location", .value = failure_location }, 300 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 301 }, 302 }); 303 }, 304 } 305 } 306 307 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 308 // revoke the session server-side so the cookie is dead for anyone holding 309 // a copy, not just this browser. 310 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 311 // return to the page the logout came from (base, or "/" at the root). 312 const location: []const u8 = if (base.len == 0) "/" else base; 313 // close the connection instead of keeping it alive: we don't read the 314 // request body, and respond()'s keep-alive path would otherwise try to 315 // discard it — which asserts on a bodyless POST that carries no 316 // content-length, and would block on one with no framing at all. a logout 317 // is just a redirect, so the browser reconnects for the follow-up GET. 318 try request.respond("", .{ 319 .status = .see_other, 320 .keep_alive = false, 321 .extra_headers = &.{ 322 .{ .name = "location", .value = location }, 323 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 324 }, 325 }); 326 } 327 328 fn handleAnsi( 329 io: std.Io, 330 request: *std.http.Server.Request, 331 allocator: std.mem.Allocator, 332 base: []const u8, 333 admin_repo_path: []const u8, 334 session_store: SessionStore, 335 ) !void { 336 // the toggle re-emits the user's own event, so it takes a logged-in user 337 var user_id: [evt.event_id_size]u8 = undefined; 338 const token = getCookieValue(request, cookie_name) orelse return respondLoginRequired(request); 339 if (!session_store.lookup(token, &user_id)) return respondLoginRequired(request); 340 341 { 342 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 343 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 344 defer repo.deinit(io, allocator); 345 346 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 347 } 348 349 // return to the settings tab the toggle came from so the change is visible. 350 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 351 defer allocator.free(location); 352 353 // like logout, this is a bodyless POST, so close the connection rather than 354 // letting the keep-alive path try to discard a body that isn't framed. 355 try request.respond("", .{ 356 .status = .see_other, 357 .keep_alive = false, 358 .extra_headers = &.{ 359 .{ .name = "location", .value = location }, 360 }, 361 }); 362 } 363 364 // the author for an event created by this request, or null when the request 365 // may not create one. local mode has no accounts, so it authors anonymously. 366 fn eventAuthorEmail( 367 io: std.Io, 368 allocator: std.mem.Allocator, 369 arena: *std.heap.ArenaAllocator, 370 request: *std.http.Server.Request, 371 host: Host, 372 ) !?[]const u8 { 373 const remote = switch (host) { 374 .remote => |remote| remote, 375 .local => return "user@haxy", // TODO: try the repo's git config user.email first 376 }; 377 const token = getCookieValue(request, cookie_name) orelse return null; 378 var user_id: [evt.event_id_size]u8 = undefined; 379 if (!remote.session_store.lookup(token, &user_id)) return null; 380 381 var repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 382 defer repo.deinit(io, allocator); 383 const moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 384 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 385 return user.event.email; 386 } 387 388 // refuse a write from a request with no logged-in user. the body goes unread, 389 // so the connection closes. 390 fn respondLoginRequired(request: *std.http.Server.Request) !void { 391 try request.respond("log in to make changes", .{ 392 .status = .forbidden, 393 .keep_alive = false, 394 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 395 }); 396 } 397 398 // create an issue in the repo the form's page names (base is 399 // "/repo/<owner>/<name>", or "" in local mode) and redirect to it 400 fn handleIssue( 401 io: std.Io, 402 request: *std.http.Server.Request, 403 allocator: std.mem.Allocator, 404 base: []const u8, 405 host: Host, 406 ) !void { 407 var author_arena = std.heap.ArenaAllocator.init(allocator); 408 defer author_arena.deinit(); 409 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 410 411 var body_buf: [256]u8 = undefined; 412 const reader = request.readerExpectNone(&body_buf); 413 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 414 defer allocator.free(body); 415 416 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 417 defer allocator.free(title); 418 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 419 defer allocator.free(tags); 420 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 421 defer allocator.free(description_crlf); 422 // form submission normalizes textarea line breaks to CRLF; store plain 423 // newlines so the text renders the same on every host 424 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 425 defer allocator.free(description); 426 427 if (!evt.Issue.fieldsValid(title, tags)) { 428 const form_location = try std.fmt.allocPrint(allocator, "{s}/issues/new", .{base}); 429 defer allocator.free(form_location); 430 try request.respond("", .{ 431 .status = .see_other, 432 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 433 }); 434 return; 435 } 436 437 var id_bytes: [evt.event_id_size]u8 = undefined; 438 io.random(&id_bytes); 439 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 440 441 const event = evt.EventWithId{ 442 .id = event_id_hex, 443 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 444 .author_email = author_email, 445 .event = .{ .issue = .{ 446 .title = title, 447 .description = description, 448 .tags = tags, 449 } }, 450 }; 451 452 const not_found = "repo not found"; 453 switch (host) { 454 .remote => |remote| { 455 const repo_prefix = "/repo/"; 456 if (!std.mem.startsWith(u8, base, repo_prefix)) { 457 try request.respond(not_found, .{ 458 .status = .not_found, 459 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 460 }); 461 return; 462 } 463 464 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 465 defer allocator.free(repos_dir); 466 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, base[repo_prefix.len..], false)) { 467 .ok => |p| p, 468 .invalid, .not_found => { 469 try request.respond(not_found, .{ 470 .status = .not_found, 471 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 472 }); 473 return; 474 }, 475 }; 476 defer allocator.free(repo_path); 477 478 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 479 defer repo.deinit(io, allocator); 480 try evt.consume(.xit, .{}, io, allocator, &repo, evt.events_ref, &[_]evt.EventWithId{event}); 481 }, 482 .local => |src| { 483 // the local form posts to "/issue", so base is empty 484 if (base.len != 0) { 485 try request.respond(not_found, .{ 486 .status = .not_found, 487 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 488 }); 489 return; 490 } 491 switch (src.repo_kind) { 492 inline else => |repo_kind| { 493 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 494 defer any_repo.deinit(io, allocator); 495 switch (any_repo) { 496 inline else => |*repo| try evt.consume(repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &[_]evt.EventWithId{event}), 497 } 498 }, 499 } 500 }, 501 } 502 503 const location = try std.fmt.allocPrint(allocator, "{s}/issues/{s}", .{ base, &event_id_hex }); 504 defer allocator.free(location); 505 try request.respond("", .{ 506 .status = .see_other, 507 .extra_headers = &.{.{ .name = "location", .value = location }}, 508 }); 509 } 510 511 // split an issue url ("/repo/<owner>/<name>/issues/<id>", identity elided in 512 // local mode) into what precedes "/issues/" and the decoded id, null when it 513 // isn't one. the repo base is validated per host in updateIssue. 514 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 515 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 516 const issues_infix = "/issues/"; 517 const id_len = evt.event_id_size * 2; 518 if (base.len < issues_infix.len + id_len) return null; 519 var id_bytes: [evt.event_id_size]u8 = undefined; 520 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 521 const head = base[0 .. base.len - id_len]; 522 if (!std.mem.endsWith(u8, head, issues_infix)) return null; 523 return .{ .repo_base = head[0 .. head.len - issues_infix.len], .id_bytes = id_bytes }; 524 } 525 526 // re-emit the issue `parts` names with `update` applied, in the repo the 527 // host resolves the base to. error.NotFound when the base names no repo or 528 // the id no issue. 529 fn updateIssue( 530 io: std.Io, 531 allocator: std.mem.Allocator, 532 host: Host, 533 parts: IssueBaseParts, 534 update: evt.Issue.Update, 535 author_email: []const u8, 536 ) !void { 537 switch (host) { 538 .remote => |remote| { 539 const repo_prefix = "/repo/"; 540 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 541 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 542 defer allocator.free(repos_dir); 543 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 544 .ok => |p| p, 545 .invalid, .not_found => return error.NotFound, 546 }; 547 defer allocator.free(repo_path); 548 549 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 550 defer repo.deinit(io, allocator); 551 try evt.Issue.update(.xit, .{}, io, allocator, &repo, &parts.id_bytes, update, author_email); 552 }, 553 .local => |src| { 554 // the local forms post to "/issues/<id>/...", so the repo base 555 // is empty 556 if (parts.repo_base.len != 0) return error.NotFound; 557 switch (src.repo_kind) { 558 inline else => |repo_kind| { 559 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 560 defer any_repo.deinit(io, allocator); 561 switch (any_repo) { 562 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author_email), 563 } 564 }, 565 } 566 }, 567 } 568 } 569 570 // set the status of the issue the url names (base is 571 // "/repo/<owner>/<name>/issues/<id>", identity elided in local mode) by 572 // re-emitting its event, then redirect back to it 573 fn handleIssueStatus( 574 io: std.Io, 575 request: *std.http.Server.Request, 576 allocator: std.mem.Allocator, 577 base: []const u8, 578 host: Host, 579 status: evt.Issue.Status, 580 ) !void { 581 const not_found = "issue not found"; 582 const parts = issueBaseParts(base) orelse { 583 try request.respond(not_found, .{ 584 .status = .not_found, 585 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 586 }); 587 return; 588 }; 589 590 var author_arena = std.heap.ArenaAllocator.init(allocator); 591 defer author_arena.deinit(); 592 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 593 594 updateIssue(io, allocator, host, parts, .{ .status = status }, author_email) catch |err| switch (err) { 595 error.NotFound => { 596 try request.respond(not_found, .{ 597 .status = .not_found, 598 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 599 }); 600 return; 601 }, 602 else => |e| return e, 603 }; 604 605 // like logout, this is a bodyless POST, so close the connection rather than 606 // letting the keep-alive path try to discard a body that isn't framed. 607 try request.respond("", .{ 608 .status = .see_other, 609 .keep_alive = false, 610 .extra_headers = &.{.{ .name = "location", .value = base }}, 611 }); 612 } 613 614 // replace the title/tags/description of the issue the url names (base is 615 // "/repo/<owner>/<name>/issues/<id>", identity elided in local mode; the 616 // form posts to "<base>/edit") by re-emitting its event with its status 617 // preserved, then redirect back to it 618 fn handleIssueEdit( 619 io: std.Io, 620 request: *std.http.Server.Request, 621 allocator: std.mem.Allocator, 622 base: []const u8, 623 host: Host, 624 ) !void { 625 var author_arena = std.heap.ArenaAllocator.init(allocator); 626 defer author_arena.deinit(); 627 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 628 629 var body_buf: [256]u8 = undefined; 630 const reader = request.readerExpectNone(&body_buf); 631 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 632 defer allocator.free(body); 633 634 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 635 defer allocator.free(title); 636 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 637 defer allocator.free(tags); 638 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 639 defer allocator.free(description_crlf); 640 // form submission normalizes textarea line breaks to CRLF; store plain 641 // newlines so the text renders the same on every host 642 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 643 defer allocator.free(description); 644 645 // invalid fields send the user back to the edit form 646 if (!evt.Issue.fieldsValid(title, tags)) { 647 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 648 defer allocator.free(form_location); 649 try request.respond("", .{ 650 .status = .see_other, 651 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 652 }); 653 return; 654 } 655 656 const not_found = "issue not found"; 657 const parts = issueBaseParts(base) orelse { 658 try request.respond(not_found, .{ 659 .status = .not_found, 660 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 661 }); 662 return; 663 }; 664 665 updateIssue(io, allocator, host, parts, .{ .fields = .{ 666 .title = title, 667 .tags = tags, 668 .description = description, 669 } }, author_email) catch |err| switch (err) { 670 error.NotFound => { 671 try request.respond(not_found, .{ 672 .status = .not_found, 673 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 674 }); 675 return; 676 }, 677 else => |e| return e, 678 }; 679 680 try request.respond("", .{ 681 .status = .see_other, 682 .extra_headers = &.{.{ .name = "location", .value = base }}, 683 }); 684 } 685 686 fn renderIndexHtml( 687 io: std.Io, 688 allocator: std.mem.Allocator, 689 host: Host, 690 session_data: ui.Session.Data, 691 ) ![]const u8 { 692 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 693 694 var page_arena = std.heap.ArenaAllocator.init(allocator); 695 defer page_arena.deinit(); 696 697 // the remote admin repo must outlive the page build, since the session's 698 // moment reads from it. 699 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 700 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 701 702 var session = switch (host) { 703 .remote => |remote| blk: { 704 // open the admin repo to read live user/repo data. 705 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 706 const repo = if (repo_maybe) |*repo| repo else unreachable; 707 var session = try ui.Session.init(&page_arena, repo, session_data); 708 // give the page builders filesystem access to the on-disk repos (a 709 // sibling "repos" dir next to the admin repo) so the Repo page can 710 // read its files. 711 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 712 break :blk session; 713 }, 714 .local => |local| ui.Session{ 715 .data = session_data, 716 .arena = &page_arena, 717 .page_arena = &page_arena, 718 .local = local, 719 }, 720 }; 721 session.io = io; 722 723 const snapshot: ui.Snapshot = .{ 724 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 725 .session = session.data, 726 }; 727 var root = try ui.initRoot(allocator, &snapshot.page, &session); 728 defer root.deinit(allocator); 729 730 const content = try generateHtml(allocator, &root); 731 defer allocator.free(content); 732 const overlay = try generateOverlay(allocator, &root, &session); 733 defer allocator.free(overlay); 734 735 // serialize the snapshot so the wasm side can parse it back without making 736 // a second request. it's embedded raw in a <script type="application/json"> 737 // block, whose content is raw text terminated only by "</script". in json, 738 // '<' appears solely inside string values, so escaping every '<' (and '>' 739 // for good measure) to its \uXXXX form yields equivalent json that can't 740 // break out of the tag. 741 var json: std.Io.Writer.Allocating = .init(allocator); 742 defer json.deinit(); 743 try std.json.Stringify.value(snapshot, .{}, &json.writer); 744 745 var json_escaped: std.ArrayList(u8) = .empty; 746 defer json_escaped.deinit(allocator); 747 for (json.written()) |c| switch (c) { 748 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 749 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 750 else => try json_escaped.append(allocator, c), 751 }; 752 753 var out: std.ArrayList(u8) = .empty; 754 errdefer out.deinit(allocator); 755 { 756 var cursor: usize = 0; 757 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 758 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 759 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 760 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 761 }) |sub| { 762 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 763 try out.appendSlice(allocator, template[cursor..idx]); 764 try out.appendSlice(allocator, sub.replacement); 765 cursor = idx + sub.needle.len; 766 } 767 try out.appendSlice(allocator, template[cursor..]); 768 } 769 return try out.toOwnedSlice(allocator); 770 } 771 772 fn findEmbed(request_path: []const u8) ?Embed { 773 const path = if (std.mem.eql(u8, request_path, "/")) 774 "index.html" 775 else if (request_path.len > 1 and request_path[0] == '/') 776 request_path[1..] 777 else 778 return null; 779 780 for (embeds) |embed| { 781 if (std.mem.eql(u8, path, embed.path)) return embed; 782 } 783 return null; 784 } 785 786 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 787 // own absolutely-positioned, natively-scrollable <div> holding its full content, 788 // rendered recursively so nested scrolls work. 789 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 790 const grid = root.getGrid() orelse return error.MissingGrid; 791 792 var out: std.ArrayList(u8) = .empty; 793 errdefer out.deinit(allocator); 794 795 try renderPanel(allocator, &out, root.getFocus(), grid); 796 return try out.toOwnedSlice(allocator); 797 } 798 799 // render one panel — a focus subtree and its content grid — as HTML, recursing 800 // once per web-native Scroll inside it. the root panel is the whole page; each 801 // Scroll becomes a nested, natively-scrollable div holding its full content. 802 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 803 // then the child scroll divs over those holes. 804 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 805 // `direct` is this panel's scroll children, each drawn as an overlaid div. 806 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 807 // plus their descendants, which the focus tree flattens into this panel's 808 // children): the cell hit-test below skips them so this panel doesn't claim 809 // cells that are really rendered inside a child scroll's own panel. 810 // (scrolls aren't nested in practice, so every scroll child is direct here.) 811 var direct: std.ArrayList(usize) = .empty; 812 defer direct.deinit(allocator); 813 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 814 defer excluded.deinit(allocator); 815 { 816 var it = focus.children.iterator(); 817 while (it.next()) |e| { 818 if (e.value_ptr.focus.scroll == null) continue; 819 try direct.append(allocator, e.key_ptr.*); 820 try excluded.put(allocator, e.key_ptr.*, {}); 821 var mit = e.value_ptr.focus.children.iterator(); 822 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 823 } 824 } 825 826 // the HTML element a run of cells is wrapped in, chosen from the cell's 827 // focusable kind 828 const CellTag = union(enum) { 829 span, // clickable focusable cell 830 a: []const u8, // clickable focusable link 831 plain, // non-focusable, colored 832 833 const a_prefix = "a:"; 834 // an "in-page" anchor: rendered as a real <a href> so it works with js 835 // disabled, but crossPageLink ignores it, so with wasm the click just 836 // moves focus rather than navigating. 837 const inpage_prefix = "ai:"; 838 839 fn init(str: []const u8) @This() { 840 if (std.mem.startsWith(u8, str, inpage_prefix)) { 841 return .{ .a = str[inpage_prefix.len..] }; 842 } 843 if (std.mem.startsWith(u8, str, a_prefix)) { 844 return .{ .a = str[a_prefix.len..] }; 845 } 846 return .span; 847 } 848 849 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 850 var id_buf: [32]u8 = undefined; 851 switch (self) { 852 .span => { 853 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 854 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 855 try out.appendSlice(alloc, "\""); 856 try out.appendSlice(alloc, style_attr); 857 try out.appendSlice(alloc, ">"); 858 }, 859 .a => |href| { 860 // tabindex=-1 keeps these out of the browser's tab order 861 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 862 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 863 try out.appendSlice(alloc, "\" href=\""); 864 try appendEscapedHtml(alloc, out, href); 865 try out.appendSlice(alloc, "\""); 866 try out.appendSlice(alloc, style_attr); 867 try out.appendSlice(alloc, ">"); 868 }, 869 .plain => { 870 try out.appendSlice(alloc, "<span"); 871 try out.appendSlice(alloc, style_attr); 872 try out.appendSlice(alloc, ">"); 873 }, 874 } 875 } 876 877 fn closeTag(self: @This()) []const u8 { 878 return switch (self) { 879 .span, .plain => "</span>", 880 .a => "</a>", 881 }; 882 } 883 }; 884 885 // emit this panel's grid as rows of text, coalescing adjacent cells that 886 // share a focus id and colors into one tag (a clickable span, a link, or a 887 // plain colored span). cells under a child scroll keep only their background. 888 for (0..grid.size.height) |y| { 889 var cur_id: ?usize = null; 890 var cur_fg: ?Grid.Color = null; 891 var cur_bg: ?Grid.Color = null; 892 var open_tag: ?CellTag = null; 893 var first = true; 894 for (0..grid.size.width) |x| { 895 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 896 // a cell covered by a child scroll's viewport is drawn by that scroll's 897 // own div, so blank its glyph and make it non-clickable here — but keep 898 // its background, so the backdrop still shows through the scroll's 899 // transparent div instead of a bare hole. 900 const covered_by_scroll = blk: { 901 for (direct.items) |id| { 902 const r = (focus.children.get(id) orelse continue).rect; 903 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 904 } 905 break :blk false; 906 }; 907 // the focusable cell at (x, y) among this panel's own focusables (skipping 908 // any that belong to a child scroll, whose cells are drawn in their own 909 // panel); none for a covered cell. 910 const cell_id = if (covered_by_scroll) null else blk: { 911 var iter = focus.children.iterator(); 912 while (iter.next()) |entry| { 913 const child = entry.value_ptr.*; 914 if (!child.focus.focusable) continue; 915 if (excluded.contains(entry.key_ptr.*)) continue; 916 const r = child.rect; 917 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 918 break :blk entry.key_ptr.*; 919 } 920 } 921 break :blk null; 922 }; 923 const fg = if (covered_by_scroll) null else cell.style.fg; 924 const bg = cell.style.bg; 925 926 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 927 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 928 929 var new_tag: ?CellTag = null; 930 if (cell_id) |id| { 931 if (focus.children.get(id)) |child| { 932 new_tag = switch (child.focus.kind) { 933 .custom => |custom| CellTag.init(custom), 934 else => .span, 935 }; 936 } 937 } 938 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 939 940 if (new_tag) |t| { 941 var style_buf: [64]u8 = undefined; 942 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 943 } 944 945 open_tag = new_tag; 946 cur_id = cell_id; 947 cur_fg = fg; 948 cur_bg = bg; 949 first = false; 950 } 951 952 if (covered_by_scroll) { 953 try appendEscapedHtml(allocator, output, " "); 954 } else if (cell.continuation) { 955 // the wide rune to the left was emitted 2ch wide, covering this column 956 } else if (cell.rune) |rune| { 957 // a double-width rune is pinned inside a 2ch span so the 958 // fallback glyph's advance width can't shift the rest of the row 959 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 960 if (wide) { 961 try output.appendSlice(allocator, "<span class=\"w2\">"); 962 try appendEscapedHtml(allocator, output, rune); 963 try output.appendSlice(allocator, "</span>"); 964 } else { 965 try appendEscapedHtml(allocator, output, rune); 966 } 967 } else { 968 try appendEscapedHtml(allocator, output, " "); 969 } 970 } 971 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 972 try output.append(allocator, '\n'); 973 } 974 975 // each child scroll becomes a natively-scrollable div positioned over its 976 // viewport, holding its full content rendered recursively. 977 for (direct.items) |id| { 978 const child = focus.children.get(id) orelse continue; 979 const info = child.focus.scroll orelse continue; 980 const r = child.rect; 981 // overflow only on the axes the widget scrolls; `auto` shows a bar only 982 // when that axis actually overflows. the other axis is clipped (hidden), 983 // matching how the terminal Scroll handles its non-scrolling axis. 984 const overflow = switch (info.direction) { 985 .vert => "overflow-x:hidden;overflow-y:auto", 986 .horiz => "overflow-x:auto;overflow-y:hidden", 987 .both => "overflow:auto", 988 }; 989 // the id carries a content version so JS preserves the native scroll 990 // position across re-renders of the same content but resets it when the 991 // content is replaced — e.g. selecting a different commit. the widget's 992 // scroll offset (in cells) rides along so JS can apply it when it has no 993 // preserved position, letting a wasm-side scrollToRect (the files list 994 // scrolling to its selected row on page load) reach the browser. 995 var buf: [224]u8 = undefined; 996 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 997 try renderPanel(allocator, output, child.focus, info.content); 998 try output.appendSlice(allocator, "</div>"); 999 } 1000 } 1001 1002 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1003 // widget tree, each wrapping the text inputs and submit button inside it, 1004 // positioned absolutely over the matching grid cells. 1005 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1006 const root_focus = root.getFocus(); 1007 1008 var out: std.ArrayList(u8) = .empty; 1009 errdefer out.deinit(allocator); 1010 1011 const form_prefix = "form:"; 1012 1013 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1014 // which matches the order widgets were added in code 1015 var iter = root_focus.children.iterator(); 1016 while (iter.next()) |entry| { 1017 const child = entry.value_ptr.*; 1018 const action_url = switch (child.focus.kind) { 1019 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1020 custom[form_prefix.len..] 1021 else 1022 continue, 1023 else => continue, 1024 }; 1025 1026 try out.appendSlice(allocator, "<form action=\""); 1027 try appendEscapedHtml(allocator, &out, action_url); 1028 try out.appendSlice(allocator, "\" method=\"post\""); 1029 // an empty action must not POST — block it and send the input to the TUI instead 1030 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1031 try out.appendSlice(allocator, ">"); 1032 1033 // form.focus.children was populated by addChild, which flattens the 1034 // whole subtree into one map — so descendants (inputs + the submit 1035 // button) all appear here. positions on form.focus are relative to 1036 // the form, so we look up absolute rects via root_focus for layout. 1037 var inner_iter = child.focus.children.iterator(); 1038 while (inner_iter.next()) |inner_entry| { 1039 const inner_id = inner_entry.key_ptr.*; 1040 const root_child = root_focus.children.get(inner_id) orelse continue; 1041 const r = root_child.rect; 1042 switch (root_child.focus.kind) { 1043 .text_input, .text_input_password => { 1044 const ti = session.text_inputs.get(inner_id) orelse continue; 1045 const inner_left = r.x + 1; 1046 const inner_top = r.y + 1; 1047 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1048 1049 try out.appendSlice(allocator, "<input type=\""); 1050 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1051 try out.appendSlice(allocator, "\" data-focus-id=\""); 1052 var id_buf: [32]u8 = undefined; 1053 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1054 if (ti.options.name.len > 0) { 1055 try out.appendSlice(allocator, "\" name=\""); 1056 try appendEscapedHtml(allocator, &out, ti.options.name); 1057 } 1058 // never the live content as the `value`: the browser tracks user 1059 // input natively, and including the wasm-side value here would make 1060 // the overlay HTML differ on every keystroke — that would trip the 1061 // diff in _setOverlay and rebuild the <input>, eating the user's 1062 // caret. a page-constant initial value is safe. 1063 if (session.input_values.get(inner_id)) |value| { 1064 try out.appendSlice(allocator, "\" value=\""); 1065 try appendEscapedHtml(allocator, &out, value); 1066 } 1067 try out.appendSlice(allocator, "\" style=\"left:"); 1068 var pos_buf: [64]u8 = undefined; 1069 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 1070 try out.appendSlice(allocator, "\">"); 1071 }, 1072 .text_area => { 1073 const ti = session.text_inputs.get(inner_id) orelse continue; 1074 const inner_left = r.x + 1; 1075 const inner_top = r.y + 1; 1076 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1077 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1078 1079 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1080 var id_buf: [32]u8 = undefined; 1081 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1082 if (ti.options.name.len > 0) { 1083 try out.appendSlice(allocator, "\" name=\""); 1084 try appendEscapedHtml(allocator, &out, ti.options.name); 1085 } 1086 // like the input above, only a page-constant initial value 1087 // inside: the browser tracks the live value and the 1088 // overlay diff must stay stable across keystrokes 1089 try out.appendSlice(allocator, "\" style=\"left:"); 1090 var pos_buf: [128]u8 = undefined; 1091 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 1092 try out.appendSlice(allocator, "\">"); 1093 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1094 try out.appendSlice(allocator, "</textarea>"); 1095 }, 1096 .custom => |custom| { 1097 if (std.mem.eql(u8, "submit", custom)) { 1098 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1099 var id_buf: [32]u8 = undefined; 1100 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1101 try out.appendSlice(allocator, "\" style=\"left:"); 1102 var pos_buf: [128]u8 = undefined; 1103 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1104 try out.appendSlice(allocator, "\"></button>"); 1105 } 1106 }, 1107 else => {}, 1108 } 1109 } 1110 1111 try out.appendSlice(allocator, "</form>"); 1112 } 1113 1114 return try out.toOwnedSlice(allocator); 1115 } 1116 1117 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1118 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1119 return b == null; 1120 } 1121 1122 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1123 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1124 // empty slice when neither is set. 1125 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1126 if (fg == null and bg == null) return buf[0..0]; 1127 const prefix = " style=\""; 1128 @memcpy(buf[0..prefix.len], prefix); 1129 var i: usize = prefix.len; 1130 if (fg) |c| { 1131 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1132 i += s.len; 1133 } 1134 if (bg) |c| { 1135 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1136 i += s.len; 1137 } 1138 buf[i] = '"'; 1139 i += 1; 1140 return buf[0..i]; 1141 } 1142 1143 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1144 for (input) |ch| { 1145 switch (ch) { 1146 '&' => try out.appendSlice(allocator, "&amp;"), 1147 '<' => try out.appendSlice(allocator, "&lt;"), 1148 '>' => try out.appendSlice(allocator, "&gt;"), 1149 '"' => try out.appendSlice(allocator, "&quot;"), 1150 '\'' => try out.appendSlice(allocator, "&#39;"), 1151 else => try out.append(allocator, ch), 1152 } 1153 } 1154 } 1155 1156 // --- helpers -------------------------------------------------------------- 1157 1158 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1159 var iter = request.iterateHeaders(); 1160 while (iter.next()) |header| { 1161 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1162 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1163 while (pairs.next()) |pair| { 1164 const trimmed = std.mem.trim(u8, pair, " \t"); 1165 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1166 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1167 return trimmed[eq + 1 ..]; 1168 } 1169 } 1170 } 1171 return null; 1172 } 1173 1174 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1175 var iter = std.mem.splitScalar(u8, body, '&'); 1176 while (iter.next()) |pair| { 1177 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1178 if (std.mem.eql(u8, pair[0..eq], key)) { 1179 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1180 } 1181 } 1182 return null; 1183 } 1184 1185 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1186 var out: std.ArrayList(u8) = .empty; 1187 errdefer out.deinit(allocator); 1188 var i: usize = 0; 1189 while (i < encoded.len) : (i += 1) { 1190 switch (encoded[i]) { 1191 '+' => try out.append(allocator, ' '), 1192 '%' => { 1193 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1194 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1195 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1196 try out.append(allocator, hi * 16 + lo); 1197 i += 2; 1198 }, 1199 else => try out.append(allocator, encoded[i]), 1200 } 1201 } 1202 return try out.toOwnedSlice(allocator); 1203 } 1204 1205 // disk-backed web session store. each login mints a random, opaque token 1206 // (not the user's id) that is stored as a file named by the token hex, whose 1207 // contents are the raw user_id bytes. authenticating a request is a lookup of 1208 // the cookie's token; logout deletes the file, revoking the session. there is 1209 // deliberately no expiry — a session lives until logout. 1210 pub const SessionStore = struct { 1211 io: std.Io, 1212 dir: std.Io.Dir, 1213 1214 pub const token_hex_len = evt.event_id_size * 2; 1215 1216 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1217 try data_dir.createDirPath(io, "sessions"); 1218 const dir = try data_dir.openDir(io, "sessions", .{}); 1219 return .{ .io = io, .dir = dir }; 1220 } 1221 1222 pub fn deinit(self: SessionStore) void { 1223 self.dir.close(self.io); 1224 } 1225 1226 // mint a new session for user_id, returning the token hex to set as the 1227 // cookie value. 1228 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1229 var token: [evt.event_id_size]u8 = undefined; 1230 self.io.random(&token); 1231 const token_hex = std.fmt.bytesToHex(token, .lower); 1232 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1233 defer file.close(self.io); 1234 try file.writeStreamingAll(self.io, user_id); 1235 return token_hex; 1236 } 1237 1238 // resolve a cookie's token to its user_id. returns false (logged out) for a 1239 // missing, malformed, or unknown token. 1240 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1241 if (!isToken(token_hex)) return false; 1242 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1243 defer file.close(self.io); 1244 var storage: [evt.event_id_size]u8 = undefined; 1245 var file_reader = file.reader(self.io, &storage); 1246 file_reader.interface.readSliceAll(out) catch return false; 1247 return true; 1248 } 1249 1250 // revoke a session. a no-op for a missing or malformed token. 1251 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1252 if (!isToken(token_hex)) return; 1253 self.dir.deleteFile(self.io, token_hex) catch {}; 1254 } 1255 1256 // leave `token_hex`'s session for the next visitor arriving without one. 1257 // only the `try` fixture writes one, and only a debug build honors it. the 1258 // name isn't token-shaped, so it can't collide with a session file. 1259 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1260 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1261 defer file.close(self.io); 1262 try file.writeStreamingAll(self.io, token_hex); 1263 } 1264 1265 // claim the offered session, if one is there. the delete picks the winner 1266 // of a race, so the offer is only ever taken once. a release build never 1267 // looks, because that would be an extra syscall for every GET request. 1268 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1269 if (builtin.mode != .Debug) return false; 1270 { 1271 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1272 defer file.close(self.io); 1273 var storage: [token_hex_len]u8 = undefined; 1274 var file_reader = file.reader(self.io, &storage); 1275 file_reader.interface.readSliceAll(out) catch return false; 1276 } 1277 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1278 return true; 1279 } 1280 1281 const auto_login_name = "auto-login"; 1282 1283 // a token is exactly token_hex_len hex chars. validating before using the 1284 // value as a path keeps attacker-supplied cookies from escaping the 1285 // sessions dir (e.g. via "/" or ".." bytes). 1286 fn isToken(token_hex: []const u8) bool { 1287 if (token_hex.len != token_hex_len) return false; 1288 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1289 return true; 1290 } 1291 }; 1292