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