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