╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1508 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1509 defer allocator.free(form_location); 1510 if (!evt.titleValid(title)) { 1511 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, tags, description, target_branch, null)); 1512 } 1513 try request.respond("", .{ 1514 .status = .see_other, 1515 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1516 }); 1517 return; 1518 } 1519 1520 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1521 defer request_repo.deinit(allocator); 1522 1523 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 1524 if (draft_user_id) |user_id| { 1525 const server = switch (host) { 1526 .server => |server| server, 1527 .local => unreachable, 1528 }; 1529 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 1530 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1531 defer allocator.free(form_location); 1532 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, tags, description, target_branch, null)); 1533 } 1534 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1535 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1536 defer admin_repo.deinit(io, allocator); 1537 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1538 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1539 defer allocator.free(repos_dir); 1540 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 1541 defer allocator.free(fork_path); 1542 if (try pch.editDraft(.{}, io, allocator, &admin_repo, fork_path, .{ 1543 .id = id, 1544 .user_id = user_id, 1545 .repo_id = repo_id, 1546 .title = title, 1547 .tags = tags, 1548 .description = description, 1549 .target_branch = target_branch, 1550 .author = author, 1551 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1552 })) { 1553 try request.respond("", .{ 1554 .status = .see_other, 1555 .extra_headers = &.{.{ .name = "location", .value = base }}, 1556 }); 1557 return; 1558 } 1559 } 1560 1561 // a draft is its author's alone, which its edit above checks 1562 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1563 1564 const not_found = switch (parts.thread_kind) { 1565 .issue => "issue not found", 1566 .patch => "patch not found", 1567 .discuss => "discussion not found", 1568 else => unreachable, 1569 }; 1570 (switch (parts.thread_kind) { 1571 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1572 .title = title, 1573 .tags = tags, 1574 .description = description, 1575 } }, author), 1576 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1577 .title = title, 1578 .tags = tags, 1579 .description = description, 1580 .target_branch = target_branch, 1581 } }, author), 1582 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1583 else => unreachable, 1584 }) catch |err| switch (err) { 1585 error.NotFound => { 1586 try request.respond(not_found, .{ 1587 .status = .not_found, 1588 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1589 }); 1590 return; 1591 }, 1592 else => { 1593 if (parts.thread_kind != .patch) return err; 1594 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 1595 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1596 defer allocator.free(form_location); 1597 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, tags, description, target_branch, null)); 1598 }, 1599 }; 1600 1601 try request.respond("", .{ 1602 .status = .see_other, 1603 .extra_headers = &.{.{ .name = "location", .value = base }}, 1604 }); 1605 } 1606 1607 // resolve every conflicted field of the thread the url names 1608 fn handleThreadResolve( 1609 io: std.Io, 1610 request: *std.http.Server.Request, 1611 allocator: std.mem.Allocator, 1612 base: []const u8, 1613 host: Host, 1614 ) !void { 1615 const parts = commentBaseParts(base) orelse { 1616 try request.respond("thread not found", .{ 1617 .status = .not_found, 1618 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1619 }); 1620 return; 1621 }; 1622 1623 var author_arena = std.heap.ArenaAllocator.init(allocator); 1624 defer author_arena.deinit(); 1625 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 1626 1627 const body = try readFormBody(request, allocator); 1628 defer allocator.free(body); 1629 1630 var field_arena = std.heap.ArenaAllocator.init(allocator); 1631 defer field_arena.deinit(); 1632 const aa = field_arena.allocator(); 1633 const title = try parseFormField(aa, body, "title"); 1634 const tags = try parseFormField(aa, body, "tags"); 1635 1636 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1637 // textarea line breaks to CRLF 1638 var hunks: std.ArrayList([]const u8) = .empty; 1639 var hunk_index: usize = 0; 1640 while (true) : (hunk_index += 1) { 1641 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1642 const submitted = (try parseFormField(aa, body, name)) orelse break; 1643 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1644 } 1645 1646 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1647 try request.respond("thread not found", .{ 1648 .status = .not_found, 1649 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1650 }); 1651 return; 1652 } 1653 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1654 try request.respond("thread not found", .{ 1655 .status = .not_found, 1656 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1657 }); 1658 return; 1659 }; 1660 const theirs: []const u8 = switch (route) { 1661 .repo_patches => |*patch| patch.theirs.slice(), 1662 .repo_issues => "", 1663 else => unreachable, 1664 }; 1665 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1666 1667 (switch (parts.thread_kind) { 1668 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1669 .title = title, 1670 .tags = tags, 1671 .hunks = hunks.items, 1672 } }, author), 1673 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1674 .title = title, 1675 .tags = tags, 1676 .hunks = hunks.items, 1677 .theirs = theirs, 1678 } }, author), 1679 else => unreachable, 1680 }) catch |err| switch (err) { 1681 error.NotFound => { 1682 try request.respond(not_found, .{ 1683 .status = .not_found, 1684 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1685 }); 1686 return; 1687 }, 1688 // invalid fields send the user back to the resolve form 1689 error.InvalidFields => { 1690 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1691 defer allocator.free(form_location); 1692 try request.respond("", .{ 1693 .status = .see_other, 1694 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1695 }); 1696 return; 1697 }, 1698 else => |e| return e, 1699 }; 1700 1701 try request.respond("", .{ 1702 .status = .see_other, 1703 .extra_headers = &.{.{ .name = "location", .value = base }}, 1704 }); 1705 } 1706 1707 fn handleSync( 1708 io: std.Io, 1709 request: *std.http.Server.Request, 1710 allocator: std.mem.Allocator, 1711 base: []const u8, 1712 source: ui.RepoSource, 1713 ) !void { 1714 if (base.len != 0) { 1715 try request.respond("not found", .{ 1716 .status = .not_found, 1717 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1718 }); 1719 return; 1720 } 1721 1722 var owned_failure: ?[]u8 = null; 1723 defer if (owned_failure) |message| allocator.free(message); 1724 const failure: ?[]const u8 = blk: { 1725 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1726 break :blk owned_failure; 1727 }; 1728 if (failure) |message| { 1729 var encoded: std.Io.Writer.Allocating = .init(allocator); 1730 defer encoded.deinit(); 1731 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1732 fn isUnreserved(c: u8) bool { 1733 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1734 } 1735 }.isUnreserved); 1736 const cookie = try std.fmt.allocPrint( 1737 allocator, 1738 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1739 .{encoded.written()}, 1740 ); 1741 defer allocator.free(cookie); 1742 try request.respond("", .{ 1743 .status = .see_other, 1744 .extra_headers = &.{ 1745 .{ .name = "location", .value = "/events" }, 1746 .{ .name = "set-cookie", .value = cookie }, 1747 }, 1748 }); 1749 return; 1750 } 1751 1752 try request.respond("", .{ 1753 .status = .see_other, 1754 .extra_headers = &.{ 1755 .{ .name = "location", .value = "/events" }, 1756 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1757 }, 1758 }); 1759 } 1760 1761 fn renderIndexHtml( 1762 io: std.Io, 1763 allocator: std.mem.Allocator, 1764 host: Host, 1765 session_data: ui.Session.Data, 1766 ) ![]const u8 { 1767 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1768 1769 var page_arena = std.heap.ArenaAllocator.init(allocator); 1770 defer page_arena.deinit(); 1771 1772 // the server admin repo must outlive the page build, since the session's 1773 // moment reads from it. 1774 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1775 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1776 1777 var session = switch (host) { 1778 .server => |server| blk: { 1779 // open the admin repo to read live user/repo data. 1780 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1781 const repo = if (repo_maybe) |*repo| repo else unreachable; 1782 var session = try ui.Session.init(&page_arena, repo, session_data); 1783 // give the page builders filesystem access to the on-disk repos (a 1784 // sibling "repos" dir next to the admin repo) so the Repo page can 1785 // read its files. 1786 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1787 break :blk session; 1788 }, 1789 .local => |local| ui.Session{ 1790 .data = session_data, 1791 .arena = &page_arena, 1792 .page_arena = &page_arena, 1793 .local = local, 1794 }, 1795 }; 1796 session.io = io; 1797 1798 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1799 var root = try ui.initRoot(allocator, &page, &session); 1800 defer root.deinit(allocator); 1801 1802 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1803 1804 const content = try generateHtml(allocator, &root, &session); 1805 defer allocator.free(content); 1806 1807 // serialize the snapshot so the wasm side can parse it back without making 1808 // a second request. it's embedded raw in a <script type="application/json"> 1809 // block, whose content is raw text terminated only by "</script". in json, 1810 // '<' appears solely inside string values, so escaping every '<' (and '>' 1811 // for good measure) to its \uXXXX form yields equivalent json that can't 1812 // break out of the tag. 1813 var json: std.Io.Writer.Allocating = .init(allocator); 1814 defer json.deinit(); 1815 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1816 1817 var json_escaped: std.ArrayList(u8) = .empty; 1818 defer json_escaped.deinit(allocator); 1819 for (json.written()) |c| switch (c) { 1820 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1821 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1822 else => try json_escaped.append(allocator, c), 1823 }; 1824 1825 var out: std.ArrayList(u8) = .empty; 1826 errdefer out.deinit(allocator); 1827 { 1828 var cursor: usize = 0; 1829 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1830 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1831 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1832 }) |sub| { 1833 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1834 try out.appendSlice(allocator, template[cursor..idx]); 1835 try out.appendSlice(allocator, sub.replacement); 1836 cursor = idx + sub.needle.len; 1837 } 1838 try out.appendSlice(allocator, template[cursor..]); 1839 } 1840 return try out.toOwnedSlice(allocator); 1841 } 1842 1843 fn findEmbed(request_path: []const u8) ?Embed { 1844 const path = if (std.mem.eql(u8, request_path, "/")) 1845 "index.html" 1846 else if (request_path.len > 1 and request_path[0] == '/') 1847 request_path[1..] 1848 else 1849 return null; 1850 1851 for (embeds) |embed| { 1852 if (std.mem.eql(u8, path, embed.path)) return embed; 1853 } 1854 return null; 1855 } 1856 1857 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1858 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1859 // rendered recursively so nested scrolls work. 1860 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1861 const grid = root.getGrid() orelse return error.MissingGrid; 1862 const root_focus = root.getFocus(); 1863 1864 var out: std.ArrayList(u8) = .empty; 1865 errdefer out.deinit(allocator); 1866 1867 switch (root.*) { 1868 .background => |*background| { 1869 if (background.art.getGrid()) |art| { 1870 var position_buf: [64]u8 = undefined; 1871 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})); 1872 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1873 try out.appendSlice(allocator, "</div>"); 1874 } 1875 }, 1876 else => {}, 1877 } 1878 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1879 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1880 try out.appendSlice(allocator, "</div>"); 1881 try renderForms(allocator, &out, root_focus); 1882 return try out.toOwnedSlice(allocator); 1883 } 1884 1885 // render one panel — a focus subtree and its content grid — as HTML, recursing 1886 // once per web-native Scroll inside it. the root panel is the whole page; each 1887 // Scroll becomes a nested, natively-scrollable div holding its full content. 1888 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1889 // then the child scroll divs over those holes. 1890 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1891 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1892 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1893 // plus their descendants, which the focus tree flattens into this panel's 1894 // children): the cell hit-test below skips them so this panel doesn't claim 1895 // cells that are really rendered inside a child scroll's own panel. 1896 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1897 var direct: std.ArrayList(usize) = .empty; 1898 defer direct.deinit(allocator); 1899 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1900 defer excluded.deinit(allocator); 1901 { 1902 var it = focus.children.iterator(); 1903 while (it.next()) |e| { 1904 if (e.value_ptr.focus.scroll == null) continue; 1905 try direct.append(allocator, e.key_ptr.*); 1906 try excluded.put(allocator, e.key_ptr.*, {}); 1907 var mit = e.value_ptr.focus.children.iterator(); 1908 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1909 } 1910 } 1911 1912 // the HTML element a run of cells is wrapped in, chosen from the cell's 1913 // focusable kind 1914 const CellTag = union(enum) { 1915 span, // clickable focusable cell 1916 a: []const u8, // clickable focusable link 1917 plain, // non-focusable, colored 1918 1919 const a_prefix = "a:"; 1920 // an "in-page" anchor: rendered as a real <a href> so it works with js 1921 // disabled, but wasm handles it without navigating. 1922 fn init(str: []const u8) @This() { 1923 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1924 return .{ .a = str[ui.raw_link_prefix.len..] }; 1925 } 1926 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1927 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1928 } 1929 if (std.mem.startsWith(u8, str, a_prefix)) { 1930 return .{ .a = str[a_prefix.len..] }; 1931 } 1932 return .span; 1933 } 1934 1935 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1936 var id_buf: [32]u8 = undefined; 1937 switch (self) { 1938 .span => { 1939 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1940 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1941 try out.appendSlice(alloc, "\""); 1942 try out.appendSlice(alloc, style_attr); 1943 try out.appendSlice(alloc, ">"); 1944 }, 1945 .a => |href| { 1946 // tabindex=-1 keeps these out of the browser's tab order 1947 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1948 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1949 try out.appendSlice(alloc, "\" href=\""); 1950 try appendEscapedHtml(alloc, out, href); 1951 try out.appendSlice(alloc, "\""); 1952 try out.appendSlice(alloc, style_attr); 1953 try out.appendSlice(alloc, ">"); 1954 }, 1955 .plain => { 1956 try out.appendSlice(alloc, "<span"); 1957 try out.appendSlice(alloc, style_attr); 1958 try out.appendSlice(alloc, ">"); 1959 }, 1960 } 1961 } 1962 1963 fn closeTag(self: @This()) []const u8 { 1964 return switch (self) { 1965 .span, .plain => "</span>", 1966 .a => "</a>", 1967 }; 1968 } 1969 }; 1970 1971 // the cells are the volatile part of a panel. js replaces this one subtree 1972 // wholesale while retaining the panel's native controls and scroll shells. 1973 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 1974 1975 // emit this panel's grid as rows of text, coalescing adjacent cells that 1976 // share a focus id and colors into one tag (a clickable span, a link, or a 1977 // plain colored span). cells under a child scroll keep only their background. 1978 for (0..grid.size.height) |y| { 1979 var cur_id: ?usize = null; 1980 var cur_fg: ?Grid.Color = null; 1981 var cur_bg: ?Grid.Color = null; 1982 var open_tag: ?CellTag = null; 1983 var first = true; 1984 for (0..grid.size.width) |x| { 1985 const cell = (try grid.cell(x, y)).*; 1986 // a cell covered by a child scroll's viewport is drawn by that scroll's 1987 // own div, so blank its glyph and make it non-clickable here — but keep 1988 // its background, so the backdrop still shows through the scroll's 1989 // transparent div instead of a bare hole. 1990 const covered_by_scroll = blk: { 1991 for (direct.items) |id| { 1992 const r = (focus.children.get(id) orelse continue).rect; 1993 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; 1994 } 1995 break :blk false; 1996 }; 1997 // the focusable cell at (x, y) among this panel's own focusables (skipping 1998 // any that belong to a child scroll, whose cells are drawn in their own 1999 // panel); none for a covered cell. 2000 const cell_id = if (covered_by_scroll) null else blk: { 2001 var iter = focus.children.iterator(); 2002 while (iter.next()) |entry| { 2003 const child = entry.value_ptr.*; 2004 if (child.focus.mode != .all) continue; 2005 if (excluded.contains(entry.key_ptr.*)) continue; 2006 const r = child.rect; 2007 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 2008 break :blk entry.key_ptr.*; 2009 } 2010 } 2011 break :blk null; 2012 }; 2013 const fg = if (covered_by_scroll) null else cell.style.fg; 2014 const bg = cell.style.bg; 2015 2016 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 2017 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2018 2019 var new_tag: ?CellTag = null; 2020 if (cell_id) |id| { 2021 if (focus.children.get(id)) |child| { 2022 new_tag = switch (child.focus.kind) { 2023 .custom => |custom| CellTag.init(custom), 2024 else => .span, 2025 }; 2026 } 2027 } 2028 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 2029 2030 if (new_tag) |t| { 2031 var style_buf: [64]u8 = undefined; 2032 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 2033 } 2034 2035 open_tag = new_tag; 2036 cur_id = cell_id; 2037 cur_fg = fg; 2038 cur_bg = bg; 2039 first = false; 2040 } 2041 2042 if (covered_by_scroll) { 2043 try appendEscapedHtml(allocator, output, " "); 2044 } else if (cell.continuation) { 2045 // the wide rune to the left was emitted 2ch wide, covering this column 2046 } else if (cell.rune) |rune| { 2047 var encoded: [4]u8 = undefined; 2048 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2049 const rune_text = encoded[0..encoded_len]; 2050 // a double-width rune is pinned inside a 2ch span so the 2051 // fallback glyph's advance width can't shift the rest of the row 2052 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2053 if (wide) { 2054 try output.appendSlice(allocator, "<span class=\"w2\">"); 2055 try appendEscapedHtml(allocator, output, rune_text); 2056 try output.appendSlice(allocator, "</span>"); 2057 } else { 2058 try appendEscapedHtml(allocator, output, rune_text); 2059 } 2060 } else { 2061 try appendEscapedHtml(allocator, output, " "); 2062 } 2063 } 2064 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2065 try output.append(allocator, '\n'); 2066 } 2067 try output.appendSlice(allocator, "</div>"); 2068 2069 // native controls live in their panel, beside the replaceable cells. their 2070 // stable keys let JS update layout without recreating their DOM nodes, and 2071 // being actual descendants of a scroll gives them native movement/clipping. 2072 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2073 2074 // each child scroll becomes a natively-scrollable div positioned over its 2075 // viewport, holding its full content rendered recursively. 2076 for (direct.items) |id| { 2077 const child = focus.children.get(id) orelse continue; 2078 const info = child.focus.scroll orelse continue; 2079 const r = child.rect; 2080 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2081 // when that axis actually overflows. the other axis is clipped (hidden), 2082 // matching how the terminal Scroll handles its non-scrolling axis. 2083 const overflow = switch (info.direction) { 2084 .vert => "overflow-x:hidden;overflow-y:auto", 2085 .horiz => "overflow-x:auto;overflow-y:hidden", 2086 .both => "overflow:auto", 2087 }; 2088 // the id carries a content version so JS preserves the native scroll 2089 // position across re-renders of the same content but resets it when the 2090 // content is replaced — e.g. selecting a different commit. the widget's 2091 // scroll offset (in cells) rides along so JS can apply it when it has no 2092 // preserved position, letting a wasm-side scrollToRect (the files list 2093 // scrolling to its selected row on page load) reach the browser. 2094 var buf: [256]u8 = undefined; 2095 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 })); 2096 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2097 try output.appendSlice(allocator, "</div>"); 2098 } 2099 } 2100 2101 const form_prefix = "form:"; 2102 const form_id_prefix = "haxy-form-"; 2103 2104 fn formAction(focus: *const Focus) ?[]const u8 { 2105 return switch (focus.kind) { 2106 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2107 else => null, 2108 }; 2109 } 2110 2111 // find the form ancestor of a flattened focus-tree child. html's `form` 2112 // attribute then associates the control with that form without requiring the 2113 // form and control to share a DOM parent. 2114 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2115 var id = focus_id; 2116 while (root_focus.children.get(id)) |child| { 2117 const parent_id = child.parent_id; 2118 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2119 const parent = root_focus.children.get(parent_id) orelse return null; 2120 if (formAction(parent.focus) != null) return parent_id; 2121 id = parent_id; 2122 } 2123 return null; 2124 } 2125 2126 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2127 const form_id = formOwner(root_focus, focus_id) orelse return; 2128 var buf: [64]u8 = undefined; 2129 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2130 } 2131 2132 fn renderPanelControls( 2133 allocator: std.mem.Allocator, 2134 output: *std.ArrayList(u8), 2135 focus: *Focus, 2136 session: *ui.Session, 2137 root_focus: *Focus, 2138 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2139 ) !void { 2140 var iter = focus.children.iterator(); 2141 while (iter.next()) |entry| { 2142 const id = entry.key_ptr.*; 2143 if (excluded.contains(id)) continue; 2144 const child = entry.value_ptr.*; 2145 const r = child.rect; 2146 2147 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2148 2149 switch (child.focus.kind) { 2150 .text_input, .text_input_password, .text_area => { 2151 const ti = session.text_inputs.get(id) orelse continue; 2152 2153 const inner_left = r.x + 1; 2154 const inner_top = r.y + 1; 2155 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2156 const preserve = !ti.options.read_only; 2157 2158 if (child.focus.kind == .text_area) { 2159 const value = try ti.text(allocator); 2160 defer allocator.free(value); 2161 var id_buf: [128]u8 = undefined; 2162 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2163 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2164 try appendFormAttribute(allocator, output, root_focus, id); 2165 if (ti.options.name.len > 0) { 2166 try output.appendSlice(allocator, " name=\""); 2167 try appendEscapedHtml(allocator, output, ti.options.name); 2168 try output.append(allocator, '"'); 2169 } 2170 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2171 var pos_buf: [128]u8 = undefined; 2172 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 })); 2173 try appendEscapedHtml(allocator, output, value); 2174 try output.appendSlice(allocator, "</textarea>"); 2175 continue; 2176 } 2177 2178 var id_buf: [160]u8 = undefined; 2179 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 })); 2180 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2181 try appendFormAttribute(allocator, output, root_focus, id); 2182 if (ti.options.name.len > 0) { 2183 try output.appendSlice(allocator, " name=\""); 2184 try appendEscapedHtml(allocator, output, ti.options.name); 2185 try output.append(allocator, '"'); 2186 } 2187 if (child.focus.kind != .text_input_password) { 2188 const value = try ti.text(allocator); 2189 defer allocator.free(value); 2190 try output.appendSlice(allocator, " value=\""); 2191 try appendEscapedHtml(allocator, output, value); 2192 try output.append(allocator, '"'); 2193 } 2194 var pos_buf: [96]u8 = undefined; 2195 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 })); 2196 }, 2197 .custom => |custom| { 2198 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2199 if (formOwner(root_focus, id) == null) continue; 2200 var id_buf: [128]u8 = undefined; 2201 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2202 try appendFormAttribute(allocator, output, root_focus, id); 2203 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2204 try output.appendSlice(allocator, " formaction=\""); 2205 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2206 try output.append(allocator, '"'); 2207 } 2208 var pos_buf: [128]u8 = undefined; 2209 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 })); 2210 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2211 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2212 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2213 var id_buf: [128]u8 = undefined; 2214 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 })); 2215 } 2216 }, 2217 else => {}, 2218 } 2219 } 2220 } 2221 2222 // emit hidden form owners beside the rendered panels. their controls point 2223 // back here with the standard HTML `form` attribute. 2224 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2225 // the focus child map preserves insertion order, which matches the order 2226 // widgets were added in code 2227 var iter = root_focus.children.iterator(); 2228 while (iter.next()) |entry| { 2229 const child = entry.value_ptr.*; 2230 const action_url = formAction(child.focus) orelse continue; 2231 2232 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2233 var id_buf: [96]u8 = undefined; 2234 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2235 try appendEscapedHtml(allocator, output, action_url); 2236 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2237 } 2238 } 2239 2240 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2241 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2242 return b == null; 2243 } 2244 2245 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2246 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2247 // empty slice when neither is set. 2248 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2249 if (fg == null and bg == null) return buf[0..0]; 2250 const prefix = " style=\""; 2251 @memcpy(buf[0..prefix.len], prefix); 2252 var i: usize = prefix.len; 2253 if (fg) |c| { 2254 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]; 2255 i += s.len; 2256 } 2257 if (bg) |c| { 2258 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]; 2259 i += s.len; 2260 } 2261 buf[i] = '"'; 2262 i += 1; 2263 return buf[0..i]; 2264 } 2265 2266 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2267 for (input) |ch| { 2268 switch (ch) { 2269 '&' => try out.appendSlice(allocator, "&amp;"), 2270 '<' => try out.appendSlice(allocator, "&lt;"), 2271 '>' => try out.appendSlice(allocator, "&gt;"), 2272 '"' => try out.appendSlice(allocator, "&quot;"), 2273 '\'' => try out.appendSlice(allocator, "&#39;"), 2274 else => try out.append(allocator, ch), 2275 } 2276 } 2277 } 2278 2279 // --- helpers -------------------------------------------------------------- 2280 2281 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2282 var iter = request.iterateHeaders(); 2283 while (iter.next()) |header| { 2284 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2285 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2286 while (pairs.next()) |pair| { 2287 const trimmed = std.mem.trim(u8, pair, " \t"); 2288 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2289 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2290 return trimmed[eq + 1 ..]; 2291 } 2292 } 2293 } 2294 return null; 2295 } 2296 2297 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2298 var iter = std.mem.splitScalar(u8, body, '&'); 2299 while (iter.next()) |pair| { 2300 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2301 if (std.mem.eql(u8, pair[0..eq], key)) { 2302 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2303 } 2304 } 2305 return null; 2306 } 2307 2308 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2309 var buffer: [256]u8 = undefined; 2310 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2311 } 2312 2313 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2314 var out: std.ArrayList(u8) = .empty; 2315 errdefer out.deinit(allocator); 2316 var i: usize = 0; 2317 while (i < encoded.len) : (i += 1) { 2318 switch (encoded[i]) { 2319 '+' => try out.append(allocator, ' '), 2320 '%' => { 2321 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2322 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2323 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2324 try out.append(allocator, hi * 16 + lo); 2325 i += 2; 2326 }, 2327 else => try out.append(allocator, encoded[i]), 2328 } 2329 } 2330 return try out.toOwnedSlice(allocator); 2331 } 2332 2333 // disk-backed web session store. each login mints a random, opaque token 2334 // (not the user's id) that is stored as a file named by the token hex, whose 2335 // contents are the raw user_id bytes. authenticating a request is a lookup of 2336 // the cookie's token; logout deletes the file, revoking the session. there is 2337 // deliberately no expiry — a session lives until logout. form failures use 2338 // files in the flash subdirectory that the redirected GET consumes. the 2339 // directory is cleared whenever the server starts. 2340 pub const SessionStore = struct { 2341 io: std.Io, 2342 dir: std.Io.Dir, 2343 flash_dir: std.Io.Dir, 2344 auto_login: ?[token_hex_len]u8, 2345 2346 pub const token_hex_len = evt.event_id_size * 2; 2347 2348 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2349 try data_dir.createDirPath(io, "sessions"); 2350 const dir = try data_dir.openDir(io, "sessions", .{}); 2351 errdefer dir.close(io); 2352 try dir.deleteTree(io, "flash"); 2353 try dir.createDirPath(io, "flash"); 2354 const flash_dir = try dir.openDir(io, "flash", .{}); 2355 errdefer flash_dir.close(io); 2356 const auto_login = blk: { 2357 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2358 defer file.close(io); 2359 var token: [token_hex_len]u8 = undefined; 2360 var storage: [token_hex_len]u8 = undefined; 2361 var reader = file.reader(io, &storage); 2362 reader.interface.readSliceAll(&token) catch break :blk null; 2363 break :blk token; 2364 }; 2365 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2366 } 2367 2368 pub fn deinit(self: SessionStore) void { 2369 self.flash_dir.close(self.io); 2370 self.dir.close(self.io); 2371 } 2372 2373 // mint a new session for user_id, returning the token hex to set as the 2374 // cookie value. 2375 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2376 var token: [evt.event_id_size]u8 = undefined; 2377 self.io.random(&token); 2378 const token_hex = std.fmt.bytesToHex(token, .lower); 2379 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2380 defer file.close(self.io); 2381 try file.writeStreamingAll(self.io, user_id); 2382 return token_hex; 2383 } 2384 2385 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2386 var token: [evt.event_id_size]u8 = undefined; 2387 self.io.random(&token); 2388 const token_hex = std.fmt.bytesToHex(token, .lower); 2389 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2390 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2391 defer file.close(self.io); 2392 2393 var json: std.Io.Writer.Allocating = .init(allocator); 2394 defer json.deinit(); 2395 try std.json.Stringify.value(value, .{}, &json.writer); 2396 try file.writeStreamingAll(self.io, json.written()); 2397 return token_hex; 2398 } 2399 2400 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2401 if (!isToken(token_hex)) return null; 2402 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2403 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2404 defer file.close(self.io); 2405 2406 var storage: [4096]u8 = undefined; 2407 var reader = file.reader(self.io, &storage); 2408 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2409 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2410 } 2411 2412 // resolve a cookie's token to its user_id. returns false (logged out) for a 2413 // missing, malformed, or unknown token. 2414 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2415 if (!isToken(token_hex)) return false; 2416 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2417 defer file.close(self.io); 2418 var storage: [evt.event_id_size]u8 = undefined; 2419 var file_reader = file.reader(self.io, &storage); 2420 file_reader.interface.readSliceAll(out) catch return false; 2421 return true; 2422 } 2423 2424 // revoke a session. a no-op for a missing or malformed token. 2425 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2426 if (!isToken(token_hex)) return; 2427 self.dir.deleteFile(self.io, token_hex) catch {}; 2428 } 2429 2430 // leave `token_hex`'s session for visitors arriving without one. only the 2431 // `try` fixture writes one. the name can't collide with a session token. 2432 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2433 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2434 defer file.close(self.io); 2435 try file.writeStreamingAll(self.io, token_hex); 2436 } 2437 2438 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2439 out.* = self.auto_login orelse return false; 2440 return true; 2441 } 2442 2443 const auto_login_name = "auto-login"; 2444 2445 // a token is exactly token_hex_len hex chars. validating before using the 2446 // value as a path keeps attacker-supplied cookies from escaping the 2447 // sessions dir (e.g. via "/" or ".." bytes). 2448 fn isToken(token_hex: []const u8) bool { 2449 if (token_hex.len != token_hex_len) return false; 2450 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2451 return true; 2452 } 2453 }; 2454