╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
498 fn handleThreadNew( 499 io: std.Io, 500 request: *std.http.Server.Request, 501 allocator: std.mem.Allocator, 502 base: []const u8, 503 host: Host, 504 kind: evt.EventKind, 505 ) !void { 506 var author_arena = std.heap.ArenaAllocator.init(allocator); 507 defer author_arena.deinit(); 508 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 509 const author = request_author.author; 510 const body = try readFormBody(request, allocator); 511 defer allocator.free(body); 512 513 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 514 defer allocator.free(title); 515 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 516 defer allocator.free(tags); 517 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 518 defer allocator.free(description_crlf); 519 // form submission normalizes textarea line breaks to CRLF; store plain 520 // newlines so the text renders the same on every host 521 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 522 defer allocator.free(description); 523 524 const valid = switch (kind) { 525 .issue => evt.Issue.fieldsValid(title, tags), 526 .patch => evt.Patch.fieldsValid(title, tags), 527 .discuss => evt.Discussion.fieldsValid(title, tags), 528 else => unreachable, 529 }; 530 if (!valid) { 531 const list_name: []const u8 = switch (kind) { 532 .issue => "issues", 533 .patch => "patches", 534 .discuss => "discussions", 535 else => unreachable, 536 }; 537 const form_location = try std.fmt.allocPrint(allocator, "{s}/{s}/new", .{ base, list_name }); 538 defer allocator.free(form_location); 539 try request.respond("", .{ 540 .status = .see_other, 541 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 542 }); 543 return; 544 } 545 546 var id_bytes: [evt.event_id_size]u8 = undefined; 547 io.random(&id_bytes); 548 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 549 550 if (kind == .patch) { 551 const remote = switch (host) { 552 .remote => |remote| remote, 553 .local => return respondRemoveNotFound(request), 554 }; 555 const user_id = request_author.user_id orelse return respondLoginRequired(request); 556 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse return respondRemoveNotFound(request); 557 defer request_repo.deinit(allocator); 558 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 559 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 560 defer admin_repo.deinit(io, allocator); 561 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 562 defer allocator.free(repos_dir); 563 const fork_path = try fork.create(.{}, io, allocator, repos_dir, &admin_repo, .{ 564 .id = event_id_hex, 565 .user_id = user_id, 566 .repo_id = repo_id, 567 .title = title, 568 .description = description, 569 .tags = tags, 570 .author = author, 571 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 572 }); 573 defer allocator.free(fork_path); 574 const location = try std.fmt.allocPrint(allocator, "{s}/patch:{s}", .{ base, &event_id_hex }); 575 defer allocator.free(location); 576 try request.respond("", .{ .status = .see_other, .extra_headers = &.{.{ .name = "location", .value = location }} }); 577 return; 578 } 579 580 const event = evt.EventWithId{ 581 .id = event_id_hex, 582 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 583 .author = author, 584 .event = switch (kind) { 585 .issue => .{ .issue = .{ .title = title, .description = description, .tags = tags } }, 586 .patch => unreachable, 587 .discuss => .{ .discuss = .{ .title = title, .description = description, .tags = tags } }, 588 else => unreachable, 589 }, 590 }; 591 592 const not_found = "repo not found"; 593 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse { 594 try request.respond(not_found, .{ 595 .status = .not_found, 596 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 597 }); 598 return; 599 }; 600 defer request_repo.deinit(allocator); 601 const source = request_repo.source; 602 switch (source.repo_kind) { 603 inline else => |repo_kind| { 604 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 605 defer any_repo.deinit(io, allocator); 606 switch (any_repo) { 607 inline else => |*repo| try evt.consume(.repo, repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &[_]evt.EventWithId{event}), 608 } 609 }, 610 } 611 612 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 613 defer allocator.free(location); 614 try request.respond("", .{ 615 .status = .see_other, 616 .extra_headers = &.{.{ .name = "location", .value = location }}, 617 }); 618 } 619 620 const CommentBaseParts = struct { 621 repo_base: []const u8, 622 thread_kind: evt.EventKind, 623 thread_id: [evt.event_id_size]u8, 624 comment_id: ?[evt.event_id_size]u8, 625 }; 626 627 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 628 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse return null; 629 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 630 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 631 .repo_patches => |*patch| .{ patch.name.slice(), evt.EventKind.patch, patch.selected.slice(), patch.comment.slice() }, 632 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discuss, discussion.selected.slice(), discussion.comment.slice() }, 633 else => return null, 634 }; 635 const thread_id = evt.parseEventId(thread_hex) catch return null; 636 const comment_id = if (comment_hex.len == 0) null else evt.parseEventId(comment_hex) catch return null; 637 const repo_base_len = if (identity.len == 0) 0 else "/repo/".len + identity.len; 638 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 639 } 640 641 fn handlePatchPublish( 642 io: std.Io, 643 request: *std.http.Server.Request, 644 allocator: std.mem.Allocator, 645 base: []const u8, 646 host: Host, 647 ) !void { 648 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 649 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 650 const remote = switch (host) { 651 .remote => |remote| remote, 652 .local => return respondRemoveNotFound(request), 653 }; 654 var author_arena = std.heap.ArenaAllocator.init(allocator); 655 defer author_arena.deinit(); 656 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 657 const user_id = request_author.user_id orelse return respondLoginRequired(request); 658 const author = request_author.author; 659 660 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 661 defer request_repo.deinit(allocator); 662 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 663 var target_repo = try rp.Repo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 664 defer target_repo.deinit(io, allocator); 665 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 666 defer admin_repo.deinit(io, allocator); 667 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 668 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 669 defer allocator.free(repos_dir); 670 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 671 defer allocator.free(fork_path); 672 try pch.publish(.{}, io, allocator, &admin_repo, &target_repo, fork_path, .{ 673 .id = id, 674 .user_id = user_id, 675 .repo_id = repo_id, 676 .author = author, 677 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 678 }); 679 try request.respond("", .{ 680 .status = .see_other, 681 .extra_headers = &.{.{ .name = "location", .value = base }}, 682 }); 683 } 684 685 // create a reply and redirect to its permalink. 686 fn handleCommentNew( 687 io: std.Io, 688 request: *std.http.Server.Request, 689 allocator: std.mem.Allocator, 690 base: []const u8, 691 host: Host, 692 ) !void { 693 const not_found = "comment parent not found"; 694 const parts = commentBaseParts(base) orelse { 695 try request.respond(not_found, .{ 696 .status = .not_found, 697 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 698 }); 699 return; 700 }; 701 702 var author_arena = std.heap.ArenaAllocator.init(allocator); 703 defer author_arena.deinit(); 704 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 705 706 const form_body = try readFormBody(request, allocator); 707 defer allocator.free(form_body); 708 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 709 defer allocator.free(body_crlf); 710 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 711 defer allocator.free(body); 712 713 if (!evt.Comment.fieldsValid(body)) { 714 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 715 defer allocator.free(form_location); 716 try request.respond("", .{ 717 .status = .see_other, 718 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 719 }); 720 return; 721 } 722 723 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 724 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 725 726 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 727 try request.respond(not_found, .{ 728 .status = .not_found, 729 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 730 }); 731 return; 732 }; 733 defer request_repo.deinit(allocator); 734 const source = request_repo.source; 735 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 736 switch (source.repo_kind) { 737 inline else => |repo_kind| { 738 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 739 defer any_repo.deinit(io, allocator); 740 switch (any_repo) { 741 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), 742 } 743 }, 744 } 745 746 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}/comment:{s}", .{ parts.repo_base, @tagName(parts.thread_kind), &thread_id_hex, &event_id_hex }); 747 defer allocator.free(location); 748 try request.respond("", .{ 749 .status = .see_other, 750 .extra_headers = &.{.{ .name = "location", .value = location }}, 751 }); 752 } 753 754 const AttachmentRequest = struct { 755 repo_base: []const u8, 756 id: [evt.event_id_size]u8, 757 }; 758 759 // an attachment url is its repo's base and the attachment's event id 760 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 761 const infix = "/attachment:"; 762 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 763 const tail = path[at + infix.len ..]; 764 const id = evt.parseEventId(tail) catch return null; 765 return .{ .repo_base = path[0..at], .id = id }; 766 } 767 768 // serve an attachment's bytes from the repo its url names 769 fn serveAttachment( 770 io: std.Io, 771 request: *std.http.Server.Request, 772 allocator: std.mem.Allocator, 773 attachment: AttachmentRequest, 774 host: Host, 775 ) !void { 776 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 777 defer request_repo.deinit(allocator); 778 const source = request_repo.source; 779 switch (source.repo_kind) { 780 inline else => |repo_kind| { 781 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 782 defer any_repo.deinit(io, allocator); 783 switch (any_repo) { 784 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 785 } 786 }, 787 } 788 } 789 790 fn sendAttachment( 791 comptime repo_kind: rp.RepoKind, 792 comptime repo_opts: rp.RepoOpts(repo_kind), 793 io: std.Io, 794 request: *std.http.Server.Request, 795 allocator: std.mem.Allocator, 796 repo: *rp.Repo(repo_kind, repo_opts), 797 id: *const [evt.event_id_size]u8, 798 ) !void { 799 var arena = std.heap.ArenaAllocator.init(allocator); 800 defer arena.deinit(); 801 802 const DB = evt.EventDB(repo_opts.hash); 803 var event_db_maybe: ?evt.LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try evt.LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 804 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 805 const haxy_moment = (if (event_db_maybe) |*event_db| 806 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 807 else if (repo_kind == .git) 808 return respondAttachmentNotFound(request) 809 else 810 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 811 812 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 813 if (record.removed) return respondAttachmentNotFound(request); 814 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 815 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 816 817 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 818 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 819 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 820 defer object_reader.deinit(); 821 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 822 823 const content_type = attachmentContentType(record.name); 824 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 825 defer allocator.free(encoded_name); 826 const disposition = try std.fmt.allocPrint(allocator, "{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 827 defer allocator.free(disposition); 828 829 var send_buf: [8192]u8 = undefined; 830 var body = try request.respondStreaming(&send_buf, .{ 831 .content_length = object_reader.header().size, 832 .respond_options = .{ 833 .extra_headers = &.{ 834 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 835 .{ .name = "content-disposition", .value = disposition }, 836 // uploaded bytes are never sniffed into a type that could run 837 // as script on this origin 838 .{ .name = "x-content-type-options", .value = "nosniff" }, 839 }, 840 }, 841 }); 842 _ = try object_reader.interface.streamRemaining(&body.writer); 843 try body.end(); 844 } 845 846 // the images a browser renders safely inline. anything else downloads as 847 // opaque bytes, so an uploaded page can't run on this origin. 848 fn attachmentContentType(name: []const u8) ?[]const u8 { 849 const types = [_]struct { ext: []const u8, value: []const u8 }{ 850 .{ .ext = ".png", .value = "image/png" }, 851 .{ .ext = ".jpg", .value = "image/jpeg" }, 852 .{ .ext = ".jpeg", .value = "image/jpeg" }, 853 .{ .ext = ".gif", .value = "image/gif" }, 854 .{ .ext = ".webp", .value = "image/webp" }, 855 }; 856 for (types) |entry| { 857 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 858 } 859 return null; 860 } 861 862 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 863 try request.respond("attachment not found", .{ 864 .status = .not_found, 865 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 866 }); 867 } 868 869 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 870 try request.respond("attachment parent not found", .{ 871 .status = .not_found, 872 .keep_alive = false, 873 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 874 }); 875 } 876 877 // the upload declares its file's name here, since the body is the file itself 878 const attachment_name_header = "x-attachment-name"; 879 880 const AttachParentParts = struct { 881 repo_base: []const u8, 882 id_bytes: [evt.event_id_size]u8, 883 }; 884 885 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 886 // with, whatever kind that is 887 fn attachParentParts(base: []const u8) ?AttachParentParts { 888 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 889 const segment = base[segment_at + 1 ..]; 890 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 891 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 892 return .{ .repo_base = base[0..segment_at], .id_bytes = id_bytes }; 893 } 894 895 // attach the uploaded file to the event the url names, then reload. the file is 896 // the whole request body, so it streams from the socket into the object store 897 // without being buffered. 898 fn handleAttach( 899 io: std.Io, 900 request: *std.http.Server.Request, 901 allocator: std.mem.Allocator, 902 base: []const u8, 903 host: Host, 904 ) !void { 905 const parts = attachParentParts(base) orelse return respondAttachmentParentNotFound(request); 906 907 var author_arena = std.heap.ArenaAllocator.init(allocator); 908 defer author_arena.deinit(); 909 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 910 911 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 912 defer allocator.free(name); 913 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 914 915 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 916 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 917 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 918 919 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 920 921 var body_buf: [4096]u8 = undefined; 922 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 923 924 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 925 defer request_repo.deinit(allocator); 926 const source = request_repo.source; 927 switch (source.repo_kind) { 928 inline else => |repo_kind| { 929 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 930 defer any_repo.deinit(io, allocator); 931 switch (any_repo) { 932 inline else => |*repo| _ = evt.Attachment.create(repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 933 error.ParentNotFound => return respondAttachmentParentNotFound(request), 934 else => return err, 935 }, 936 } 937 }, 938 } 939 940 // the client reloads the page itself 941 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 942 } 943 944 // the name the upload declares for its file, percent-encoded so it survives a 945 // header 946 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 947 var iter = request.iterateHeaders(); 948 while (iter.next()) |header| { 949 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 950 return try decodeFormValue(allocator, header.value); 951 } 952 return null; 953 } 954 955 // an upload that failed leaves the body partly read, so the connection closes 956 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 957 try request.respond(message, .{ 958 .status = status, 959 .keep_alive = false, 960 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 961 }); 962 } 963 964 // re-emit the comment `parts` names with a new body, in the repo the host 965 // resolves the base to. 966 fn updateComment( 967 io: std.Io, 968 allocator: std.mem.Allocator, 969 host: Host, 970 parts: CommentBaseParts, 971 body: []const u8, 972 author: evt.CommitAuthor, 973 ) !void { 974 const comment_id = parts.comment_id orelse return error.NotFound; 975 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 976 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 977 defer request_repo.deinit(allocator); 978 const source = request_repo.source; 979 switch (source.repo_kind) { 980 inline else => |repo_kind| { 981 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 982 defer any_repo.deinit(io, allocator); 983 switch (any_repo) { 984 inline else => |*repo| try evt.Comment.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 985 } 986 }, 987 } 988 } 989 990 // edit actions share a suffix; the base identifies the event being edited. 991 fn handleEdit( 992 io: std.Io, 993 request: *std.http.Server.Request, 994 allocator: std.mem.Allocator, 995 base: []const u8, 996 host: Host, 997 ) !void { 998 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 999 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1000 return handleThreadEdit(io, request, allocator, base, host, parts); 1001 } 1002 1003 // replace the body of the comment the url names, then redirect to its 1004 // permalink. 1005 fn handleCommentEdit( 1006 io: std.Io, 1007 request: *std.http.Server.Request, 1008 allocator: std.mem.Allocator, 1009 base: []const u8, 1010 host: Host, 1011 parts: CommentBaseParts, 1012 ) !void { 1013 var author_arena = std.heap.ArenaAllocator.init(allocator); 1014 defer author_arena.deinit(); 1015 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1016 1017 const form_body = try readFormBody(request, allocator); 1018 defer allocator.free(form_body); 1019 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1020 defer allocator.free(body_crlf); 1021 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1022 defer allocator.free(body); 1023 1024 if (!evt.Comment.fieldsValid(body)) { 1025 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1026 defer allocator.free(form_location); 1027 try request.respond("", .{ 1028 .status = .see_other, 1029 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1030 }); 1031 return; 1032 } 1033 1034 const not_found = "comment not found"; 1035 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1036 error.NotFound => { 1037 try request.respond(not_found, .{ 1038 .status = .not_found, 1039 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1040 }); 1041 return; 1042 }, 1043 else => |e| return e, 1044 }; 1045 1046 try request.respond("", .{ 1047 .status = .see_other, 1048 .extra_headers = &.{.{ .name = "location", .value = base }}, 1049 }); 1050 } 1051 1052 fn updateThread( 1053 comptime Event: type, 1054 io: std.Io, 1055 allocator: std.mem.Allocator, 1056 host: Host, 1057 repo_base: []const u8, 1058 id: *const [evt.event_id_size]u8, 1059 update: Event.Update, 1060 author: evt.CommitAuthor, 1061 ) !void { 1062 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1063 defer request_repo.deinit(allocator); 1064 const source = request_repo.source; 1065 switch (source.repo_kind) { 1066 inline else => |repo_kind| { 1067 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1068 defer any_repo.deinit(io, allocator); 1069 switch (any_repo) { 1070 inline else => |*repo| try Event.update(repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1071 } 1072 }, 1073 } 1074 } 1075 1076 const RemoveParts = struct { 1077 repo_base: []const u8, 1078 kind: evt.EventKind, 1079 id: [evt.event_id_size]u8, 1080 }; 1081 1082 // split a remove url into the repo and event it names 1083 fn removeParts(base: []const u8) ?RemoveParts { 1084 if (attachmentRequest(base)) |attachment| { 1085 const parent = attachParentParts(attachment.repo_base) orelse return null; 1086 return .{ 1087 .repo_base = parent.repo_base, 1088 .kind = .attach, 1089 .id = attachment.id, 1090 }; 1091 } 1092 if (commentBaseParts(base)) |thread| return .{ 1093 .repo_base = thread.repo_base, 1094 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1095 .id = thread.comment_id orelse thread.thread_id, 1096 }; 1097 return null; 1098 } 1099 1100 // remove the event named by the form's url 1101 fn handleRemove( 1102 io: std.Io, 1103 request: *std.http.Server.Request, 1104 allocator: std.mem.Allocator, 1105 base: []const u8, 1106 host: Host, 1107 ) !void { 1108 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1109 1110 var author_arena = std.heap.ArenaAllocator.init(allocator); 1111 defer author_arena.deinit(); 1112 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1113 const author = request_author.author; 1114 1115 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1116 defer request_repo.deinit(allocator); 1117 const source = request_repo.source; 1118 1119 if (parts.kind == .patch) switch (host) { 1120 .remote => |remote| { 1121 const user_id = request_author.user_id orelse return respondLoginRequired(request); 1122 1123 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1124 defer admin_repo.deinit(io, allocator); 1125 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 1126 const record = try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &author_arena, &parts.id); 1127 if (record) |fork_record| { 1128 const repo_id = evt.parseEventId(std.fs.path.basename(source.path)) catch return respondRemoveNotFound(request); 1129 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, fork_record.event.repo_id, &repo_id)) { 1130 const id = std.fmt.bytesToHex(parts.id, .lower); 1131 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1132 defer allocator.free(repos_dir); 1133 try fork.remove(io, allocator, repos_dir, &admin_repo, &id, &user_id, author); 1134 1135 const location = try std.fmt.allocPrint(allocator, "{s}/patches/drafts", .{parts.repo_base}); 1136 defer allocator.free(location); 1137 try request.respond("", .{ 1138 .status = .see_other, 1139 .keep_alive = false, 1140 .extra_headers = &.{.{ .name = "location", .value = location }}, 1141 }); 1142 return; 1143 } 1144 } 1145 }, 1146 .local => {}, 1147 }; 1148 1149 switch (source.repo_kind) { 1150 inline else => |repo_kind| { 1151 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1152 defer any_repo.deinit(io, allocator); 1153 switch (any_repo) { 1154 inline else => |*repo| evt.remove(.repo, repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1155 error.EventNotFound => return respondRemoveNotFound(request), 1156 else => |e| return e, 1157 }, 1158 } 1159 }, 1160 } 1161 1162 const id = std.fmt.bytesToHex(parts.id, .lower); 1163 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1164 defer allocator.free(location); 1165 try request.respond("", .{ 1166 .status = .see_other, 1167 .keep_alive = false, 1168 .extra_headers = &.{.{ .name = "location", .value = location }}, 1169 }); 1170 } 1171 1172 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1173 try request.respond("event not found", .{ 1174 .status = .not_found, 1175 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1176 }); 1177 } 1178 1179 fn updateDiscussion( 1180 io: std.Io, 1181 allocator: std.mem.Allocator, 1182 host: Host, 1183 repo_base: []const u8, 1184 id: *const [evt.event_id_size]u8, 1185 title: []const u8, 1186 tags: []const u8, 1187 description: []const u8, 1188 author: evt.CommitAuthor, 1189 ) !void { 1190 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1191 defer request_repo.deinit(allocator); 1192 const source = request_repo.source; 1193 switch (source.repo_kind) { 1194 inline else => |repo_kind| { 1195 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1196 defer any_repo.deinit(io, allocator); 1197 switch (any_repo) { 1198 inline else => |*repo| try evt.Discussion.update(repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1199 } 1200 }, 1201 } 1202 } 1203 1204 // set the status of the issue the url names (base is 1205 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1206 // re-emitting its event, then redirect back to it 1207 fn handleThreadStatus( 1208 io: std.Io, 1209 request: *std.http.Server.Request, 1210 allocator: std.mem.Allocator, 1211 base: []const u8, 1212 host: Host, 1213 open: bool, 1214 ) !void { 1215 const not_found = "thread not found"; 1216 const parts = commentBaseParts(base) orelse { 1217 try request.respond(not_found, .{ 1218 .status = .not_found, 1219 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1220 }); 1221 return; 1222 }; 1223 1224 var author_arena = std.heap.ArenaAllocator.init(allocator); 1225 defer author_arena.deinit(); 1226 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1227 1228 (switch (parts.thread_kind) { 1229 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1230 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1231 else => return respondRemoveNotFound(request), 1232 }) catch |err| switch (err) { 1233 error.NotFound => { 1234 try request.respond(not_found, .{ 1235 .status = .not_found, 1236 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1237 }); 1238 return; 1239 }, 1240 else => |e| return e, 1241 }; 1242 1243 // like logout, this is a bodyless POST, so close the connection rather than 1244 // letting the keep-alive path try to discard a body that isn't framed. 1245 try request.respond("", .{ 1246 .status = .see_other, 1247 .keep_alive = false, 1248 .extra_headers = &.{.{ .name = "location", .value = base }}, 1249 }); 1250 } 1251 1252 // replace the title, tags and description of a thread. 1253 fn handleThreadEdit( 1254 io: std.Io, 1255 request: *std.http.Server.Request, 1256 allocator: std.mem.Allocator, 1257 base: []const u8, 1258 host: Host, 1259 parts: CommentBaseParts, 1260 ) !void { 1261 var author_arena = std.heap.ArenaAllocator.init(allocator); 1262 defer author_arena.deinit(); 1263 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1264 const author = request_author.author; 1265 1266 const body = try readFormBody(request, allocator); 1267 defer allocator.free(body); 1268 1269 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1270 defer allocator.free(title); 1271 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1272 defer allocator.free(tags); 1273 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1274 defer allocator.free(description_crlf); 1275 // form submission normalizes textarea line breaks to CRLF; store plain 1276 // newlines so the text renders the same on every host 1277 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1278 defer allocator.free(description); 1279 1280 // invalid fields send the user back to the edit form 1281 const valid = switch (parts.thread_kind) { 1282 .issue => evt.Issue.fieldsValid(title, tags), 1283 .patch => evt.Patch.fieldsValid(title, tags), 1284 .discuss => evt.Discussion.fieldsValid(title, tags), 1285 else => unreachable, 1286 }; 1287 if (!valid) { 1288 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1289 defer allocator.free(form_location); 1290 try request.respond("", .{ 1291 .status = .see_other, 1292 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1293 }); 1294 return; 1295 } 1296 1297 const draft_user_id = if (parts.thread_kind == .patch) request_author.user_id else null; 1298 if (draft_user_id) |user_id| { 1299 const remote = switch (host) { 1300 .remote => |remote| remote, 1301 .local => unreachable, 1302 }; 1303 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1304 defer request_repo.deinit(allocator); 1305 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1306 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1307 defer admin_repo.deinit(io, allocator); 1308 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1309 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1310 defer allocator.free(repos_dir); 1311 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 1312 defer allocator.free(fork_path); 1313 if (try pch.editDraft(.{}, io, allocator, &admin_repo, fork_path, .{ 1314 .id = id, 1315 .user_id = user_id, 1316 .repo_id = repo_id, 1317 .title = title, 1318 .tags = tags, 1319 .description = description, 1320 .author = author, 1321 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1322 })) { 1323 try request.respond("", .{ 1324 .status = .see_other, 1325 .extra_headers = &.{.{ .name = "location", .value = base }}, 1326 }); 1327 return; 1328 } 1329 } 1330 1331 const not_found = switch (parts.thread_kind) { 1332 .issue => "issue not found", 1333 .patch => "patch not found", 1334 .discuss => "discussion not found", 1335 else => unreachable, 1336 }; 1337 (switch (parts.thread_kind) { 1338 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1339 .title = title, 1340 .tags = tags, 1341 .description = description, 1342 } }, author), 1343 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1344 .title = title, 1345 .tags = tags, 1346 .description = description, 1347 } }, author), 1348 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1349 else => unreachable, 1350 }) catch |err| switch (err) { 1351 error.NotFound => { 1352 try request.respond(not_found, .{ 1353 .status = .not_found, 1354 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1355 }); 1356 return; 1357 }, 1358 else => |e| return e, 1359 }; 1360 1361 try request.respond("", .{ 1362 .status = .see_other, 1363 .extra_headers = &.{.{ .name = "location", .value = base }}, 1364 }); 1365 } 1366 1367 // resolve every conflicted field of the thread the url names 1368 fn handleThreadResolve( 1369 io: std.Io, 1370 request: *std.http.Server.Request, 1371 allocator: std.mem.Allocator, 1372 base: []const u8, 1373 host: Host, 1374 ) !void { 1375 var author_arena = std.heap.ArenaAllocator.init(allocator); 1376 defer author_arena.deinit(); 1377 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1378 1379 const body = try readFormBody(request, allocator); 1380 defer allocator.free(body); 1381 1382 var field_arena = std.heap.ArenaAllocator.init(allocator); 1383 defer field_arena.deinit(); 1384 const aa = field_arena.allocator(); 1385 const title = try parseFormField(aa, body, "title"); 1386 const tags = try parseFormField(aa, body, "tags"); 1387 1388 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1389 // textarea line breaks to CRLF 1390 var hunks: std.ArrayList([]const u8) = .empty; 1391 var hunk_index: usize = 0; 1392 while (true) : (hunk_index += 1) { 1393 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1394 const submitted = (try parseFormField(aa, body, name)) orelse break; 1395 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1396 } 1397 1398 const parts = commentBaseParts(base) orelse { 1399 try request.respond("thread not found", .{ 1400 .status = .not_found, 1401 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1402 }); 1403 return; 1404 }; 1405 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1406 try request.respond("thread not found", .{ 1407 .status = .not_found, 1408 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1409 }); 1410 return; 1411 } 1412 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1413 try request.respond("thread not found", .{ 1414 .status = .not_found, 1415 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1416 }); 1417 return; 1418 }; 1419 const theirs: []const u8 = switch (route) { 1420 .repo_patches => |*patch| patch.theirs.slice(), 1421 .repo_issues => "", 1422 else => unreachable, 1423 }; 1424 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1425 1426 (switch (parts.thread_kind) { 1427 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1428 .title = title, 1429 .tags = tags, 1430 .hunks = hunks.items, 1431 } }, author), 1432 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1433 .title = title, 1434 .tags = tags, 1435 .hunks = hunks.items, 1436 .theirs = theirs, 1437 } }, author), 1438 else => unreachable, 1439 }) catch |err| switch (err) { 1440 error.NotFound => { 1441 try request.respond(not_found, .{ 1442 .status = .not_found, 1443 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1444 }); 1445 return; 1446 }, 1447 // invalid fields send the user back to the resolve form 1448 error.InvalidFields => { 1449 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1450 defer allocator.free(form_location); 1451 try request.respond("", .{ 1452 .status = .see_other, 1453 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1454 }); 1455 return; 1456 }, 1457 else => |e| return e, 1458 }; 1459 1460 try request.respond("", .{ 1461 .status = .see_other, 1462 .extra_headers = &.{.{ .name = "location", .value = base }}, 1463 }); 1464 } 1465 1466 fn handleSync( 1467 io: std.Io, 1468 request: *std.http.Server.Request, 1469 allocator: std.mem.Allocator, 1470 base: []const u8, 1471 source: ui.RepoSource, 1472 ) !void { 1473 if (base.len != 0) { 1474 try request.respond("not found", .{ 1475 .status = .not_found, 1476 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1477 }); 1478 return; 1479 } 1480 1481 var owned_failure: ?[]u8 = null; 1482 defer if (owned_failure) |message| allocator.free(message); 1483 const failure: ?[]const u8 = blk: { 1484 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1485 break :blk owned_failure; 1486 }; 1487 if (failure) |message| { 1488 var encoded: std.Io.Writer.Allocating = .init(allocator); 1489 defer encoded.deinit(); 1490 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1491 fn isUnreserved(c: u8) bool { 1492 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1493 } 1494 }.isUnreserved); 1495 const cookie = try std.fmt.allocPrint( 1496 allocator, 1497 sync_failure_cookie ++ "={s}; Path=/; HttpOnly; SameSite=Strict", 1498 .{encoded.written()}, 1499 ); 1500 defer allocator.free(cookie); 1501 try request.respond("", .{ 1502 .status = .see_other, 1503 .extra_headers = &.{ 1504 .{ .name = "location", .value = "/events" }, 1505 .{ .name = "set-cookie", .value = cookie }, 1506 }, 1507 }); 1508 return; 1509 } 1510 1511 try request.respond("", .{ 1512 .status = .see_other, 1513 .extra_headers = &.{ 1514 .{ .name = "location", .value = "/events" }, 1515 .{ .name = "set-cookie", .value = sync_failure_cookie ++ "=; Path=/; Max-Age=0" }, 1516 }, 1517 }); 1518 } 1519 1520 fn renderIndexHtml( 1521 io: std.Io, 1522 allocator: std.mem.Allocator, 1523 host: Host, 1524 session_data: ui.Session.Data, 1525 ) ![]const u8 { 1526 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1527 1528 var page_arena = std.heap.ArenaAllocator.init(allocator); 1529 defer page_arena.deinit(); 1530 1531 // the remote admin repo must outlive the page build, since the session's 1532 // moment reads from it. 1533 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1534 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1535 1536 var session = switch (host) { 1537 .remote => |remote| blk: { 1538 // open the admin repo to read live user/repo data. 1539 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1540 const repo = if (repo_maybe) |*repo| repo else unreachable; 1541 var session = try ui.Session.init(&page_arena, repo, session_data); 1542 // give the page builders filesystem access to the on-disk repos (a 1543 // sibling "repos" dir next to the admin repo) so the Repo page can 1544 // read its files. 1545 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1546 break :blk session; 1547 }, 1548 .local => |local| ui.Session{ 1549 .data = session_data, 1550 .arena = &page_arena, 1551 .page_arena = &page_arena, 1552 .local = local, 1553 }, 1554 }; 1555 session.io = io; 1556 1557 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1558 var root = try ui.initRoot(allocator, &page, &session); 1559 defer root.deinit(allocator); 1560 1561 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1562 1563 const content = try generateHtml(allocator, &root, &session); 1564 defer allocator.free(content); 1565 1566 // serialize the snapshot so the wasm side can parse it back without making 1567 // a second request. it's embedded raw in a <script type="application/json"> 1568 // block, whose content is raw text terminated only by "</script". in json, 1569 // '<' appears solely inside string values, so escaping every '<' (and '>' 1570 // for good measure) to its \uXXXX form yields equivalent json that can't 1571 // break out of the tag. 1572 var json: std.Io.Writer.Allocating = .init(allocator); 1573 defer json.deinit(); 1574 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1575 1576 var json_escaped: std.ArrayList(u8) = .empty; 1577 defer json_escaped.deinit(allocator); 1578 for (json.written()) |c| switch (c) { 1579 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1580 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1581 else => try json_escaped.append(allocator, c), 1582 }; 1583 1584 var out: std.ArrayList(u8) = .empty; 1585 errdefer out.deinit(allocator); 1586 { 1587 var cursor: usize = 0; 1588 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1589 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1590 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1591 }) |sub| { 1592 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1593 try out.appendSlice(allocator, template[cursor..idx]); 1594 try out.appendSlice(allocator, sub.replacement); 1595 cursor = idx + sub.needle.len; 1596 } 1597 try out.appendSlice(allocator, template[cursor..]); 1598 } 1599 return try out.toOwnedSlice(allocator); 1600 } 1601 1602 fn findEmbed(request_path: []const u8) ?Embed { 1603 const path = if (std.mem.eql(u8, request_path, "/")) 1604 "index.html" 1605 else if (request_path.len > 1 and request_path[0] == '/') 1606 request_path[1..] 1607 else 1608 return null; 1609 1610 for (embeds) |embed| { 1611 if (std.mem.eql(u8, path, embed.path)) return embed; 1612 } 1613 return null; 1614 } 1615 1616 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1617 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1618 // rendered recursively so nested scrolls work. 1619 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1620 const grid = root.getGrid() orelse return error.MissingGrid; 1621 const root_focus = root.getFocus(); 1622 1623 var out: std.ArrayList(u8) = .empty; 1624 errdefer out.deinit(allocator); 1625 1626 switch (root.*) { 1627 .background => |*background| { 1628 if (background.art.getGrid()) |art| { 1629 var position_buf: [64]u8 = undefined; 1630 try out.appendSlice(allocator, try std.fmt.bufPrint(&position_buf, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch\">", .{grid.size.width -| art.size.width})); 1631 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1632 try out.appendSlice(allocator, "</div>"); 1633 } 1634 }, 1635 else => {}, 1636 } 1637 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1638 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1639 try out.appendSlice(allocator, "</div>"); 1640 try renderForms(allocator, &out, root_focus); 1641 return try out.toOwnedSlice(allocator); 1642 } 1643 1644 // render one panel — a focus subtree and its content grid — as HTML, recursing 1645 // once per web-native Scroll inside it. the root panel is the whole page; each 1646 // Scroll becomes a nested, natively-scrollable div holding its full content. 1647 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1648 // then the child scroll divs over those holes. 1649 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1650 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1651 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1652 // plus their descendants, which the focus tree flattens into this panel's 1653 // children): the cell hit-test below skips them so this panel doesn't claim 1654 // cells that are really rendered inside a child scroll's own panel. 1655 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1656 var direct: std.ArrayList(usize) = .empty; 1657 defer direct.deinit(allocator); 1658 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1659 defer excluded.deinit(allocator); 1660 { 1661 var it = focus.children.iterator(); 1662 while (it.next()) |e| { 1663 if (e.value_ptr.focus.scroll == null) continue; 1664 try direct.append(allocator, e.key_ptr.*); 1665 try excluded.put(allocator, e.key_ptr.*, {}); 1666 var mit = e.value_ptr.focus.children.iterator(); 1667 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1668 } 1669 } 1670 1671 // the HTML element a run of cells is wrapped in, chosen from the cell's 1672 // focusable kind 1673 const CellTag = union(enum) { 1674 span, // clickable focusable cell 1675 a: []const u8, // clickable focusable link 1676 plain, // non-focusable, colored 1677 1678 const a_prefix = "a:"; 1679 // an "in-page" anchor: rendered as a real <a href> so it works with js 1680 // disabled, but wasm handles it without navigating. 1681 fn init(str: []const u8) @This() { 1682 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1683 return .{ .a = str[ui.raw_link_prefix.len..] }; 1684 } 1685 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1686 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1687 } 1688 if (std.mem.startsWith(u8, str, a_prefix)) { 1689 return .{ .a = str[a_prefix.len..] }; 1690 } 1691 return .span; 1692 } 1693 1694 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1695 var id_buf: [32]u8 = undefined; 1696 switch (self) { 1697 .span => { 1698 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1699 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1700 try out.appendSlice(alloc, "\""); 1701 try out.appendSlice(alloc, style_attr); 1702 try out.appendSlice(alloc, ">"); 1703 }, 1704 .a => |href| { 1705 // tabindex=-1 keeps these out of the browser's tab order 1706 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1707 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1708 try out.appendSlice(alloc, "\" href=\""); 1709 try appendEscapedHtml(alloc, out, href); 1710 try out.appendSlice(alloc, "\""); 1711 try out.appendSlice(alloc, style_attr); 1712 try out.appendSlice(alloc, ">"); 1713 }, 1714 .plain => { 1715 try out.appendSlice(alloc, "<span"); 1716 try out.appendSlice(alloc, style_attr); 1717 try out.appendSlice(alloc, ">"); 1718 }, 1719 } 1720 } 1721 1722 fn closeTag(self: @This()) []const u8 { 1723 return switch (self) { 1724 .span, .plain => "</span>", 1725 .a => "</a>", 1726 }; 1727 } 1728 }; 1729 1730 // the cells are the volatile part of a panel. js replaces this one subtree 1731 // wholesale while retaining the panel's native controls and scroll shells. 1732 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 1733 1734 // emit this panel's grid as rows of text, coalescing adjacent cells that 1735 // share a focus id and colors into one tag (a clickable span, a link, or a 1736 // plain colored span). cells under a child scroll keep only their background. 1737 for (0..grid.size.height) |y| { 1738 var cur_id: ?usize = null; 1739 var cur_fg: ?Grid.Color = null; 1740 var cur_bg: ?Grid.Color = null; 1741 var open_tag: ?CellTag = null; 1742 var first = true; 1743 for (0..grid.size.width) |x| { 1744 const cell = (try grid.cell(x, y)).*; 1745 // a cell covered by a child scroll's viewport is drawn by that scroll's 1746 // own div, so blank its glyph and make it non-clickable here — but keep 1747 // its background, so the backdrop still shows through the scroll's 1748 // transparent div instead of a bare hole. 1749 const covered_by_scroll = blk: { 1750 for (direct.items) |id| { 1751 const r = (focus.children.get(id) orelse continue).rect; 1752 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; 1753 } 1754 break :blk false; 1755 }; 1756 // the focusable cell at (x, y) among this panel's own focusables (skipping 1757 // any that belong to a child scroll, whose cells are drawn in their own 1758 // panel); none for a covered cell. 1759 const cell_id = if (covered_by_scroll) null else blk: { 1760 var iter = focus.children.iterator(); 1761 while (iter.next()) |entry| { 1762 const child = entry.value_ptr.*; 1763 if (!child.focus.focusable) continue; 1764 if (excluded.contains(entry.key_ptr.*)) continue; 1765 const r = child.rect; 1766 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1767 break :blk entry.key_ptr.*; 1768 } 1769 } 1770 break :blk null; 1771 }; 1772 const fg = if (covered_by_scroll) null else cell.style.fg; 1773 const bg = cell.style.bg; 1774 1775 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1776 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1777 1778 var new_tag: ?CellTag = null; 1779 if (cell_id) |id| { 1780 if (focus.children.get(id)) |child| { 1781 new_tag = switch (child.focus.kind) { 1782 .custom => |custom| CellTag.init(custom), 1783 else => .span, 1784 }; 1785 } 1786 } 1787 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1788 1789 if (new_tag) |t| { 1790 var style_buf: [64]u8 = undefined; 1791 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1792 } 1793 1794 open_tag = new_tag; 1795 cur_id = cell_id; 1796 cur_fg = fg; 1797 cur_bg = bg; 1798 first = false; 1799 } 1800 1801 if (covered_by_scroll) { 1802 try appendEscapedHtml(allocator, output, " "); 1803 } else if (cell.continuation) { 1804 // the wide rune to the left was emitted 2ch wide, covering this column 1805 } else if (cell.rune) |rune| { 1806 var encoded: [4]u8 = undefined; 1807 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 1808 const rune_text = encoded[0..encoded_len]; 1809 // a double-width rune is pinned inside a 2ch span so the 1810 // fallback glyph's advance width can't shift the rest of the row 1811 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 1812 if (wide) { 1813 try output.appendSlice(allocator, "<span class=\"w2\">"); 1814 try appendEscapedHtml(allocator, output, rune_text); 1815 try output.appendSlice(allocator, "</span>"); 1816 } else { 1817 try appendEscapedHtml(allocator, output, rune_text); 1818 } 1819 } else { 1820 try appendEscapedHtml(allocator, output, " "); 1821 } 1822 } 1823 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1824 try output.append(allocator, '\n'); 1825 } 1826 try output.appendSlice(allocator, "</div>"); 1827 1828 // native controls live in their panel, beside the replaceable cells. their 1829 // stable keys let JS update layout without recreating their DOM nodes, and 1830 // being actual descendants of a scroll gives them native movement/clipping. 1831 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 1832 1833 // each child scroll becomes a natively-scrollable div positioned over its 1834 // viewport, holding its full content rendered recursively. 1835 for (direct.items) |id| { 1836 const child = focus.children.get(id) orelse continue; 1837 const info = child.focus.scroll orelse continue; 1838 const r = child.rect; 1839 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1840 // when that axis actually overflows. the other axis is clipped (hidden), 1841 // matching how the terminal Scroll handles its non-scrolling axis. 1842 const overflow = switch (info.direction) { 1843 .vert => "overflow-x:hidden;overflow-y:auto", 1844 .horiz => "overflow-x:auto;overflow-y:hidden", 1845 .both => "overflow:auto", 1846 }; 1847 // the id carries a content version so JS preserves the native scroll 1848 // position across re-renders of the same content but resets it when the 1849 // content is replaced — e.g. selecting a different commit. the widget's 1850 // scroll offset (in cells) rides along so JS can apply it when it has no 1851 // preserved position, letting a wasm-side scrollToRect (the files list 1852 // scrolling to its selected row on page load) reach the browser. 1853 var buf: [256]u8 = undefined; 1854 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 1855 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 1856 try output.appendSlice(allocator, "</div>"); 1857 } 1858 } 1859 1860 const form_prefix = "form:"; 1861 const form_id_prefix = "haxy-form-"; 1862 1863 fn formAction(focus: *const Focus) ?[]const u8 { 1864 return switch (focus.kind) { 1865 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 1866 else => null, 1867 }; 1868 } 1869 1870 // find the form ancestor of a flattened focus-tree child. html's `form` 1871 // attribute then associates the control with that form without requiring the 1872 // form and control to share a DOM parent. 1873 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 1874 var id = focus_id; 1875 while (root_focus.children.get(id)) |child| { 1876 const parent_id = child.parent_id; 1877 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 1878 const parent = root_focus.children.get(parent_id) orelse return null; 1879 if (formAction(parent.focus) != null) return parent_id; 1880 id = parent_id; 1881 } 1882 return null; 1883 } 1884 1885 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 1886 const form_id = formOwner(root_focus, focus_id) orelse return; 1887 var buf: [64]u8 = undefined; 1888 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 1889 } 1890 1891 fn renderPanelControls( 1892 allocator: std.mem.Allocator, 1893 output: *std.ArrayList(u8), 1894 focus: *Focus, 1895 session: *ui.Session, 1896 root_focus: *Focus, 1897 excluded: *const std.AutoHashMapUnmanaged(usize, void), 1898 ) !void { 1899 var iter = focus.children.iterator(); 1900 while (iter.next()) |entry| { 1901 const id = entry.key_ptr.*; 1902 if (excluded.contains(id)) continue; 1903 const child = entry.value_ptr.*; 1904 const r = child.rect; 1905 1906 switch (child.focus.kind) { 1907 .text_input, .text_input_password, .text_area => { 1908 const ti = session.text_inputs.get(id) orelse continue; 1909 1910 const inner_left = r.x + 1; 1911 const inner_top = r.y + 1; 1912 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1913 const preserve = !ti.options.read_only; 1914 1915 if (child.focus.kind == .text_area) { 1916 const value = try ti.text(allocator); 1917 defer allocator.free(value); 1918 var id_buf: [128]u8 = undefined; 1919 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 1920 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 1921 try appendFormAttribute(allocator, output, root_focus, id); 1922 if (ti.options.name.len > 0) { 1923 try output.appendSlice(allocator, " name=\""); 1924 try appendEscapedHtml(allocator, output, ti.options.name); 1925 try output.append(allocator, '"'); 1926 } 1927 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1928 var pos_buf: [128]u8 = undefined; 1929 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 1930 try appendEscapedHtml(allocator, output, value); 1931 try output.appendSlice(allocator, "</textarea>"); 1932 continue; 1933 } 1934 1935 var id_buf: [160]u8 = undefined; 1936 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 1937 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 1938 try appendFormAttribute(allocator, output, root_focus, id); 1939 if (ti.options.name.len > 0) { 1940 try output.appendSlice(allocator, " name=\""); 1941 try appendEscapedHtml(allocator, output, ti.options.name); 1942 try output.append(allocator, '"'); 1943 } 1944 if (child.focus.kind != .text_input_password) { 1945 const value = try ti.text(allocator); 1946 defer allocator.free(value); 1947 try output.appendSlice(allocator, " value=\""); 1948 try appendEscapedHtml(allocator, output, value); 1949 try output.append(allocator, '"'); 1950 } 1951 var pos_buf: [96]u8 = undefined; 1952 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 1953 }, 1954 .custom => |custom| { 1955 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1956 if (formOwner(root_focus, id) == null) continue; 1957 var id_buf: [128]u8 = undefined; 1958 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 1959 try appendFormAttribute(allocator, output, root_focus, id); 1960 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1961 try output.appendSlice(allocator, " formaction=\""); 1962 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 1963 try output.append(allocator, '"'); 1964 } 1965 var pos_buf: [128]u8 = undefined; 1966 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 1967 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 1968 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 1969 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 1970 var id_buf: [128]u8 = undefined; 1971 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 1972 } 1973 }, 1974 else => {}, 1975 } 1976 } 1977 } 1978 1979 // emit hidden form owners beside the rendered panels. their controls point 1980 // back here with the standard HTML `form` attribute. 1981 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 1982 // the focus child map preserves insertion order, which matches the order 1983 // widgets were added in code 1984 var iter = root_focus.children.iterator(); 1985 while (iter.next()) |entry| { 1986 const child = entry.value_ptr.*; 1987 const action_url = formAction(child.focus) orelse continue; 1988 1989 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 1990 var id_buf: [96]u8 = undefined; 1991 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 1992 try appendEscapedHtml(allocator, output, action_url); 1993 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 1994 } 1995 } 1996 1997 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1998 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1999 return b == null; 2000 } 2001 2002 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2003 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2004 // empty slice when neither is set. 2005 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2006 if (fg == null and bg == null) return buf[0..0]; 2007 const prefix = " style=\""; 2008 @memcpy(buf[0..prefix.len], prefix); 2009 var i: usize = prefix.len; 2010 if (fg) |c| { 2011 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]; 2012 i += s.len; 2013 } 2014 if (bg) |c| { 2015 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]; 2016 i += s.len; 2017 } 2018 buf[i] = '"'; 2019 i += 1; 2020 return buf[0..i]; 2021 } 2022 2023 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2024 for (input) |ch| { 2025 switch (ch) { 2026 '&' => try out.appendSlice(allocator, "&amp;"), 2027 '<' => try out.appendSlice(allocator, "&lt;"), 2028 '>' => try out.appendSlice(allocator, "&gt;"), 2029 '"' => try out.appendSlice(allocator, "&quot;"), 2030 '\'' => try out.appendSlice(allocator, "&#39;"), 2031 else => try out.append(allocator, ch), 2032 } 2033 } 2034 } 2035 2036 // --- helpers -------------------------------------------------------------- 2037 2038 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2039 var iter = request.iterateHeaders(); 2040 while (iter.next()) |header| { 2041 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2042 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2043 while (pairs.next()) |pair| { 2044 const trimmed = std.mem.trim(u8, pair, " \t"); 2045 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2046 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2047 return trimmed[eq + 1 ..]; 2048 } 2049 } 2050 } 2051 return null; 2052 } 2053 2054 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2055 var iter = std.mem.splitScalar(u8, body, '&'); 2056 while (iter.next()) |pair| { 2057 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2058 if (std.mem.eql(u8, pair[0..eq], key)) { 2059 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2060 } 2061 } 2062 return null; 2063 } 2064 2065 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2066 var buffer: [256]u8 = undefined; 2067 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2068 } 2069 2070 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2071 var out: std.ArrayList(u8) = .empty; 2072 errdefer out.deinit(allocator); 2073 var i: usize = 0; 2074 while (i < encoded.len) : (i += 1) { 2075 switch (encoded[i]) { 2076 '+' => try out.append(allocator, ' '), 2077 '%' => { 2078 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2079 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2080 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2081 try out.append(allocator, hi * 16 + lo); 2082 i += 2; 2083 }, 2084 else => try out.append(allocator, encoded[i]), 2085 } 2086 } 2087 return try out.toOwnedSlice(allocator); 2088 } 2089 2090 // disk-backed web session store. each login mints a random, opaque token 2091 // (not the user's id) that is stored as a file named by the token hex, whose 2092 // contents are the raw user_id bytes. authenticating a request is a lookup of 2093 // the cookie's token; logout deletes the file, revoking the session. there is 2094 // deliberately no expiry — a session lives until logout. 2095 pub const SessionStore = struct { 2096 io: std.Io, 2097 dir: std.Io.Dir, 2098 auto_login: ?[token_hex_len]u8, 2099 2100 pub const token_hex_len = evt.event_id_size * 2; 2101 2102 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2103 try data_dir.createDirPath(io, "sessions"); 2104 const dir = try data_dir.openDir(io, "sessions", .{}); 2105 const auto_login = blk: { 2106 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2107 defer file.close(io); 2108 var token: [token_hex_len]u8 = undefined; 2109 var storage: [token_hex_len]u8 = undefined; 2110 var reader = file.reader(io, &storage); 2111 reader.interface.readSliceAll(&token) catch break :blk null; 2112 break :blk token; 2113 }; 2114 return .{ .io = io, .dir = dir, .auto_login = auto_login }; 2115 } 2116 2117 pub fn deinit(self: SessionStore) void { 2118 self.dir.close(self.io); 2119 } 2120 2121 // mint a new session for user_id, returning the token hex to set as the 2122 // cookie value. 2123 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2124 var token: [evt.event_id_size]u8 = undefined; 2125 self.io.random(&token); 2126 const token_hex = std.fmt.bytesToHex(token, .lower); 2127 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2128 defer file.close(self.io); 2129 try file.writeStreamingAll(self.io, user_id); 2130 return token_hex; 2131 } 2132 2133 // resolve a cookie's token to its user_id. returns false (logged out) for a 2134 // missing, malformed, or unknown token. 2135 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2136 if (!isToken(token_hex)) return false; 2137 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2138 defer file.close(self.io); 2139 var storage: [evt.event_id_size]u8 = undefined; 2140 var file_reader = file.reader(self.io, &storage); 2141 file_reader.interface.readSliceAll(out) catch return false; 2142 return true; 2143 } 2144 2145 // revoke a session. a no-op for a missing or malformed token. 2146 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2147 if (!isToken(token_hex)) return; 2148 self.dir.deleteFile(self.io, token_hex) catch {}; 2149 } 2150 2151 // leave `token_hex`'s session for visitors arriving without one. only the 2152 // `try` fixture writes one. the name can't collide with a session token. 2153 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2154 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2155 defer file.close(self.io); 2156 try file.writeStreamingAll(self.io, token_hex); 2157 } 2158 2159 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2160 out.* = self.auto_login orelse return false; 2161 return true; 2162 } 2163 2164 const auto_login_name = "auto-login"; 2165 2166 // a token is exactly token_hex_len hex chars. validating before using the 2167 // value as a path keeps attacker-supplied cookies from escaping the 2168 // sessions dir (e.g. via "/" or ".." bytes). 2169 fn isToken(token_hex: []const u8) bool { 2170 if (token_hex.len != token_hex_len) return false; 2171 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2172 return true; 2173 } 2174 }; 2175