╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2830 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2831 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2832 try appendFormAttribute(allocator, output, root_focus, id); 2833 if (ti.options.name.len > 0) { 2834 try output.appendSlice(allocator, " name=\""); 2835 try appendEscapedHtml(allocator, output, ti.options.name); 2836 try output.append(allocator, '"'); 2837 } 2838 if (child.focus.kind != .text_input_password) { 2839 const value = try ti.text(allocator); 2840 defer allocator.free(value); 2841 try output.appendSlice(allocator, " value=\""); 2842 try appendEscapedHtml(allocator, output, value); 2843 try output.append(allocator, '"'); 2844 } 2845 var pos_buf: [96]u8 = undefined; 2846 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2847 }, 2848 .custom => |custom| { 2849 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2850 if (formOwner(root_focus, id) == null) continue; 2851 var id_buf: [128]u8 = undefined; 2852 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2853 try appendFormAttribute(allocator, output, root_focus, id); 2854 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2855 try output.appendSlice(allocator, " formaction=\""); 2856 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2857 try output.append(allocator, '"'); 2858 } 2859 var pos_buf: [128]u8 = undefined; 2860 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2861 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2862 // an invisible native radio over the option, checked when the option is its row's selection 2863 const field = custom[ui.radio_prefix.len..]; 2864 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2865 const row = root_focus.children.get(child.parent_id) orelse continue; 2866 var id_buf: [128]u8 = undefined; 2867 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2868 try appendFormAttribute(allocator, output, root_focus, id); 2869 try output.appendSlice(allocator, " name=\""); 2870 try appendEscapedHtml(allocator, output, field[0..separator]); 2871 try output.appendSlice(allocator, "\" value=\""); 2872 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2873 try output.append(allocator, '"'); 2874 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2875 var pos_buf: [128]u8 = undefined; 2876 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2877 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2878 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2879 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2880 var id_buf: [128]u8 = undefined; 2881 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2882 } 2883 }, 2884 else => {}, 2885 } 2886 } 2887 } 2888 2889 // emit hidden form owners beside the rendered panels. their controls point 2890 // back here with the standard HTML `form` attribute. 2891 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2892 // the focus child map preserves insertion order, which matches the order 2893 // widgets were added in code 2894 var iter = root_focus.children.iterator(); 2895 while (iter.next()) |entry| { 2896 const child = entry.value_ptr.*; 2897 const action_url = formAction(child.focus) orelse continue; 2898 2899 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2900 var id_buf: [96]u8 = undefined; 2901 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2902 try appendEscapedHtml(allocator, output, action_url); 2903 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2904 } 2905 } 2906 2907 // the 16 ansi colors as the browser shows them (xterm's defaults) 2908 const ansi_palette = [16]Grid.Color.Rgb{ 2909 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2910 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2911 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2912 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2913 }; 2914 2915 // resolve any color to rgb: palette colors through the ansi table and the 2916 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2917 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2918 return switch (color) { 2919 .rgb => |c| c, 2920 .ansi => |a| ansi_palette[@backingInt(a)], 2921 .indexed => |n| if (n < 16) 2922 ansi_palette[n] 2923 else if (n < 232) blk: { 2924 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2925 const i = n - 16; 2926 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2927 } else blk: { 2928 const v: u8 = 8 + (n - 232) * 10; 2929 break :blk .{ .r = v, .g = v, .b = v }; 2930 }, 2931 }; 2932 } 2933 2934 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2935 // cell's style into `buf`, omitting whichever color is unset. an inverted 2936 // cell swaps the two, falling back to the page's --fg/--bg variables for 2937 // whichever side is unset. text attributes follow the colors. returns an 2938 // empty slice when nothing is set. 2939 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2940 if (style.eql(.{})) return buf[0..0]; 2941 const prefix = " style=\""; 2942 @memcpy(buf[0..prefix.len], prefix); 2943 var i: usize = prefix.len; 2944 const inverted = style.inverted; 2945 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2946 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2947 const decoration: []const u8 = if (style.underline and style.strikethrough) 2948 "text-decoration:underline line-through;" 2949 else if (style.underline) 2950 "text-decoration:underline;" 2951 else if (style.strikethrough) 2952 "text-decoration:line-through;" 2953 else 2954 ""; 2955 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2956 if (style.bold) "font-weight:bold;" else "", 2957 if (style.italic) "font-style:italic;" else "", 2958 decoration, 2959 if (style.dim) "opacity:.6;" else "", 2960 }) catch return buf[0..0]; 2961 i += attributes.len; 2962 if (i >= buf.len) return buf[0..0]; 2963 buf[i] = '"'; 2964 return buf[0 .. i + 1]; 2965 } 2966 2967 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2968 // the color is unset (nothing when both are). returns the new end, or null 2969 // when it doesn't fit. 2970 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2971 const s = if (color) |c| blk: { 2972 const v = colorRgb(c); 2973 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; 2974 } else if (fallback) |f| 2975 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2976 else 2977 return i; 2978 return i + s.len; 2979 } 2980 2981 // a cell's link as an href, when it's a page path or a web or mail url 2982 fn webLink(link: ?[]const u8) ?[]const u8 { 2983 const url = link orelse return null; 2984 // a page path, not a protocol-relative url 2985 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2986 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2987 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2988 } 2989 return null; 2990 } 2991 2992 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2993 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2994 return b == null; 2995 } 2996 2997 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2998 for (input) |ch| { 2999 switch (ch) { 3000 '&' => try out.appendSlice(allocator, "&amp;"), 3001 '<' => try out.appendSlice(allocator, "&lt;"), 3002 '>' => try out.appendSlice(allocator, "&gt;"), 3003 '"' => try out.appendSlice(allocator, "&quot;"), 3004 '\'' => try out.appendSlice(allocator, "&#39;"), 3005 else => try out.append(allocator, ch), 3006 } 3007 } 3008 } 3009 3010 // --- helpers -------------------------------------------------------------- 3011 3012 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 3013 var iter = request.iterateHeaders(); 3014 while (iter.next()) |header| { 3015 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 3016 var pairs = std.mem.splitScalar(u8, header.value, ';'); 3017 while (pairs.next()) |pair| { 3018 const trimmed = std.mem.trim(u8, pair, " \t"); 3019 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 3020 if (std.mem.eql(u8, trimmed[0..eq], name)) { 3021 return trimmed[eq + 1 ..]; 3022 } 3023 } 3024 } 3025 return null; 3026 } 3027 3028 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 3029 var iter = std.mem.splitScalar(u8, body, '&'); 3030 while (iter.next()) |pair| { 3031 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 3032 if (std.mem.eql(u8, pair[0..eq], key)) { 3033 return try decodeFormValue(allocator, pair[eq + 1 ..]); 3034 } 3035 } 3036 return null; 3037 } 3038 3039 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 3040 var buffer: [256]u8 = undefined; 3041 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 3042 } 3043 3044 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 3045 var out: std.ArrayList(u8) = .empty; 3046 errdefer out.deinit(allocator); 3047 var i: usize = 0; 3048 while (i < encoded.len) : (i += 1) { 3049 switch (encoded[i]) { 3050 '+' => try out.append(allocator, ' '), 3051 '%' => { 3052 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 3053 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 3054 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 3055 try out.append(allocator, hi * 16 + lo); 3056 i += 2; 3057 }, 3058 else => try out.append(allocator, encoded[i]), 3059 } 3060 } 3061 return try out.toOwnedSlice(allocator); 3062 } 3063 3064 // disk-backed web session store. each login mints a random, opaque token 3065 // (not the user's id) that is stored as a file named by the token hex, whose 3066 // contents are the raw user_id bytes. authenticating a request is a lookup of 3067 // the cookie's token; logout deletes the file, revoking the session. there is 3068 // deliberately no expiry — a session lives until logout. form failures use 3069 // files in the flash subdirectory that the redirected GET consumes. the 3070 // directory is cleared whenever the server starts. 3071 pub const SessionStore = struct { 3072 io: std.Io, 3073 dir: std.Io.Dir, 3074 flash_dir: std.Io.Dir, 3075 auto_login: ?[token_hex_len]u8, 3076 3077 pub const token_hex_len = evt.event_id_size * 2; 3078 3079 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3080 try data_dir.createDirPath(io, "sessions"); 3081 const dir = try data_dir.openDir(io, "sessions", .{}); 3082 errdefer dir.close(io); 3083 try dir.deleteTree(io, "flash"); 3084 try dir.createDirPath(io, "flash"); 3085 const flash_dir = try dir.openDir(io, "flash", .{}); 3086 errdefer flash_dir.close(io); 3087 const auto_login = blk: { 3088 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3089 defer file.close(io); 3090 var token: [token_hex_len]u8 = undefined; 3091 var storage: [token_hex_len]u8 = undefined; 3092 var reader = file.reader(io, &storage); 3093 reader.interface.readSliceAll(&token) catch break :blk null; 3094 break :blk token; 3095 }; 3096 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3097 } 3098 3099 pub fn deinit(self: SessionStore) void { 3100 self.flash_dir.close(self.io); 3101 self.dir.close(self.io); 3102 } 3103 3104 // mint a new session for user_id, returning the token hex to set as the 3105 // cookie value. 3106 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3107 var token: [evt.event_id_size]u8 = undefined; 3108 self.io.random(&token); 3109 const token_hex = std.fmt.bytesToHex(token, .lower); 3110 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3111 defer file.close(self.io); 3112 try file.writeStreamingAll(self.io, user_id); 3113 return token_hex; 3114 } 3115 3116 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3117 var token: [evt.event_id_size]u8 = undefined; 3118 self.io.random(&token); 3119 const token_hex = std.fmt.bytesToHex(token, .lower); 3120 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3121 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3122 defer file.close(self.io); 3123 3124 var json: std.Io.Writer.Allocating = .init(allocator); 3125 defer json.deinit(); 3126 try std.json.Stringify.value(value, .{}, &json.writer); 3127 try file.writeStreamingAll(self.io, json.written()); 3128 return token_hex; 3129 } 3130 3131 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3132 if (!isToken(token_hex)) return null; 3133 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3134 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3135 defer file.close(self.io); 3136 3137 var storage: [4096]u8 = undefined; 3138 var reader = file.reader(self.io, &storage); 3139 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3140 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3141 } 3142 3143 // resolve a cookie's token to its user_id. returns false (logged out) for a 3144 // missing, malformed, or unknown token. 3145 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3146 if (!isToken(token_hex)) return false; 3147 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3148 defer file.close(self.io); 3149 var storage: [evt.event_id_size]u8 = undefined; 3150 var file_reader = file.reader(self.io, &storage); 3151 file_reader.interface.readSliceAll(out) catch return false; 3152 return true; 3153 } 3154 3155 // revoke a session. a no-op for a missing or malformed token. 3156 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3157 if (!isToken(token_hex)) return; 3158 self.dir.deleteFile(self.io, token_hex) catch {}; 3159 } 3160 3161 // leave `token_hex`'s session for visitors arriving without one. only the 3162 // `try` fixture writes one. the name can't collide with a session token. 3163 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3164 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3165 defer file.close(self.io); 3166 try file.writeStreamingAll(self.io, token_hex); 3167 } 3168 3169 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3170 out.* = self.auto_login orelse return false; 3171 return true; 3172 } 3173 3174 const auto_login_name = "auto-login"; 3175 3176 // a token is exactly token_hex_len hex chars. validating before using the 3177 // value as a path keeps attacker-supplied cookies from escaping the 3178 // sessions dir (e.g. via "/" or ".." bytes). 3179 fn isToken(token_hex: []const u8) bool { 3180 if (token_hex.len != token_hex_len) return false; 3181 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3182 return true; 3183 } 3184 }; 3185