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