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