╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2048 for (0..grid.size.width) |x| { 2049 const cell = (try grid.cell(x, y)).*; 2050 // a cell covered by a child scroll's viewport is drawn by that scroll's 2051 // own div, so blank its glyph and make it non-clickable here — but keep 2052 // its background, so the backdrop still shows through the scroll's 2053 // transparent div instead of a bare hole. 2054 const covered_by_scroll = blk: { 2055 for (direct.items) |id| { 2056 const r = (focus.children.get(id) orelse continue).rect; 2057 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 2058 } 2059 break :blk false; 2060 }; 2061 // the focusable owning the cell at (x, y); none for a covered cell. 2062 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2063 const fg = if (covered_by_scroll) null else cell.style.fg; 2064 const bg = cell.style.bg; 2065 const inverted = !covered_by_scroll and cell.style.inverted; 2066 2067 if (first or cell_id != cur_id or !std.meta.eql(fg, cur_fg) or !std.meta.eql(bg, cur_bg) or inverted != cur_inverted) { 2068 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2069 2070 var new_tag: ?CellTag = null; 2071 if (cell_id) |id| { 2072 if (focus.children.get(id)) |child| { 2073 new_tag = switch (child.focus.kind) { 2074 .custom => |custom| CellTag.init(custom), 2075 else => .span, 2076 }; 2077 } 2078 } 2079 if (new_tag == null and (fg != null or bg != null or inverted)) new_tag = .plain; 2080 2081 if (new_tag) |t| { 2082 var style_buf: [64]u8 = undefined; 2083 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg, inverted)); 2084 } 2085 2086 open_tag = new_tag; 2087 cur_id = cell_id; 2088 cur_fg = fg; 2089 cur_bg = bg; 2090 cur_inverted = inverted; 2091 first = false; 2092 } 2093 2094 if (covered_by_scroll) { 2095 try appendEscapedHtml(allocator, output, " "); 2096 } else if (cell.continuation) { 2097 // the wide rune to the left was emitted 2ch wide, covering this column 2098 } else if (cell.rune) |rune| { 2099 var encoded: [4]u8 = undefined; 2100 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2101 const rune_text = encoded[0..encoded_len]; 2102 // a double-width rune is pinned inside a 2ch span so the 2103 // fallback glyph's advance width can't shift the rest of the row 2104 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2105 if (wide) { 2106 try output.appendSlice(allocator, "<span class=\"w2\">"); 2107 try appendEscapedHtml(allocator, output, rune_text); 2108 try output.appendSlice(allocator, "</span>"); 2109 } else { 2110 try appendEscapedHtml(allocator, output, rune_text); 2111 } 2112 } else { 2113 try appendEscapedHtml(allocator, output, " "); 2114 } 2115 } 2116 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2117 try output.append(allocator, '\n'); 2118 } 2119 try output.appendSlice(allocator, "</div>"); 2120 2121 // native controls live in their panel, beside the replaceable cells. their 2122 // stable keys let JS update layout without recreating their DOM nodes, and 2123 // being actual descendants of a scroll gives them native movement/clipping. 2124 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2125 2126 // each child scroll becomes a natively-scrollable div positioned over its 2127 // viewport, holding its full content rendered recursively. 2128 for (direct.items) |id| { 2129 const child = focus.children.get(id) orelse continue; 2130 const info = child.focus.scroll orelse continue; 2131 const r = child.rect; 2132 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2133 // when that axis actually overflows. the other axis is clipped (hidden), 2134 // matching how the terminal Scroll handles its non-scrolling axis. 2135 const overflow = switch (info.direction) { 2136 .vert => "overflow-x:hidden;overflow-y:auto", 2137 .horiz => "overflow-x:auto;overflow-y:hidden", 2138 .both => "overflow:auto", 2139 }; 2140 // the id carries a content version so JS preserves the native scroll 2141 // position across re-renders of the same content but resets it when the 2142 // content is replaced — e.g. selecting a different commit. the widget's 2143 // scroll offset (in cells) rides along so JS can apply it when it has no 2144 // preserved position, letting a wasm-side scrollToRect (the files list 2145 // scrolling to its selected row on page load) reach the browser. 2146 var buf: [256]u8 = undefined; 2147 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 })); 2148 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2149 try output.appendSlice(allocator, "</div>"); 2150 } 2151 } 2152 2153 const form_prefix = "form:"; 2154 const form_id_prefix = "haxy-form-"; 2155 2156 fn formAction(focus: *const Focus) ?[]const u8 { 2157 return switch (focus.kind) { 2158 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2159 else => null, 2160 }; 2161 } 2162 2163 // find the form ancestor of a flattened focus-tree child. html's `form` 2164 // attribute then associates the control with that form without requiring the 2165 // form and control to share a DOM parent. 2166 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2167 var id = focus_id; 2168 while (root_focus.children.get(id)) |child| { 2169 const parent_id = child.parent_id; 2170 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2171 const parent = root_focus.children.get(parent_id) orelse return null; 2172 if (formAction(parent.focus) != null) return parent_id; 2173 id = parent_id; 2174 } 2175 return null; 2176 } 2177 2178 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2179 const form_id = formOwner(root_focus, focus_id) orelse return; 2180 var buf: [64]u8 = undefined; 2181 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2182 } 2183 2184 fn renderPanelControls( 2185 allocator: std.mem.Allocator, 2186 output: *std.ArrayList(u8), 2187 focus: *Focus, 2188 session: *ui.Session, 2189 root_focus: *Focus, 2190 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2191 ) !void { 2192 var iter = focus.children.iterator(); 2193 while (iter.next()) |entry| { 2194 const id = entry.key_ptr.*; 2195 if (excluded.contains(id)) continue; 2196 const child = entry.value_ptr.*; 2197 const r = child.rect; 2198 2199 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2200 2201 switch (child.focus.kind) { 2202 .text_input, .text_input_password, .text_area => { 2203 const ti = session.text_inputs.get(id) orelse continue; 2204 2205 const inner_left = r.x + 1; 2206 const inner_top = r.y + 1; 2207 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2208 const preserve = !ti.options.read_only; 2209 2210 if (child.focus.kind == .text_area) { 2211 const value = try ti.text(allocator); 2212 defer allocator.free(value); 2213 var id_buf: [128]u8 = undefined; 2214 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2215 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2216 try appendFormAttribute(allocator, output, root_focus, id); 2217 if (ti.options.name.len > 0) { 2218 try output.appendSlice(allocator, " name=\""); 2219 try appendEscapedHtml(allocator, output, ti.options.name); 2220 try output.append(allocator, '"'); 2221 } 2222 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2223 var pos_buf: [128]u8 = undefined; 2224 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 })); 2225 try appendEscapedHtml(allocator, output, value); 2226 try output.appendSlice(allocator, "</textarea>"); 2227 continue; 2228 } 2229 2230 var id_buf: [160]u8 = undefined; 2231 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 })); 2232 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2233 try appendFormAttribute(allocator, output, root_focus, id); 2234 if (ti.options.name.len > 0) { 2235 try output.appendSlice(allocator, " name=\""); 2236 try appendEscapedHtml(allocator, output, ti.options.name); 2237 try output.append(allocator, '"'); 2238 } 2239 if (child.focus.kind != .text_input_password) { 2240 const value = try ti.text(allocator); 2241 defer allocator.free(value); 2242 try output.appendSlice(allocator, " value=\""); 2243 try appendEscapedHtml(allocator, output, value); 2244 try output.append(allocator, '"'); 2245 } 2246 var pos_buf: [96]u8 = undefined; 2247 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 })); 2248 }, 2249 .custom => |custom| { 2250 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2251 if (formOwner(root_focus, id) == null) continue; 2252 var id_buf: [128]u8 = undefined; 2253 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2254 try appendFormAttribute(allocator, output, root_focus, id); 2255 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2256 try output.appendSlice(allocator, " formaction=\""); 2257 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2258 try output.append(allocator, '"'); 2259 } 2260 var pos_buf: [128]u8 = undefined; 2261 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 })); 2262 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2263 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2264 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2265 var id_buf: [128]u8 = undefined; 2266 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 })); 2267 } 2268 }, 2269 else => {}, 2270 } 2271 } 2272 } 2273 2274 // emit hidden form owners beside the rendered panels. their controls point 2275 // back here with the standard HTML `form` attribute. 2276 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2277 // the focus child map preserves insertion order, which matches the order 2278 // widgets were added in code 2279 var iter = root_focus.children.iterator(); 2280 while (iter.next()) |entry| { 2281 const child = entry.value_ptr.*; 2282 const action_url = formAction(child.focus) orelse continue; 2283 2284 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2285 var id_buf: [96]u8 = undefined; 2286 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2287 try appendEscapedHtml(allocator, output, action_url); 2288 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2289 } 2290 } 2291 2292 // the 16 ansi colors as the browser shows them (xterm's defaults) 2293 const ansi_palette = [16]Grid.Color.Rgb{ 2294 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2295 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2296 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2297 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2298 }; 2299 2300 // resolve any color to rgb: palette colors through the ansi table and the 2301 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2302 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2303 return switch (color) { 2304 .rgb => |c| c, 2305 .ansi => |a| ansi_palette[@intFromEnum(a)], 2306 .indexed => |n| if (n < 16) 2307 ansi_palette[n] 2308 else if (n < 232) blk: { 2309 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2310 const i = n - 16; 2311 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2312 } else blk: { 2313 const v: u8 = 8 + (n - 232) * 10; 2314 break :blk .{ .r = v, .g = v, .b = v }; 2315 }, 2316 }; 2317 } 2318 2319 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2320 // cell's fg/bg into `buf`, omitting whichever color is unset. an inverted 2321 // cell swaps the two, falling back to the page's --fg/--bg variables for 2322 // whichever side is unset. returns an empty slice when nothing is set. 2323 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color, inverted: bool) []const u8 { 2324 if (fg == null and bg == null and !inverted) return buf[0..0]; 2325 const prefix = " style=\""; 2326 @memcpy(buf[0..prefix.len], prefix); 2327 var i: usize = prefix.len; 2328 i = cssColor(buf, i, "color", if (inverted) bg else fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2329 i = cssColor(buf, i, "background-color", if (inverted) fg else bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2330 buf[i] = '"'; 2331 return buf[0 .. i + 1]; 2332 } 2333 2334 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2335 // the color is unset (nothing when both are). returns the new end, or null 2336 // when it doesn't fit. 2337 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2338 const s = if (color) |c| blk: { 2339 const v = colorRgb(c); 2340 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; 2341 } else if (fallback) |f| 2342 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2343 else 2344 return i; 2345 return i + s.len; 2346 } 2347 2348 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2349 for (input) |ch| { 2350 switch (ch) { 2351 '&' => try out.appendSlice(allocator, "&amp;"), 2352 '<' => try out.appendSlice(allocator, "&lt;"), 2353 '>' => try out.appendSlice(allocator, "&gt;"), 2354 '"' => try out.appendSlice(allocator, "&quot;"), 2355 '\'' => try out.appendSlice(allocator, "&#39;"), 2356 else => try out.append(allocator, ch), 2357 } 2358 } 2359 } 2360 2361 // --- helpers -------------------------------------------------------------- 2362 2363 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2364 var iter = request.iterateHeaders(); 2365 while (iter.next()) |header| { 2366 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2367 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2368 while (pairs.next()) |pair| { 2369 const trimmed = std.mem.trim(u8, pair, " \t"); 2370 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2371 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2372 return trimmed[eq + 1 ..]; 2373 } 2374 } 2375 } 2376 return null; 2377 } 2378 2379 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2380 var iter = std.mem.splitScalar(u8, body, '&'); 2381 while (iter.next()) |pair| { 2382 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2383 if (std.mem.eql(u8, pair[0..eq], key)) { 2384 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2385 } 2386 } 2387 return null; 2388 } 2389 2390 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2391 var buffer: [256]u8 = undefined; 2392 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2393 } 2394 2395 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2396 var out: std.ArrayList(u8) = .empty; 2397 errdefer out.deinit(allocator); 2398 var i: usize = 0; 2399 while (i < encoded.len) : (i += 1) { 2400 switch (encoded[i]) { 2401 '+' => try out.append(allocator, ' '), 2402 '%' => { 2403 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2404 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2405 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2406 try out.append(allocator, hi * 16 + lo); 2407 i += 2; 2408 }, 2409 else => try out.append(allocator, encoded[i]), 2410 } 2411 } 2412 return try out.toOwnedSlice(allocator); 2413 } 2414 2415 // disk-backed web session store. each login mints a random, opaque token 2416 // (not the user's id) that is stored as a file named by the token hex, whose 2417 // contents are the raw user_id bytes. authenticating a request is a lookup of 2418 // the cookie's token; logout deletes the file, revoking the session. there is 2419 // deliberately no expiry — a session lives until logout. form failures use 2420 // files in the flash subdirectory that the redirected GET consumes. the 2421 // directory is cleared whenever the server starts. 2422 pub const SessionStore = struct { 2423 io: std.Io, 2424 dir: std.Io.Dir, 2425 flash_dir: std.Io.Dir, 2426 auto_login: ?[token_hex_len]u8, 2427 2428 pub const token_hex_len = evt.event_id_size * 2; 2429 2430 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2431 try data_dir.createDirPath(io, "sessions"); 2432 const dir = try data_dir.openDir(io, "sessions", .{}); 2433 errdefer dir.close(io); 2434 try dir.deleteTree(io, "flash"); 2435 try dir.createDirPath(io, "flash"); 2436 const flash_dir = try dir.openDir(io, "flash", .{}); 2437 errdefer flash_dir.close(io); 2438 const auto_login = blk: { 2439 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2440 defer file.close(io); 2441 var token: [token_hex_len]u8 = undefined; 2442 var storage: [token_hex_len]u8 = undefined; 2443 var reader = file.reader(io, &storage); 2444 reader.interface.readSliceAll(&token) catch break :blk null; 2445 break :blk token; 2446 }; 2447 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2448 } 2449 2450 pub fn deinit(self: SessionStore) void { 2451 self.flash_dir.close(self.io); 2452 self.dir.close(self.io); 2453 } 2454 2455 // mint a new session for user_id, returning the token hex to set as the 2456 // cookie value. 2457 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2458 var token: [evt.event_id_size]u8 = undefined; 2459 self.io.random(&token); 2460 const token_hex = std.fmt.bytesToHex(token, .lower); 2461 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2462 defer file.close(self.io); 2463 try file.writeStreamingAll(self.io, user_id); 2464 return token_hex; 2465 } 2466 2467 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2468 var token: [evt.event_id_size]u8 = undefined; 2469 self.io.random(&token); 2470 const token_hex = std.fmt.bytesToHex(token, .lower); 2471 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2472 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2473 defer file.close(self.io); 2474 2475 var json: std.Io.Writer.Allocating = .init(allocator); 2476 defer json.deinit(); 2477 try std.json.Stringify.value(value, .{}, &json.writer); 2478 try file.writeStreamingAll(self.io, json.written()); 2479 return token_hex; 2480 } 2481 2482 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2483 if (!isToken(token_hex)) return null; 2484 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2485 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2486 defer file.close(self.io); 2487 2488 var storage: [4096]u8 = undefined; 2489 var reader = file.reader(self.io, &storage); 2490 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2491 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2492 } 2493 2494 // resolve a cookie's token to its user_id. returns false (logged out) for a 2495 // missing, malformed, or unknown token. 2496 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2497 if (!isToken(token_hex)) return false; 2498 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2499 defer file.close(self.io); 2500 var storage: [evt.event_id_size]u8 = undefined; 2501 var file_reader = file.reader(self.io, &storage); 2502 file_reader.interface.readSliceAll(out) catch return false; 2503 return true; 2504 } 2505 2506 // revoke a session. a no-op for a missing or malformed token. 2507 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2508 if (!isToken(token_hex)) return; 2509 self.dir.deleteFile(self.io, token_hex) catch {}; 2510 } 2511 2512 // leave `token_hex`'s session for visitors arriving without one. only the 2513 // `try` fixture writes one. the name can't collide with a session token. 2514 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2515 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2516 defer file.close(self.io); 2517 try file.writeStreamingAll(self.io, token_hex); 2518 } 2519 2520 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2521 out.* = self.auto_login orelse return false; 2522 return true; 2523 } 2524 2525 const auto_login_name = "auto-login"; 2526 2527 // a token is exactly token_hex_len hex chars. validating before using the 2528 // value as a path keeps attacker-supplied cookies from escaping the 2529 // sessions dir (e.g. via "/" or ".." bytes). 2530 fn isToken(token_hex: []const u8) bool { 2531 if (token_hex.len != token_hex_len) return false; 2532 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2533 return true; 2534 } 2535 }; 2536