╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
557 try appendEscapedHtml(allocator, &out, ti.options.name); 558 } 559 // intentionally no `value` attribute: the browser tracks user input 560 // natively, and including the wasm-side value here would make the 561 // overlay HTML differ on every keystroke — that would trip the diff 562 // in _setOverlay and rebuild the <input>, eating the user's caret. 563 try out.appendSlice(allocator, "\" style=\"left:"); 564 var pos_buf: [64]u8 = undefined; 565 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 })); 566 try out.appendSlice(allocator, "\">"); 567 }, 568 .custom => |custom| { 569 if (std.mem.eql(u8, "submit", custom)) { 570 // inside the dashed border the TUI cells draw around the button. 571 const inner_left = r.x + 1; 572 const inner_top = r.y + 1; 573 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 574 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 575 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 576 var id_buf: [32]u8 = undefined; 577 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 578 try out.appendSlice(allocator, "\" style=\"left:"); 579 var pos_buf: [128]u8 = undefined; 580 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 })); 581 try out.appendSlice(allocator, "\"></button>"); 582 } 583 }, 584 else => {}, 585 } 586 } 587 588 try out.appendSlice(allocator, "</form>"); 589 } 590 591 return try out.toOwnedSlice(allocator); 592 } 593 594 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 595 if (a) |av| return if (b) |bv| av.eql(bv) else false; 596 return b == null; 597 } 598 599 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 600 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 601 // empty slice when neither is set. 602 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 603 if (fg == null and bg == null) return buf[0..0]; 604 const prefix = " style=\""; 605 @memcpy(buf[0..prefix.len], prefix); 606 var i: usize = prefix.len; 607 if (fg) |c| { 608 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]; 609 i += s.len; 610 } 611 if (bg) |c| { 612 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]; 613 i += s.len; 614 } 615 buf[i] = '"'; 616 i += 1; 617 return buf[0..i]; 618 } 619 620 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 621 var iter = focus.children.iterator(); 622 while (iter.next()) |entry| { 623 const child = entry.value_ptr.*; 624 if (!child.focus.focusable) continue; 625 const r = child.rect; 626 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 627 return entry.key_ptr.*; 628 } 629 } 630 return null; 631 } 632 633 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 634 for (input) |ch| { 635 switch (ch) { 636 '&' => try out.appendSlice(allocator, "&amp;"), 637 '<' => try out.appendSlice(allocator, "&lt;"), 638 '>' => try out.appendSlice(allocator, "&gt;"), 639 '"' => try out.appendSlice(allocator, "&quot;"), 640 '\'' => try out.appendSlice(allocator, "&#39;"), 641 else => try out.append(allocator, ch), 642 } 643 } 644 } 645 646 // --- helpers -------------------------------------------------------------- 647 648 fn openHaxyMoment( 649 comptime repo_opts: rp.RepoOpts(.xit), 650 repo: *rp.Repo(.xit, repo_opts), 651 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 652 const DB = rp.Repo(.xit, repo_opts).DB; 653 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 654 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 655 const moment = try DB.HashMap(.read_only).init(moment_cursor); 656 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 657 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 658 _ = try last_object_id_cursor.readBytes(&last_object_id); 659 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 660 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 661 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 662 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 663 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 664 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 665 } 666 667 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 668 var iter = request.iterateHeaders(); 669 while (iter.next()) |header| { 670 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 671 var pairs = std.mem.splitScalar(u8, header.value, ';'); 672 while (pairs.next()) |pair| { 673 const trimmed = std.mem.trim(u8, pair, " \t"); 674 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 675 if (std.mem.eql(u8, trimmed[0..eq], name)) { 676 return trimmed[eq + 1 ..]; 677 } 678 } 679 } 680 return null; 681 } 682 683 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 684 var iter = std.mem.splitScalar(u8, body, '&'); 685 while (iter.next()) |pair| { 686 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 687 if (std.mem.eql(u8, pair[0..eq], key)) { 688 return try decodeFormValue(allocator, pair[eq + 1 ..]); 689 } 690 } 691 return null; 692 } 693 694 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 695 var out: std.ArrayList(u8) = .empty; 696 errdefer out.deinit(allocator); 697 var i: usize = 0; 698 while (i < encoded.len) : (i += 1) { 699 switch (encoded[i]) { 700 '+' => try out.append(allocator, ' '), 701 '%' => { 702 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 703 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 704 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 705 try out.append(allocator, hi * 16 + lo); 706 i += 2; 707 }, 708 else => try out.append(allocator, encoded[i]), 709 } 710 } 711 return try out.toOwnedSlice(allocator); 712 } 713 714 // disk-backed web session store. each login mints a random, opaque token 715 // (not the user's id) that is stored as a file named by the token hex, whose 716 // contents are the raw user_id bytes. authenticating a request is a lookup of 717 // the cookie's token; logout deletes the file, revoking the session. there is 718 // deliberately no expiry — a session lives until logout. 719 pub const SessionStore = struct { 720 io: std.Io, 721 dir: std.Io.Dir, 722 723 pub const token_hex_len = evt.event_id_size * 2; 724 725 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 726 try data_dir.createDirPath(io, "sessions"); 727 const dir = try data_dir.openDir(io, "sessions", .{}); 728 return .{ .io = io, .dir = dir }; 729 } 730 731 pub fn deinit(self: SessionStore) void { 732 self.dir.close(self.io); 733 } 734 735 // mint a new session for user_id, returning the token hex to set as the 736 // cookie value. 737 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 738 var token: [evt.event_id_size]u8 = undefined; 739 self.io.random(&token); 740 const token_hex = std.fmt.bytesToHex(token, .lower); 741 const file = try self.dir.createFile(self.io, &token_hex, .{}); 742 defer file.close(self.io); 743 try file.writeStreamingAll(self.io, user_id); 744 return token_hex; 745 } 746 747 // resolve a cookie's token to its user_id. returns false (logged out) for a 748 // missing, malformed, or unknown token. 749 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 750 if (!isToken(token_hex)) return false; 751 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 752 defer file.close(self.io); 753 var storage: [evt.event_id_size]u8 = undefined; 754 var file_reader = file.reader(self.io, &storage); 755 file_reader.interface.readSliceAll(out) catch return false; 756 return true; 757 } 758 759 // revoke a session. a no-op for a missing or malformed token. 760 pub fn remove(self: SessionStore, token_hex: []const u8) void { 761 if (!isToken(token_hex)) return; 762 self.dir.deleteFile(self.io, token_hex) catch {}; 763 } 764 765 // a token is exactly token_hex_len hex chars. validating before using the 766 // value as a path keeps attacker-supplied cookies from escaping the 767 // sessions dir (e.g. via "/" or ".." bytes). 768 fn isToken(token_hex: []const u8) bool { 769 if (token_hex.len != token_hex_len) return false; 770 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 771 return true; 772 } 773 }; 774