╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
514 try request.respond(not_found, .{ 515 .status = .not_found, 516 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 517 }); 518 return; 519 } 520 switch (src.repo_kind) { 521 inline else => |repo_kind| { 522 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 523 defer any_repo.deinit(io, allocator); 524 switch (any_repo) { 525 inline else => |*repo| try evt.consume(repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &[_]evt.EventWithId{event}), 526 } 527 }, 528 } 529 }, 530 } 531 532 const location = try std.fmt.allocPrint(allocator, "{s}/issue:{s}", .{ base, &event_id_hex }); 533 defer allocator.free(location); 534 try request.respond("", .{ 535 .status = .see_other, 536 .extra_headers = &.{.{ .name = "location", .value = location }}, 537 }); 538 } 539 540 const CommentBaseParts = struct { 541 repo_base: []const u8, 542 thread_id: [evt.event_id_size]u8, 543 comment_id: ?[evt.event_id_size]u8, 544 }; 545 546 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 547 const issue_infix = "/issue:"; 548 const comment_infix = "/comment:"; 549 const id_len = evt.event_id_size * 2; 550 const issue_at = std.mem.lastIndexOf(u8, base, issue_infix) orelse return null; 551 const tail = base[issue_at + issue_infix.len ..]; 552 if (tail.len < id_len) return null; 553 554 var thread_id: [evt.event_id_size]u8 = undefined; 555 _ = std.fmt.hexToBytes(&thread_id, tail[0..id_len]) catch return null; 556 var comment_id: ?[evt.event_id_size]u8 = null; 557 if (tail.len != id_len) { 558 if (tail.len != id_len + comment_infix.len + id_len) return null; 559 if (!std.mem.eql(u8, tail[id_len .. id_len + comment_infix.len], comment_infix)) return null; 560 var id: [evt.event_id_size]u8 = undefined; 561 _ = std.fmt.hexToBytes(&id, tail[id_len + comment_infix.len ..]) catch return null; 562 comment_id = id; 563 } 564 return .{ .repo_base = base[0..issue_at], .thread_id = thread_id, .comment_id = comment_id }; 565 } 566 567 // create a reply from an issue or comment /new form, then redirect to its 568 // permalink. the rest of the url identifies the thread and parent. 569 fn handleCommentNew( 570 io: std.Io, 571 request: *std.http.Server.Request, 572 allocator: std.mem.Allocator, 573 base: []const u8, 574 host: Host, 575 ) !void { 576 const not_found = "comment parent not found"; 577 const parts = commentBaseParts(base) orelse { 578 try request.respond(not_found, .{ 579 .status = .not_found, 580 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 581 }); 582 return; 583 }; 584 585 var author_arena = std.heap.ArenaAllocator.init(allocator); 586 defer author_arena.deinit(); 587 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 588 589 var body_buf: [256]u8 = undefined; 590 const reader = request.readerExpectNone(&body_buf); 591 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 592 defer allocator.free(posted); 593 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 594 defer allocator.free(body_crlf); 595 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 596 defer allocator.free(body); 597 598 if (!evt.Comment.fieldsValid(body)) { 599 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 600 defer allocator.free(form_location); 601 try request.respond("", .{ 602 .status = .see_other, 603 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 604 }); 605 return; 606 } 607 608 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 609 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 610 611 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 612 switch (host) { 613 .remote => |remote| { 614 const repo_prefix = "/repo/"; 615 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) { 616 try request.respond(not_found, .{ 617 .status = .not_found, 618 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 619 }); 620 return; 621 } 622 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 623 defer allocator.free(repos_dir); 624 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 625 .ok => |p| p, 626 .invalid, .not_found => { 627 try request.respond(not_found, .{ 628 .status = .not_found, 629 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 630 }); 631 return; 632 }, 633 }; 634 defer allocator.free(repo_path); 635 636 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 637 defer repo.deinit(io, allocator); 638 event_id_hex = try evt.Comment.create(.xit, .{}, io, allocator, &repo, &thread_id_hex, &parent_id_hex, body, author_email); 639 }, 640 .local => |src| { 641 if (parts.repo_base.len != 0) { 642 try request.respond(not_found, .{ 643 .status = .not_found, 644 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 645 }); 646 return; 647 } 648 switch (src.repo_kind) { 649 inline else => |repo_kind| { 650 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 651 defer any_repo.deinit(io, allocator); 652 switch (any_repo) { 653 inline else => |*repo| event_id_hex = try evt.Comment.create(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id_hex, &parent_id_hex, body, author_email), 654 } 655 }, 656 } 657 }, 658 } 659 660 const location = try std.fmt.allocPrint(allocator, "{s}/issue:{s}/comment:{s}", .{ parts.repo_base, &thread_id_hex, &event_id_hex }); 661 defer allocator.free(location); 662 try request.respond("", .{ 663 .status = .see_other, 664 .extra_headers = &.{.{ .name = "location", .value = location }}, 665 }); 666 } 667 668 // re-emit the comment `parts` names with a new body, in the repo the host 669 // resolves the base to. 670 fn updateComment( 671 io: std.Io, 672 allocator: std.mem.Allocator, 673 host: Host, 674 parts: CommentBaseParts, 675 body: []const u8, 676 author_email: []const u8, 677 ) !void { 678 const comment_id = parts.comment_id orelse return error.NotFound; 679 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 680 switch (host) { 681 .remote => |remote| { 682 const repo_prefix = "/repo/"; 683 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 684 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 685 defer allocator.free(repos_dir); 686 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 687 .ok => |p| p, 688 .invalid, .not_found => return error.NotFound, 689 }; 690 defer allocator.free(repo_path); 691 692 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 693 defer repo.deinit(io, allocator); 694 try evt.Comment.update(.xit, .{}, io, allocator, &repo, &thread_id, &comment_id, body, author_email); 695 }, 696 .local => |src| { 697 if (parts.repo_base.len != 0) return error.NotFound; 698 switch (src.repo_kind) { 699 inline else => |repo_kind| { 700 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 701 defer any_repo.deinit(io, allocator); 702 switch (any_repo) { 703 inline else => |*repo| try evt.Comment.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author_email), 704 } 705 }, 706 } 707 }, 708 } 709 } 710 711 // edit actions share a suffix; the base identifies whether the form names an 712 // issue or comment. 713 fn handleEdit( 714 io: std.Io, 715 request: *std.http.Server.Request, 716 allocator: std.mem.Allocator, 717 base: []const u8, 718 host: Host, 719 ) !void { 720 if (commentBaseParts(base)) |parts| { 721 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 722 } 723 return handleIssueEdit(io, request, allocator, base, host); 724 } 725 726 // replace the body of the comment the url names, then redirect to its 727 // permalink. 728 fn handleCommentEdit( 729 io: std.Io, 730 request: *std.http.Server.Request, 731 allocator: std.mem.Allocator, 732 base: []const u8, 733 host: Host, 734 parts: CommentBaseParts, 735 ) !void { 736 var author_arena = std.heap.ArenaAllocator.init(allocator); 737 defer author_arena.deinit(); 738 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 739 740 var body_buf: [256]u8 = undefined; 741 const reader = request.readerExpectNone(&body_buf); 742 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 743 defer allocator.free(posted); 744 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 745 defer allocator.free(body_crlf); 746 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 747 defer allocator.free(body); 748 749 if (!evt.Comment.fieldsValid(body)) { 750 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 751 defer allocator.free(form_location); 752 try request.respond("", .{ 753 .status = .see_other, 754 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 755 }); 756 return; 757 } 758 759 const not_found = "comment not found"; 760 updateComment(io, allocator, host, parts, body, author_email) catch |err| switch (err) { 761 error.NotFound => { 762 try request.respond(not_found, .{ 763 .status = .not_found, 764 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 765 }); 766 return; 767 }, 768 else => |e| return e, 769 }; 770 771 try request.respond("", .{ 772 .status = .see_other, 773 .extra_headers = &.{.{ .name = "location", .value = base }}, 774 }); 775 } 776 777 // split an issue url ("/repo/<owner>/<name>/issue:<id>", identity elided in 778 // local mode) into what precedes "/issue:" and the decoded id, null when it 779 // isn't one. the repo base is validated per host in updateIssue. 780 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 781 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 782 const issues_infix = "/issue:"; 783 const id_len = evt.event_id_size * 2; 784 if (base.len < issues_infix.len + id_len) return null; 785 var id_bytes: [evt.event_id_size]u8 = undefined; 786 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 787 const head = base[0 .. base.len - id_len]; 788 if (!std.mem.endsWith(u8, head, issues_infix)) return null; 789 return .{ .repo_base = head[0 .. head.len - issues_infix.len], .id_bytes = id_bytes }; 790 } 791 792 // re-emit the issue `parts` names with `update` applied, in the repo the 793 // host resolves the base to. error.NotFound when the base names no repo or 794 // the id no issue. 795 fn updateIssue( 796 io: std.Io, 797 allocator: std.mem.Allocator, 798 host: Host, 799 parts: IssueBaseParts, 800 update: evt.Issue.Update, 801 author_email: []const u8, 802 ) !void { 803 switch (host) { 804 .remote => |remote| { 805 const repo_prefix = "/repo/"; 806 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 807 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 808 defer allocator.free(repos_dir); 809 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 810 .ok => |p| p, 811 .invalid, .not_found => return error.NotFound, 812 }; 813 defer allocator.free(repo_path); 814 815 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 816 defer repo.deinit(io, allocator); 817 try evt.Issue.update(.xit, .{}, io, allocator, &repo, &parts.id_bytes, update, author_email); 818 }, 819 .local => |src| { 820 // the local forms post to "/issue:<id>/...", so the repo base 821 // is empty 822 if (parts.repo_base.len != 0) return error.NotFound; 823 switch (src.repo_kind) { 824 inline else => |repo_kind| { 825 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 826 defer any_repo.deinit(io, allocator); 827 switch (any_repo) { 828 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author_email), 829 } 830 }, 831 } 832 }, 833 } 834 } 835 836 // set the status of the issue the url names (base is 837 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 838 // re-emitting its event, then redirect back to it 839 fn handleIssueStatus( 840 io: std.Io, 841 request: *std.http.Server.Request, 842 allocator: std.mem.Allocator, 843 base: []const u8, 844 host: Host, 845 status: evt.Issue.Status, 846 ) !void { 847 const not_found = "issue not found"; 848 const parts = issueBaseParts(base) orelse { 849 try request.respond(not_found, .{ 850 .status = .not_found, 851 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 852 }); 853 return; 854 }; 855 856 var author_arena = std.heap.ArenaAllocator.init(allocator); 857 defer author_arena.deinit(); 858 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 859 860 updateIssue(io, allocator, host, parts, .{ .status = status }, author_email) catch |err| switch (err) { 861 error.NotFound => { 862 try request.respond(not_found, .{ 863 .status = .not_found, 864 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 865 }); 866 return; 867 }, 868 else => |e| return e, 869 }; 870 871 // like logout, this is a bodyless POST, so close the connection rather than 872 // letting the keep-alive path try to discard a body that isn't framed. 873 try request.respond("", .{ 874 .status = .see_other, 875 .keep_alive = false, 876 .extra_headers = &.{.{ .name = "location", .value = base }}, 877 }); 878 } 879 880 // replace the title/tags/description of the issue the url names (base is 881 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 882 // form posts to "<base>/edit") by re-emitting its event with its status 883 // preserved, then redirect back to it 884 fn handleIssueEdit( 885 io: std.Io, 886 request: *std.http.Server.Request, 887 allocator: std.mem.Allocator, 888 base: []const u8, 889 host: Host, 890 ) !void { 891 var author_arena = std.heap.ArenaAllocator.init(allocator); 892 defer author_arena.deinit(); 893 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 894 895 var body_buf: [256]u8 = undefined; 896 const reader = request.readerExpectNone(&body_buf); 897 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 898 defer allocator.free(body); 899 900 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 901 defer allocator.free(title); 902 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 903 defer allocator.free(tags); 904 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 905 defer allocator.free(description_crlf); 906 // form submission normalizes textarea line breaks to CRLF; store plain 907 // newlines so the text renders the same on every host 908 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 909 defer allocator.free(description); 910 911 // invalid fields send the user back to the edit form 912 if (!evt.Issue.fieldsValid(title, tags)) { 913 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 914 defer allocator.free(form_location); 915 try request.respond("", .{ 916 .status = .see_other, 917 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 918 }); 919 return; 920 } 921 922 const not_found = "issue not found"; 923 const parts = issueBaseParts(base) orelse { 924 try request.respond(not_found, .{ 925 .status = .not_found, 926 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 927 }); 928 return; 929 }; 930 931 updateIssue(io, allocator, host, parts, .{ .fields = .{ 932 .title = title, 933 .tags = tags, 934 .description = description, 935 } }, author_email) catch |err| switch (err) { 936 error.NotFound => { 937 try request.respond(not_found, .{ 938 .status = .not_found, 939 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 940 }); 941 return; 942 }, 943 else => |e| return e, 944 }; 945 946 try request.respond("", .{ 947 .status = .see_other, 948 .extra_headers = &.{.{ .name = "location", .value = base }}, 949 }); 950 } 951 952 // resolve the conflict of the issue the url names (base is 953 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 954 // form posts to "<base>/resolve") 955 fn handleIssueResolve( 956 io: std.Io, 957 request: *std.http.Server.Request, 958 allocator: std.mem.Allocator, 959 base: []const u8, 960 host: Host, 961 ) !void { 962 var author_arena = std.heap.ArenaAllocator.init(allocator); 963 defer author_arena.deinit(); 964 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 965 966 var body_buf: [256]u8 = undefined; 967 const reader = request.readerExpectNone(&body_buf); 968 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 969 defer allocator.free(body); 970 971 var field_arena = std.heap.ArenaAllocator.init(allocator); 972 defer field_arena.deinit(); 973 const aa = field_arena.allocator(); 974 const title = try parseFormField(aa, body, "title"); 975 const tags = try parseFormField(aa, body, "tags"); 976 977 // the hunk inputs post as d0, d1, ...; form submission normalizes their 978 // textarea line breaks to CRLF 979 var hunks: std.ArrayList([]const u8) = .empty; 980 var hunk_index: usize = 0; 981 while (true) : (hunk_index += 1) { 982 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 983 const posted = (try parseFormField(aa, body, name)) orelse break; 984 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 985 } 986 987 const not_found = "issue not found"; 988 const parts = issueBaseParts(base) orelse { 989 try request.respond(not_found, .{ 990 .status = .not_found, 991 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 992 }); 993 return; 994 }; 995 996 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 997 .title = title, 998 .tags = tags, 999 .hunks = hunks.items, 1000 } }, author_email) catch |err| switch (err) { 1001 error.NotFound => { 1002 try request.respond(not_found, .{ 1003 .status = .not_found, 1004 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1005 }); 1006 return; 1007 }, 1008 // invalid fields send the user back to the resolve form 1009 error.InvalidFields => { 1010 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1011 defer allocator.free(form_location); 1012 try request.respond("", .{ 1013 .status = .see_other, 1014 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1015 }); 1016 return; 1017 }, 1018 else => |e| return e, 1019 }; 1020 1021 try request.respond("", .{ 1022 .status = .see_other, 1023 .extra_headers = &.{.{ .name = "location", .value = base }}, 1024 }); 1025 } 1026 1027 fn renderIndexHtml( 1028 io: std.Io, 1029 allocator: std.mem.Allocator, 1030 host: Host, 1031 session_data: ui.Session.Data, 1032 ) ![]const u8 { 1033 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1034 1035 var page_arena = std.heap.ArenaAllocator.init(allocator); 1036 defer page_arena.deinit(); 1037 1038 // the remote admin repo must outlive the page build, since the session's 1039 // moment reads from it. 1040 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1041 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1042 1043 var session = switch (host) { 1044 .remote => |remote| blk: { 1045 // open the admin repo to read live user/repo data. 1046 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1047 const repo = if (repo_maybe) |*repo| repo else unreachable; 1048 var session = try ui.Session.init(&page_arena, repo, session_data); 1049 // give the page builders filesystem access to the on-disk repos (a 1050 // sibling "repos" dir next to the admin repo) so the Repo page can 1051 // read its files. 1052 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1053 break :blk session; 1054 }, 1055 .local => |local| ui.Session{ 1056 .data = session_data, 1057 .arena = &page_arena, 1058 .page_arena = &page_arena, 1059 .local = local, 1060 }, 1061 }; 1062 session.io = io; 1063 1064 const snapshot: ui.Snapshot = .{ 1065 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 1066 .session = session.data, 1067 }; 1068 var root = try ui.initRoot(allocator, &snapshot.page, &session); 1069 defer root.deinit(allocator); 1070 1071 const content = try generateHtml(allocator, &root); 1072 defer allocator.free(content); 1073 const overlay = try generateOverlay(allocator, &root, &session); 1074 defer allocator.free(overlay); 1075 1076 // serialize the snapshot so the wasm side can parse it back without making 1077 // a second request. it's embedded raw in a <script type="application/json"> 1078 // block, whose content is raw text terminated only by "</script". in json, 1079 // '<' appears solely inside string values, so escaping every '<' (and '>' 1080 // for good measure) to its \uXXXX form yields equivalent json that can't 1081 // break out of the tag. 1082 var json: std.Io.Writer.Allocating = .init(allocator); 1083 defer json.deinit(); 1084 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1085 1086 var json_escaped: std.ArrayList(u8) = .empty; 1087 defer json_escaped.deinit(allocator); 1088 for (json.written()) |c| switch (c) { 1089 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1090 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1091 else => try json_escaped.append(allocator, c), 1092 }; 1093 1094 var out: std.ArrayList(u8) = .empty; 1095 errdefer out.deinit(allocator); 1096 { 1097 var cursor: usize = 0; 1098 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1099 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1100 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1101 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1102 }) |sub| { 1103 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1104 try out.appendSlice(allocator, template[cursor..idx]); 1105 try out.appendSlice(allocator, sub.replacement); 1106 cursor = idx + sub.needle.len; 1107 } 1108 try out.appendSlice(allocator, template[cursor..]); 1109 } 1110 return try out.toOwnedSlice(allocator); 1111 } 1112 1113 fn findEmbed(request_path: []const u8) ?Embed { 1114 const path = if (std.mem.eql(u8, request_path, "/")) 1115 "index.html" 1116 else if (request_path.len > 1 and request_path[0] == '/') 1117 request_path[1..] 1118 else 1119 return null; 1120 1121 for (embeds) |embed| { 1122 if (std.mem.eql(u8, path, embed.path)) return embed; 1123 } 1124 return null; 1125 } 1126 1127 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1128 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1129 // rendered recursively so nested scrolls work. 1130 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1131 const grid = root.getGrid() orelse return error.MissingGrid; 1132 1133 var out: std.ArrayList(u8) = .empty; 1134 errdefer out.deinit(allocator); 1135 1136 try renderPanel(allocator, &out, root.getFocus(), grid); 1137 return try out.toOwnedSlice(allocator); 1138 } 1139 1140 // render one panel — a focus subtree and its content grid — as HTML, recursing 1141 // once per web-native Scroll inside it. the root panel is the whole page; each 1142 // Scroll becomes a nested, natively-scrollable div holding its full content. 1143 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1144 // then the child scroll divs over those holes. 1145 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1146 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1147 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1148 // plus their descendants, which the focus tree flattens into this panel's 1149 // children): the cell hit-test below skips them so this panel doesn't claim 1150 // cells that are really rendered inside a child scroll's own panel. 1151 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1152 var direct: std.ArrayList(usize) = .empty; 1153 defer direct.deinit(allocator); 1154 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1155 defer excluded.deinit(allocator); 1156 { 1157 var it = focus.children.iterator(); 1158 while (it.next()) |e| { 1159 if (e.value_ptr.focus.scroll == null) continue; 1160 try direct.append(allocator, e.key_ptr.*); 1161 try excluded.put(allocator, e.key_ptr.*, {}); 1162 var mit = e.value_ptr.focus.children.iterator(); 1163 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1164 } 1165 } 1166 1167 // the HTML element a run of cells is wrapped in, chosen from the cell's 1168 // focusable kind 1169 const CellTag = union(enum) { 1170 span, // clickable focusable cell 1171 a: []const u8, // clickable focusable link 1172 plain, // non-focusable, colored 1173 1174 const a_prefix = "a:"; 1175 // an "in-page" anchor: rendered as a real <a href> so it works with js 1176 // disabled, but crossPageLink ignores it, so with wasm the click just 1177 // moves focus rather than navigating. 1178 const inpage_prefix = "ai:"; 1179 1180 fn init(str: []const u8) @This() { 1181 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1182 return .{ .a = str[inpage_prefix.len..] }; 1183 } 1184 if (std.mem.startsWith(u8, str, a_prefix)) { 1185 return .{ .a = str[a_prefix.len..] }; 1186 } 1187 return .span; 1188 } 1189 1190 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1191 var id_buf: [32]u8 = undefined; 1192 switch (self) { 1193 .span => { 1194 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1195 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1196 try out.appendSlice(alloc, "\""); 1197 try out.appendSlice(alloc, style_attr); 1198 try out.appendSlice(alloc, ">"); 1199 }, 1200 .a => |href| { 1201 // tabindex=-1 keeps these out of the browser's tab order 1202 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1203 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1204 try out.appendSlice(alloc, "\" href=\""); 1205 try appendEscapedHtml(alloc, out, href); 1206 try out.appendSlice(alloc, "\""); 1207 try out.appendSlice(alloc, style_attr); 1208 try out.appendSlice(alloc, ">"); 1209 }, 1210 .plain => { 1211 try out.appendSlice(alloc, "<span"); 1212 try out.appendSlice(alloc, style_attr); 1213 try out.appendSlice(alloc, ">"); 1214 }, 1215 } 1216 } 1217 1218 fn closeTag(self: @This()) []const u8 { 1219 return switch (self) { 1220 .span, .plain => "</span>", 1221 .a => "</a>", 1222 }; 1223 } 1224 }; 1225 1226 // emit this panel's grid as rows of text, coalescing adjacent cells that 1227 // share a focus id and colors into one tag (a clickable span, a link, or a 1228 // plain colored span). cells under a child scroll keep only their background. 1229 for (0..grid.size.height) |y| { 1230 var cur_id: ?usize = null; 1231 var cur_fg: ?Grid.Color = null; 1232 var cur_bg: ?Grid.Color = null; 1233 var open_tag: ?CellTag = null; 1234 var first = true; 1235 for (0..grid.size.width) |x| { 1236 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1237 // a cell covered by a child scroll's viewport is drawn by that scroll's 1238 // own div, so blank its glyph and make it non-clickable here — but keep 1239 // its background, so the backdrop still shows through the scroll's 1240 // transparent div instead of a bare hole. 1241 const covered_by_scroll = blk: { 1242 for (direct.items) |id| { 1243 const r = (focus.children.get(id) orelse continue).rect; 1244 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; 1245 } 1246 break :blk false; 1247 }; 1248 // the focusable cell at (x, y) among this panel's own focusables (skipping 1249 // any that belong to a child scroll, whose cells are drawn in their own 1250 // panel); none for a covered cell. 1251 const cell_id = if (covered_by_scroll) null else blk: { 1252 var iter = focus.children.iterator(); 1253 while (iter.next()) |entry| { 1254 const child = entry.value_ptr.*; 1255 if (!child.focus.focusable) continue; 1256 if (excluded.contains(entry.key_ptr.*)) continue; 1257 const r = child.rect; 1258 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1259 break :blk entry.key_ptr.*; 1260 } 1261 } 1262 break :blk null; 1263 }; 1264 const fg = if (covered_by_scroll) null else cell.style.fg; 1265 const bg = cell.style.bg; 1266 1267 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1268 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1269 1270 var new_tag: ?CellTag = null; 1271 if (cell_id) |id| { 1272 if (focus.children.get(id)) |child| { 1273 new_tag = switch (child.focus.kind) { 1274 .custom => |custom| CellTag.init(custom), 1275 else => .span, 1276 }; 1277 } 1278 } 1279 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1280 1281 if (new_tag) |t| { 1282 var style_buf: [64]u8 = undefined; 1283 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1284 } 1285 1286 open_tag = new_tag; 1287 cur_id = cell_id; 1288 cur_fg = fg; 1289 cur_bg = bg; 1290 first = false; 1291 } 1292 1293 if (covered_by_scroll) { 1294 try appendEscapedHtml(allocator, output, " "); 1295 } else if (cell.continuation) { 1296 // the wide rune to the left was emitted 2ch wide, covering this column 1297 } else if (cell.rune) |rune| { 1298 // a double-width rune is pinned inside a 2ch span so the 1299 // fallback glyph's advance width can't shift the rest of the row 1300 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1301 if (wide) { 1302 try output.appendSlice(allocator, "<span class=\"w2\">"); 1303 try appendEscapedHtml(allocator, output, rune); 1304 try output.appendSlice(allocator, "</span>"); 1305 } else { 1306 try appendEscapedHtml(allocator, output, rune); 1307 } 1308 } else { 1309 try appendEscapedHtml(allocator, output, " "); 1310 } 1311 } 1312 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1313 try output.append(allocator, '\n'); 1314 } 1315 1316 // each child scroll becomes a natively-scrollable div positioned over its 1317 // viewport, holding its full content rendered recursively. 1318 for (direct.items) |id| { 1319 const child = focus.children.get(id) orelse continue; 1320 const info = child.focus.scroll orelse continue; 1321 const r = child.rect; 1322 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1323 // when that axis actually overflows. the other axis is clipped (hidden), 1324 // matching how the terminal Scroll handles its non-scrolling axis. 1325 const overflow = switch (info.direction) { 1326 .vert => "overflow-x:hidden;overflow-y:auto", 1327 .horiz => "overflow-x:auto;overflow-y:hidden", 1328 .both => "overflow:auto", 1329 }; 1330 // the id carries a content version so JS preserves the native scroll 1331 // position across re-renders of the same content but resets it when the 1332 // content is replaced — e.g. selecting a different commit. the widget's 1333 // scroll offset (in cells) rides along so JS can apply it when it has no 1334 // preserved position, letting a wasm-side scrollToRect (the files list 1335 // scrolling to its selected row on page load) reach the browser. 1336 var buf: [224]u8 = undefined; 1337 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 })); 1338 try renderPanel(allocator, output, child.focus, info.content); 1339 try output.appendSlice(allocator, "</div>"); 1340 } 1341 } 1342 1343 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1344 // widget tree, each wrapping the text inputs and submit button inside it, 1345 // positioned absolutely over the matching grid cells. 1346 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1347 const root_focus = root.getFocus(); 1348 1349 var out: std.ArrayList(u8) = .empty; 1350 errdefer out.deinit(allocator); 1351 1352 const form_prefix = "form:"; 1353 1354 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1355 // which matches the order widgets were added in code 1356 var iter = root_focus.children.iterator(); 1357 while (iter.next()) |entry| { 1358 const child = entry.value_ptr.*; 1359 const action_url = switch (child.focus.kind) { 1360 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1361 custom[form_prefix.len..] 1362 else 1363 continue, 1364 else => continue, 1365 }; 1366 1367 try out.appendSlice(allocator, "<form action=\""); 1368 try appendEscapedHtml(allocator, &out, action_url); 1369 try out.appendSlice(allocator, "\" method=\"post\""); 1370 // an empty action must not POST — block it and send the input to the TUI instead 1371 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1372 try out.appendSlice(allocator, ">"); 1373 1374 // form.focus.children was populated by addChild, which flattens the 1375 // whole subtree into one map — so descendants (inputs + the submit 1376 // button) all appear here. positions on form.focus are relative to 1377 // the form, so we look up absolute rects via root_focus for layout. 1378 var inner_iter = child.focus.children.iterator(); 1379 while (inner_iter.next()) |inner_entry| { 1380 const inner_id = inner_entry.key_ptr.*; 1381 const root_child = root_focus.children.get(inner_id) orelse continue; 1382 const r = root_child.rect; 1383 switch (root_child.focus.kind) { 1384 .text_input, .text_input_password => { 1385 const ti = session.text_inputs.get(inner_id) orelse continue; 1386 const inner_left = r.x + 1; 1387 const inner_top = r.y + 1; 1388 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1389 1390 try out.appendSlice(allocator, "<input type=\""); 1391 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1392 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1393 var id_buf: [32]u8 = undefined; 1394 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1395 if (ti.options.name.len > 0) { 1396 try out.appendSlice(allocator, "\" name=\""); 1397 try appendEscapedHtml(allocator, &out, ti.options.name); 1398 } 1399 // never the live content as the `value`: the browser tracks user 1400 // input natively, and including the wasm-side value here would make 1401 // the overlay HTML differ on every keystroke — that would trip the 1402 // diff in _setOverlay and rebuild the <input>, eating the user's 1403 // caret. a page-constant initial value is safe. 1404 if (session.input_values.get(inner_id)) |value| { 1405 try out.appendSlice(allocator, "\" value=\""); 1406 try appendEscapedHtml(allocator, &out, value); 1407 } 1408 try out.appendSlice(allocator, "\" style=\"left:"); 1409 var pos_buf: [64]u8 = undefined; 1410 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 })); 1411 try out.appendSlice(allocator, "\">"); 1412 }, 1413 .text_area => { 1414 const ti = session.text_inputs.get(inner_id) orelse continue; 1415 const inner_left = r.x + 1; 1416 const inner_top = r.y + 1; 1417 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1418 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1419 1420 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1421 var id_buf: [32]u8 = undefined; 1422 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1423 if (ti.options.name.len > 0) { 1424 try out.appendSlice(allocator, "\" name=\""); 1425 try appendEscapedHtml(allocator, &out, ti.options.name); 1426 } 1427 // like the input above, only a page-constant initial value 1428 // inside: the browser tracks the live value and the 1429 // overlay diff must stay stable across keystrokes 1430 try out.appendSlice(allocator, "\" style=\"left:"); 1431 var pos_buf: [128]u8 = undefined; 1432 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 })); 1433 // textarea discards the first newline immediately following 1434 // its start tag, so add one of our own so text that begins 1435 // with a newline doesn't lose it 1436 try out.appendSlice(allocator, "\">\n"); 1437 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1438 try out.appendSlice(allocator, "</textarea>"); 1439 }, 1440 .custom => |custom| { 1441 if (std.mem.eql(u8, "submit", custom)) { 1442 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1443 var id_buf: [32]u8 = undefined; 1444 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1445 try out.appendSlice(allocator, "\" style=\"left:"); 1446 var pos_buf: [128]u8 = undefined; 1447 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 })); 1448 try out.appendSlice(allocator, "\"></button>"); 1449 } 1450 }, 1451 else => {}, 1452 } 1453 } 1454 1455 try out.appendSlice(allocator, "</form>"); 1456 } 1457 1458 return try out.toOwnedSlice(allocator); 1459 } 1460 1461 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1462 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1463 return b == null; 1464 } 1465 1466 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1467 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1468 // empty slice when neither is set. 1469 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1470 if (fg == null and bg == null) return buf[0..0]; 1471 const prefix = " style=\""; 1472 @memcpy(buf[0..prefix.len], prefix); 1473 var i: usize = prefix.len; 1474 if (fg) |c| { 1475 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]; 1476 i += s.len; 1477 } 1478 if (bg) |c| { 1479 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]; 1480 i += s.len; 1481 } 1482 buf[i] = '"'; 1483 i += 1; 1484 return buf[0..i]; 1485 } 1486 1487 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1488 for (input) |ch| { 1489 switch (ch) { 1490 '&' => try out.appendSlice(allocator, "&amp;"), 1491 '<' => try out.appendSlice(allocator, "&lt;"), 1492 '>' => try out.appendSlice(allocator, "&gt;"), 1493 '"' => try out.appendSlice(allocator, "&quot;"), 1494 '\'' => try out.appendSlice(allocator, "&#39;"), 1495 else => try out.append(allocator, ch), 1496 } 1497 } 1498 } 1499 1500 // --- helpers -------------------------------------------------------------- 1501 1502 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1503 var iter = request.iterateHeaders(); 1504 while (iter.next()) |header| { 1505 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1506 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1507 while (pairs.next()) |pair| { 1508 const trimmed = std.mem.trim(u8, pair, " \t"); 1509 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1510 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1511 return trimmed[eq + 1 ..]; 1512 } 1513 } 1514 } 1515 return null; 1516 } 1517 1518 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1519 var iter = std.mem.splitScalar(u8, body, '&'); 1520 while (iter.next()) |pair| { 1521 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1522 if (std.mem.eql(u8, pair[0..eq], key)) { 1523 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1524 } 1525 } 1526 return null; 1527 } 1528 1529 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1530 var out: std.ArrayList(u8) = .empty; 1531 errdefer out.deinit(allocator); 1532 var i: usize = 0; 1533 while (i < encoded.len) : (i += 1) { 1534 switch (encoded[i]) { 1535 '+' => try out.append(allocator, ' '), 1536 '%' => { 1537 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1538 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1539 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1540 try out.append(allocator, hi * 16 + lo); 1541 i += 2; 1542 }, 1543 else => try out.append(allocator, encoded[i]), 1544 } 1545 } 1546 return try out.toOwnedSlice(allocator); 1547 } 1548 1549 // disk-backed web session store. each login mints a random, opaque token 1550 // (not the user's id) that is stored as a file named by the token hex, whose 1551 // contents are the raw user_id bytes. authenticating a request is a lookup of 1552 // the cookie's token; logout deletes the file, revoking the session. there is 1553 // deliberately no expiry — a session lives until logout. 1554 pub const SessionStore = struct { 1555 io: std.Io, 1556 dir: std.Io.Dir, 1557 1558 pub const token_hex_len = evt.event_id_size * 2; 1559 1560 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1561 try data_dir.createDirPath(io, "sessions"); 1562 const dir = try data_dir.openDir(io, "sessions", .{}); 1563 return .{ .io = io, .dir = dir }; 1564 } 1565 1566 pub fn deinit(self: SessionStore) void { 1567 self.dir.close(self.io); 1568 } 1569 1570 // mint a new session for user_id, returning the token hex to set as the 1571 // cookie value. 1572 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1573 var token: [evt.event_id_size]u8 = undefined; 1574 self.io.random(&token); 1575 const token_hex = std.fmt.bytesToHex(token, .lower); 1576 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1577 defer file.close(self.io); 1578 try file.writeStreamingAll(self.io, user_id); 1579 return token_hex; 1580 } 1581 1582 // resolve a cookie's token to its user_id. returns false (logged out) for a 1583 // missing, malformed, or unknown token. 1584 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1585 if (!isToken(token_hex)) return false; 1586 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1587 defer file.close(self.io); 1588 var storage: [evt.event_id_size]u8 = undefined; 1589 var file_reader = file.reader(self.io, &storage); 1590 file_reader.interface.readSliceAll(out) catch return false; 1591 return true; 1592 } 1593 1594 // revoke a session. a no-op for a missing or malformed token. 1595 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1596 if (!isToken(token_hex)) return; 1597 self.dir.deleteFile(self.io, token_hex) catch {}; 1598 } 1599 1600 // leave `token_hex`'s session for the next visitor arriving without one. 1601 // only the `try` fixture writes one, and only a debug build honors it. the 1602 // name isn't token-shaped, so it can't collide with a session file. 1603 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1604 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1605 defer file.close(self.io); 1606 try file.writeStreamingAll(self.io, token_hex); 1607 } 1608 1609 // claim the offered session, if one is there. the delete picks the winner 1610 // of a race, so the offer is only ever taken once. a release build never 1611 // looks, because that would be an extra syscall for every GET request. 1612 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1613 if (builtin.mode != .Debug) return false; 1614 { 1615 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1616 defer file.close(self.io); 1617 var storage: [token_hex_len]u8 = undefined; 1618 var file_reader = file.reader(self.io, &storage); 1619 file_reader.interface.readSliceAll(out) catch return false; 1620 } 1621 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1622 return true; 1623 } 1624 1625 const auto_login_name = "auto-login"; 1626 1627 // a token is exactly token_hex_len hex chars. validating before using the 1628 // value as a path keeps attacker-supplied cookies from escaping the 1629 // sessions dir (e.g. via "/" or ".." bytes). 1630 fn isToken(token_hex: []const u8) bool { 1631 if (token_hex.len != token_hex_len) return false; 1632 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1633 return true; 1634 } 1635 }; 1636