╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
713 const inner_top = r.y + 1; 714 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 715 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 716 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 717 var id_buf: [32]u8 = undefined; 718 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 719 try out.appendSlice(allocator, "\" style=\"left:"); 720 var pos_buf: [128]u8 = undefined; 721 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 })); 722 try out.appendSlice(allocator, "\"></button>"); 723 } 724 }, 725 else => {}, 726 } 727 } 728 729 try out.appendSlice(allocator, "</form>"); 730 } 731 732 return try out.toOwnedSlice(allocator); 733 } 734 735 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 736 if (a) |av| return if (b) |bv| av.eql(bv) else false; 737 return b == null; 738 } 739 740 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 741 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 742 // empty slice when neither is set. 743 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 744 if (fg == null and bg == null) return buf[0..0]; 745 const prefix = " style=\""; 746 @memcpy(buf[0..prefix.len], prefix); 747 var i: usize = prefix.len; 748 if (fg) |c| { 749 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]; 750 i += s.len; 751 } 752 if (bg) |c| { 753 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]; 754 i += s.len; 755 } 756 buf[i] = '"'; 757 i += 1; 758 return buf[0..i]; 759 } 760 761 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 762 for (input) |ch| { 763 switch (ch) { 764 '&' => try out.appendSlice(allocator, "&amp;"), 765 '<' => try out.appendSlice(allocator, "&lt;"), 766 '>' => try out.appendSlice(allocator, "&gt;"), 767 '"' => try out.appendSlice(allocator, "&quot;"), 768 '\'' => try out.appendSlice(allocator, "&#39;"), 769 else => try out.append(allocator, ch), 770 } 771 } 772 } 773 774 // --- helpers -------------------------------------------------------------- 775 776 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 777 var iter = request.iterateHeaders(); 778 while (iter.next()) |header| { 779 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 780 var pairs = std.mem.splitScalar(u8, header.value, ';'); 781 while (pairs.next()) |pair| { 782 const trimmed = std.mem.trim(u8, pair, " \t"); 783 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 784 if (std.mem.eql(u8, trimmed[0..eq], name)) { 785 return trimmed[eq + 1 ..]; 786 } 787 } 788 } 789 return null; 790 } 791 792 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 793 var iter = std.mem.splitScalar(u8, body, '&'); 794 while (iter.next()) |pair| { 795 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 796 if (std.mem.eql(u8, pair[0..eq], key)) { 797 return try decodeFormValue(allocator, pair[eq + 1 ..]); 798 } 799 } 800 return null; 801 } 802 803 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 804 var out: std.ArrayList(u8) = .empty; 805 errdefer out.deinit(allocator); 806 var i: usize = 0; 807 while (i < encoded.len) : (i += 1) { 808 switch (encoded[i]) { 809 '+' => try out.append(allocator, ' '), 810 '%' => { 811 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 812 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 813 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 814 try out.append(allocator, hi * 16 + lo); 815 i += 2; 816 }, 817 else => try out.append(allocator, encoded[i]), 818 } 819 } 820 return try out.toOwnedSlice(allocator); 821 } 822 823 // disk-backed web session store. each login mints a random, opaque token 824 // (not the user's id) that is stored as a file named by the token hex, whose 825 // contents are the raw user_id bytes. authenticating a request is a lookup of 826 // the cookie's token; logout deletes the file, revoking the session. there is 827 // deliberately no expiry — a session lives until logout. 828 pub const SessionStore = struct { 829 io: std.Io, 830 dir: std.Io.Dir, 831 832 pub const token_hex_len = evt.event_id_size * 2; 833 834 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 835 try data_dir.createDirPath(io, "sessions"); 836 const dir = try data_dir.openDir(io, "sessions", .{}); 837 return .{ .io = io, .dir = dir }; 838 } 839 840 pub fn deinit(self: SessionStore) void { 841 self.dir.close(self.io); 842 } 843 844 // mint a new session for user_id, returning the token hex to set as the 845 // cookie value. 846 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 847 var token: [evt.event_id_size]u8 = undefined; 848 self.io.random(&token); 849 const token_hex = std.fmt.bytesToHex(token, .lower); 850 const file = try self.dir.createFile(self.io, &token_hex, .{}); 851 defer file.close(self.io); 852 try file.writeStreamingAll(self.io, user_id); 853 return token_hex; 854 } 855 856 // resolve a cookie's token to its user_id. returns false (logged out) for a 857 // missing, malformed, or unknown token. 858 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 859 if (!isToken(token_hex)) return false; 860 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 861 defer file.close(self.io); 862 var storage: [evt.event_id_size]u8 = undefined; 863 var file_reader = file.reader(self.io, &storage); 864 file_reader.interface.readSliceAll(out) catch return false; 865 return true; 866 } 867 868 // revoke a session. a no-op for a missing or malformed token. 869 pub fn remove(self: SessionStore, token_hex: []const u8) void { 870 if (!isToken(token_hex)) return; 871 self.dir.deleteFile(self.io, token_hex) catch {}; 872 } 873 874 // a token is exactly token_hex_len hex chars. validating before using the 875 // value as a path keeps attacker-supplied cookies from escaping the 876 // sessions dir (e.g. via "/" or ".." bytes). 877 fn isToken(token_hex: []const u8) bool { 878 if (token_hex.len != token_hex_len) return false; 879 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 880 return true; 881 } 882 }; 883