╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
629 try out.appendSlice(allocator, "\" data-focus-id=\""); 630 var id_buf: [32]u8 = undefined; 631 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 632 if (ti.options.name.len > 0) { 633 try out.appendSlice(allocator, "\" name=\""); 634 try appendEscapedHtml(allocator, &out, ti.options.name); 635 } 636 // intentionally no `value` attribute: the browser tracks user input 637 // natively, and including the wasm-side value here would make the 638 // overlay HTML differ on every keystroke — that would trip the diff 639 // in _setOverlay and rebuild the <input>, eating the user's caret. 640 try out.appendSlice(allocator, "\" style=\"left:"); 641 var pos_buf: [64]u8 = undefined; 642 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 643 try out.appendSlice(allocator, "\">"); 644 }, 645 .custom => |custom| { 646 if (std.mem.eql(u8, "submit", custom)) { 647 // inside the dashed border the TUI cells draw around the button. 648 const inner_left = r.x + 1; 649 const inner_top = r.y + 1; 650 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 651 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 652 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 653 var id_buf: [32]u8 = undefined; 654 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 655 try out.appendSlice(allocator, "\" style=\"left:"); 656 var pos_buf: [128]u8 = undefined; 657 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 658 try out.appendSlice(allocator, "\"></button>"); 659 } 660 }, 661 else => {}, 662 } 663 } 664 665 try out.appendSlice(allocator, "</form>"); 666 } 667 668 return try out.toOwnedSlice(allocator); 669 } 670 671 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 672 if (a) |av| return if (b) |bv| av.eql(bv) else false; 673 return b == null; 674 } 675 676 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 677 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 678 // empty slice when neither is set. 679 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 680 if (fg == null and bg == null) return buf[0..0]; 681 const prefix = " style=\""; 682 @memcpy(buf[0..prefix.len], prefix); 683 var i: usize = prefix.len; 684 if (fg) |c| { 685 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 686 i += s.len; 687 } 688 if (bg) |c| { 689 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 690 i += s.len; 691 } 692 buf[i] = '"'; 693 i += 1; 694 return buf[0..i]; 695 } 696 697 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 698 for (input) |ch| { 699 switch (ch) { 700 '&' => try out.appendSlice(allocator, "&amp;"), 701 '<' => try out.appendSlice(allocator, "&lt;"), 702 '>' => try out.appendSlice(allocator, "&gt;"), 703 '"' => try out.appendSlice(allocator, "&quot;"), 704 '\'' => try out.appendSlice(allocator, "&#39;"), 705 else => try out.append(allocator, ch), 706 } 707 } 708 } 709 710 // --- helpers -------------------------------------------------------------- 711 712 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 713 var iter = request.iterateHeaders(); 714 while (iter.next()) |header| { 715 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 716 var pairs = std.mem.splitScalar(u8, header.value, ';'); 717 while (pairs.next()) |pair| { 718 const trimmed = std.mem.trim(u8, pair, " \t"); 719 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 720 if (std.mem.eql(u8, trimmed[0..eq], name)) { 721 return trimmed[eq + 1 ..]; 722 } 723 } 724 } 725 return null; 726 } 727 728 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 729 var iter = std.mem.splitScalar(u8, body, '&'); 730 while (iter.next()) |pair| { 731 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 732 if (std.mem.eql(u8, pair[0..eq], key)) { 733 return try decodeFormValue(allocator, pair[eq + 1 ..]); 734 } 735 } 736 return null; 737 } 738 739 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 740 var out: std.ArrayList(u8) = .empty; 741 errdefer out.deinit(allocator); 742 var i: usize = 0; 743 while (i < encoded.len) : (i += 1) { 744 switch (encoded[i]) { 745 '+' => try out.append(allocator, ' '), 746 '%' => { 747 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 748 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 749 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 750 try out.append(allocator, hi * 16 + lo); 751 i += 2; 752 }, 753 else => try out.append(allocator, encoded[i]), 754 } 755 } 756 return try out.toOwnedSlice(allocator); 757 } 758 759 // disk-backed web session store. each login mints a random, opaque token 760 // (not the user's id) that is stored as a file named by the token hex, whose 761 // contents are the raw user_id bytes. authenticating a request is a lookup of 762 // the cookie's token; logout deletes the file, revoking the session. there is 763 // deliberately no expiry — a session lives until logout. 764 pub const SessionStore = struct { 765 io: std.Io, 766 dir: std.Io.Dir, 767 768 pub const token_hex_len = evt.event_id_size * 2; 769 770 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 771 try data_dir.createDirPath(io, "sessions"); 772 const dir = try data_dir.openDir(io, "sessions", .{}); 773 return .{ .io = io, .dir = dir }; 774 } 775 776 pub fn deinit(self: SessionStore) void { 777 self.dir.close(self.io); 778 } 779 780 // mint a new session for user_id, returning the token hex to set as the 781 // cookie value. 782 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 783 var token: [evt.event_id_size]u8 = undefined; 784 self.io.random(&token); 785 const token_hex = std.fmt.bytesToHex(token, .lower); 786 const file = try self.dir.createFile(self.io, &token_hex, .{}); 787 defer file.close(self.io); 788 try file.writeStreamingAll(self.io, user_id); 789 return token_hex; 790 } 791 792 // resolve a cookie's token to its user_id. returns false (logged out) for a 793 // missing, malformed, or unknown token. 794 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 795 if (!isToken(token_hex)) return false; 796 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 797 defer file.close(self.io); 798 var storage: [evt.event_id_size]u8 = undefined; 799 var file_reader = file.reader(self.io, &storage); 800 file_reader.interface.readSliceAll(out) catch return false; 801 return true; 802 } 803 804 // revoke a session. a no-op for a missing or malformed token. 805 pub fn remove(self: SessionStore, token_hex: []const u8) void { 806 if (!isToken(token_hex)) return; 807 self.dir.deleteFile(self.io, token_hex) catch {}; 808 } 809 810 // a token is exactly token_hex_len hex chars. validating before using the 811 // value as a path keeps attacker-supplied cookies from escaping the 812 // sessions dir (e.g. via "/" or ".." bytes). 813 fn isToken(token_hex: []const u8) bool { 814 if (token_hex.len != token_hex_len) return false; 815 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 816 return true; 817 } 818 }; 819