╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
2740 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2741 } else blk: { 2742 const v: u8 = 8 + (n - 232) * 10; 2743 break :blk .{ .r = v, .g = v, .b = v }; 2744 }, 2745 }; 2746 } 2747 2748 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2749 // cell's style into `buf`, omitting whichever color is unset. an inverted 2750 // cell swaps the two, falling back to the page's --fg/--bg variables for 2751 // whichever side is unset. text attributes follow the colors. returns an 2752 // empty slice when nothing is set. 2753 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2754 if (style.eql(.{})) return buf[0..0]; 2755 const prefix = " style=\""; 2756 @memcpy(buf[0..prefix.len], prefix); 2757 var i: usize = prefix.len; 2758 const inverted = style.inverted; 2759 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2760 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2761 const decoration: []const u8 = if (style.underline and style.strikethrough) 2762 "text-decoration:underline line-through;" 2763 else if (style.underline) 2764 "text-decoration:underline;" 2765 else if (style.strikethrough) 2766 "text-decoration:line-through;" 2767 else 2768 ""; 2769 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2770 if (style.bold) "font-weight:bold;" else "", 2771 if (style.italic) "font-style:italic;" else "", 2772 decoration, 2773 if (style.dim) "opacity:.6;" else "", 2774 }) catch return buf[0..0]; 2775 i += attributes.len; 2776 if (i >= buf.len) return buf[0..0]; 2777 buf[i] = '"'; 2778 return buf[0 .. i + 1]; 2779 } 2780 2781 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2782 // the color is unset (nothing when both are). returns the new end, or null 2783 // when it doesn't fit. 2784 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2785 const s = if (color) |c| blk: { 2786 const v = colorRgb(c); 2787 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2788 } else if (fallback) |f| 2789 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2790 else 2791 return i; 2792 return i + s.len; 2793 } 2794 2795 // a cell's link as an href, when it's a page path or a web or mail url 2796 fn webLink(link: ?[]const u8) ?[]const u8 { 2797 const url = link orelse return null; 2798 // a page path, not a protocol-relative url 2799 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2800 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2801 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2802 } 2803 return null; 2804 } 2805 2806 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2807 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2808 return b == null; 2809 } 2810 2811 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2812 for (input) |ch| { 2813 switch (ch) { 2814 '&' => try out.appendSlice(allocator, "&amp;"), 2815 '<' => try out.appendSlice(allocator, "&lt;"), 2816 '>' => try out.appendSlice(allocator, "&gt;"), 2817 '"' => try out.appendSlice(allocator, "&quot;"), 2818 '\'' => try out.appendSlice(allocator, "&#39;"), 2819 else => try out.append(allocator, ch), 2820 } 2821 } 2822 } 2823 2824 // --- helpers -------------------------------------------------------------- 2825 2826 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2827 var iter = request.iterateHeaders(); 2828 while (iter.next()) |header| { 2829 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2830 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2831 while (pairs.next()) |pair| { 2832 const trimmed = std.mem.trim(u8, pair, " \t"); 2833 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2834 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2835 return trimmed[eq + 1 ..]; 2836 } 2837 } 2838 } 2839 return null; 2840 } 2841 2842 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2843 var iter = std.mem.splitScalar(u8, body, '&'); 2844 while (iter.next()) |pair| { 2845 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2846 if (std.mem.eql(u8, pair[0..eq], key)) { 2847 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2848 } 2849 } 2850 return null; 2851 } 2852 2853 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2854 var buffer: [256]u8 = undefined; 2855 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2856 } 2857 2858 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2859 var out: std.ArrayList(u8) = .empty; 2860 errdefer out.deinit(allocator); 2861 var i: usize = 0; 2862 while (i < encoded.len) : (i += 1) { 2863 switch (encoded[i]) { 2864 '+' => try out.append(allocator, ' '), 2865 '%' => { 2866 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2867 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2868 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2869 try out.append(allocator, hi * 16 + lo); 2870 i += 2; 2871 }, 2872 else => try out.append(allocator, encoded[i]), 2873 } 2874 } 2875 return try out.toOwnedSlice(allocator); 2876 } 2877 2878 // disk-backed web session store. each login mints a random, opaque token 2879 // (not the user's id) that is stored as a file named by the token hex, whose 2880 // contents are the raw user_id bytes. authenticating a request is a lookup of 2881 // the cookie's token; logout deletes the file, revoking the session. there is 2882 // deliberately no expiry — a session lives until logout. form failures use 2883 // files in the flash subdirectory that the redirected GET consumes. the 2884 // directory is cleared whenever the server starts. 2885 pub const SessionStore = struct { 2886 io: std.Io, 2887 dir: std.Io.Dir, 2888 flash_dir: std.Io.Dir, 2889 auto_login: ?[token_hex_len]u8, 2890 2891 pub const token_hex_len = evt.event_id_size * 2; 2892 2893 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2894 try data_dir.createDirPath(io, "sessions"); 2895 const dir = try data_dir.openDir(io, "sessions", .{}); 2896 errdefer dir.close(io); 2897 try dir.deleteTree(io, "flash"); 2898 try dir.createDirPath(io, "flash"); 2899 const flash_dir = try dir.openDir(io, "flash", .{}); 2900 errdefer flash_dir.close(io); 2901 const auto_login = blk: { 2902 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2903 defer file.close(io); 2904 var token: [token_hex_len]u8 = undefined; 2905 var storage: [token_hex_len]u8 = undefined; 2906 var reader = file.reader(io, &storage); 2907 reader.interface.readSliceAll(&token) catch break :blk null; 2908 break :blk token; 2909 }; 2910 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2911 } 2912 2913 pub fn deinit(self: SessionStore) void { 2914 self.flash_dir.close(self.io); 2915 self.dir.close(self.io); 2916 } 2917 2918 // mint a new session for user_id, returning the token hex to set as the 2919 // cookie value. 2920 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2921 var token: [evt.event_id_size]u8 = undefined; 2922 self.io.random(&token); 2923 const token_hex = std.fmt.bytesToHex(token, .lower); 2924 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2925 defer file.close(self.io); 2926 try file.writeStreamingAll(self.io, user_id); 2927 return token_hex; 2928 } 2929 2930 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2931 var token: [evt.event_id_size]u8 = undefined; 2932 self.io.random(&token); 2933 const token_hex = std.fmt.bytesToHex(token, .lower); 2934 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2935 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2936 defer file.close(self.io); 2937 2938 var json: std.Io.Writer.Allocating = .init(allocator); 2939 defer json.deinit(); 2940 try std.json.Stringify.value(value, .{}, &json.writer); 2941 try file.writeStreamingAll(self.io, json.written()); 2942 return token_hex; 2943 } 2944 2945 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2946 if (!isToken(token_hex)) return null; 2947 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2948 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2949 defer file.close(self.io); 2950 2951 var storage: [4096]u8 = undefined; 2952 var reader = file.reader(self.io, &storage); 2953 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2954 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2955 } 2956 2957 // resolve a cookie's token to its user_id. returns false (logged out) for a 2958 // missing, malformed, or unknown token. 2959 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2960 if (!isToken(token_hex)) return false; 2961 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2962 defer file.close(self.io); 2963 var storage: [evt.event_id_size]u8 = undefined; 2964 var file_reader = file.reader(self.io, &storage); 2965 file_reader.interface.readSliceAll(out) catch return false; 2966 return true; 2967 } 2968 2969 // revoke a session. a no-op for a missing or malformed token. 2970 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2971 if (!isToken(token_hex)) return; 2972 self.dir.deleteFile(self.io, token_hex) catch {}; 2973 } 2974 2975 // leave `token_hex`'s session for visitors arriving without one. only the 2976 // `try` fixture writes one. the name can't collide with a session token. 2977 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2978 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2979 defer file.close(self.io); 2980 try file.writeStreamingAll(self.io, token_hex); 2981 } 2982 2983 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2984 out.* = self.auto_login orelse return false; 2985 return true; 2986 } 2987 2988 const auto_login_name = "auto-login"; 2989 2990 // a token is exactly token_hex_len hex chars. validating before using the 2991 // value as a path keeps attacker-supplied cookies from escaping the 2992 // sessions dir (e.g. via "/" or ".." bytes). 2993 fn isToken(token_hex: []const u8) bool { 2994 if (token_hex.len != token_hex_len) return false; 2995 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2996 return true; 2997 } 2998 }; 2999