╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
650 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 651 // widget tree, each wrapping the text inputs and submit button inside it, 652 // positioned absolutely over the matching grid cells. 653 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 654 const root_focus = root.getFocus(); 655 656 var out: std.ArrayList(u8) = .empty; 657 errdefer out.deinit(allocator); 658 659 const form_prefix = "form:"; 660 661 // Focus.children is an AutoArrayHashMap that preserves insertion order, 662 // which matches the order widgets were added in code 663 var iter = root_focus.children.iterator(); 664 while (iter.next()) |entry| { 665 const child = entry.value_ptr.*; 666 const action_url = switch (child.focus.kind) { 667 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 668 custom[form_prefix.len..] 669 else 670 continue, 671 else => continue, 672 }; 673 674 try out.appendSlice(allocator, "<form action=\""); 675 try appendEscapedHtml(allocator, &out, action_url); 676 try out.appendSlice(allocator, "\" method=\"post\""); 677 // an empty action must not POST — block it and send the input to the TUI instead 678 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 679 try out.appendSlice(allocator, ">"); 680 681 // form.focus.children was populated by addChild, which flattens the 682 // whole subtree into one map — so descendants (inputs + the submit 683 // button) all appear here. positions on form.focus are relative to 684 // the form, so we look up absolute rects via root_focus for layout. 685 var inner_iter = child.focus.children.iterator(); 686 while (inner_iter.next()) |inner_entry| { 687 const inner_id = inner_entry.key_ptr.*; 688 const root_child = root_focus.children.get(inner_id) orelse continue; 689 const r = root_child.rect; 690 switch (root_child.focus.kind) { 691 .text_input, .text_input_password => { 692 const ti = session.text_inputs.get(inner_id) orelse continue; 693 const inner_left = r.x + 1; 694 const inner_top = r.y + 1; 695 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 696 697 try out.appendSlice(allocator, "<input type=\""); 698 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 699 try out.appendSlice(allocator, "\" data-focus-id=\""); 700 var id_buf: [32]u8 = undefined; 701 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 702 if (ti.options.name.len > 0) { 703 try out.appendSlice(allocator, "\" name=\""); 704 try appendEscapedHtml(allocator, &out, ti.options.name); 705 } 706 // intentionally no `value` attribute: the browser tracks user input 707 // natively, and including the wasm-side value here would make the 708 // overlay HTML differ on every keystroke — that would trip the diff 709 // in _setOverlay and rebuild the <input>, eating the user's caret. 710 try out.appendSlice(allocator, "\" style=\"left:"); 711 var pos_buf: [64]u8 = undefined; 712 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 713 try out.appendSlice(allocator, "\">"); 714 }, 715 .custom => |custom| { 716 if (std.mem.eql(u8, "submit", custom)) { 717 // inside the dashed border the TUI cells draw around the button. 718 const inner_left = r.x + 1; 719 const inner_top = r.y + 1; 720 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 721 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 722 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 723 var id_buf: [32]u8 = undefined; 724 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 725 try out.appendSlice(allocator, "\" style=\"left:"); 726 var pos_buf: [128]u8 = undefined; 727 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 728 try out.appendSlice(allocator, "\"></button>"); 729 } 730 }, 731 else => {}, 732 } 733 } 734 735 try out.appendSlice(allocator, "</form>"); 736 } 737 738 return try out.toOwnedSlice(allocator); 739 } 740 741 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 742 if (a) |av| return if (b) |bv| av.eql(bv) else false; 743 return b == null; 744 } 745 746 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 747 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 748 // empty slice when neither is set. 749 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 750 if (fg == null and bg == null) return buf[0..0]; 751 const prefix = " style=\""; 752 @memcpy(buf[0..prefix.len], prefix); 753 var i: usize = prefix.len; 754 if (fg) |c| { 755 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]; 756 i += s.len; 757 } 758 if (bg) |c| { 759 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]; 760 i += s.len; 761 } 762 buf[i] = '"'; 763 i += 1; 764 return buf[0..i]; 765 } 766 767 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 768 for (input) |ch| { 769 switch (ch) { 770 '&' => try out.appendSlice(allocator, "&amp;"), 771 '<' => try out.appendSlice(allocator, "&lt;"), 772 '>' => try out.appendSlice(allocator, "&gt;"), 773 '"' => try out.appendSlice(allocator, "&quot;"), 774 '\'' => try out.appendSlice(allocator, "&#39;"), 775 else => try out.append(allocator, ch), 776 } 777 } 778 } 779 780 // --- helpers -------------------------------------------------------------- 781 782 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 783 var iter = request.iterateHeaders(); 784 while (iter.next()) |header| { 785 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 786 var pairs = std.mem.splitScalar(u8, header.value, ';'); 787 while (pairs.next()) |pair| { 788 const trimmed = std.mem.trim(u8, pair, " \t"); 789 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 790 if (std.mem.eql(u8, trimmed[0..eq], name)) { 791 return trimmed[eq + 1 ..]; 792 } 793 } 794 } 795 return null; 796 } 797 798 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 799 var iter = std.mem.splitScalar(u8, body, '&'); 800 while (iter.next()) |pair| { 801 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 802 if (std.mem.eql(u8, pair[0..eq], key)) { 803 return try decodeFormValue(allocator, pair[eq + 1 ..]); 804 } 805 } 806 return null; 807 } 808 809 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 810 var out: std.ArrayList(u8) = .empty; 811 errdefer out.deinit(allocator); 812 var i: usize = 0; 813 while (i < encoded.len) : (i += 1) { 814 switch (encoded[i]) { 815 '+' => try out.append(allocator, ' '), 816 '%' => { 817 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 818 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 819 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 820 try out.append(allocator, hi * 16 + lo); 821 i += 2; 822 }, 823 else => try out.append(allocator, encoded[i]), 824 } 825 } 826 return try out.toOwnedSlice(allocator); 827 } 828 829 // disk-backed web session store. each login mints a random, opaque token 830 // (not the user's id) that is stored as a file named by the token hex, whose 831 // contents are the raw user_id bytes. authenticating a request is a lookup of 832 // the cookie's token; logout deletes the file, revoking the session. there is 833 // deliberately no expiry — a session lives until logout. 834 pub const SessionStore = struct { 835 io: std.Io, 836 dir: std.Io.Dir, 837 838 pub const token_hex_len = evt.event_id_size * 2; 839 840 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 841 try data_dir.createDirPath(io, "sessions"); 842 const dir = try data_dir.openDir(io, "sessions", .{}); 843 return .{ .io = io, .dir = dir }; 844 } 845 846 pub fn deinit(self: SessionStore) void { 847 self.dir.close(self.io); 848 } 849 850 // mint a new session for user_id, returning the token hex to set as the 851 // cookie value. 852 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 853 var token: [evt.event_id_size]u8 = undefined; 854 self.io.random(&token); 855 const token_hex = std.fmt.bytesToHex(token, .lower); 856 const file = try self.dir.createFile(self.io, &token_hex, .{}); 857 defer file.close(self.io); 858 try file.writeStreamingAll(self.io, user_id); 859 return token_hex; 860 } 861 862 // resolve a cookie's token to its user_id. returns false (logged out) for a 863 // missing, malformed, or unknown token. 864 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 865 if (!isToken(token_hex)) return false; 866 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 867 defer file.close(self.io); 868 var storage: [evt.event_id_size]u8 = undefined; 869 var file_reader = file.reader(self.io, &storage); 870 file_reader.interface.readSliceAll(out) catch return false; 871 return true; 872 } 873 874 // revoke a session. a no-op for a missing or malformed token. 875 pub fn remove(self: SessionStore, token_hex: []const u8) void { 876 if (!isToken(token_hex)) return; 877 self.dir.deleteFile(self.io, token_hex) catch {}; 878 } 879 880 // a token is exactly token_hex_len hex chars. validating before using the 881 // value as a path keeps attacker-supplied cookies from escaping the 882 // sessions dir (e.g. via "/" or ".." bytes). 883 fn isToken(token_hex: []const u8) bool { 884 if (token_hex.len != token_hex_len) return false; 885 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 886 return true; 887 } 888 }; 889