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