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