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