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