╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
333 // like logout, this is a bodyless POST, so close the connection rather than 334 // letting the keep-alive path try to discard a body that isn't framed. 335 try request.respond("", .{ 336 .status = .see_other, 337 .keep_alive = false, 338 .extra_headers = &.{ 339 .{ .name = "location", .value = ui.RoutablePage.url(.settings) }, 340 }, 341 }); 342 } 343 344 fn renderIndexHtml( 345 io: std.Io, 346 allocator: std.mem.Allocator, 347 admin_repo_path: []const u8, 348 session_data: ui.Session.Data, 349 ) ![]const u8 { 350 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 351 352 // open the admin repo to read live user/repo data. 353 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 354 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 355 defer repo.deinit(io, allocator); 356 var page_arena = std.heap.ArenaAllocator.init(allocator); 357 defer page_arena.deinit(); 358 359 var session = try ui.Session.init(&page_arena, &repo, session_data); 360 361 const snapshot: ui.Snapshot = .{ 362 .page = .{ .home = try .init(session.arena, session.haxy_moment orelse unreachable) }, 363 .session = session.data, 364 }; 365 var root = try ui.initRoot(allocator, &snapshot.page, &session); 366 defer root.deinit(allocator); 367 368 const content = try generateHtml(allocator, &root); 369 defer allocator.free(content); 370 const overlay = try generateOverlay(allocator, &root); 371 defer allocator.free(overlay); 372 373 // serialize the snapshot so the wasm side can parse it back without 374 // making a second request. base64-encoded so the json can be embedded 375 // safely inside the host html. 376 var json: std.Io.Writer.Allocating = .init(allocator); 377 defer json.deinit(); 378 try std.json.Stringify.value(snapshot, .{}, &json.writer); 379 380 const b64 = std.base64.standard.Encoder; 381 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 382 defer allocator.free(json_b64); 383 _ = b64.encode(json_b64, json.written()); 384 385 var out: std.ArrayList(u8) = .empty; 386 errdefer out.deinit(allocator); 387 { 388 var cursor: usize = 0; 389 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 390 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 391 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 392 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 393 }) |sub| { 394 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 395 try out.appendSlice(allocator, template[cursor..idx]); 396 try out.appendSlice(allocator, sub.replacement); 397 cursor = idx + sub.needle.len; 398 } 399 try out.appendSlice(allocator, template[cursor..]); 400 } 401 return try out.toOwnedSlice(allocator); 402 } 403 404 fn findEmbed(request_path: []const u8) ?Embed { 405 const path = if (std.mem.eql(u8, request_path, "/")) 406 "index.html" 407 else if (request_path.len > 1 and request_path[0] == '/') 408 request_path[1..] 409 else 410 return null; 411 412 for (embeds) |embed| { 413 if (std.mem.eql(u8, path, embed.path)) return embed; 414 } 415 return null; 416 } 417 418 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 419 err.print(fmt, args) catch return; 420 err.flush() catch {}; 421 } 422 423 // emits the TUI grid cells as static HTML 424 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 425 const grid = root.getGrid() orelse return error.MissingGrid; 426 const root_focus = root.getFocus(); 427 428 const Tag = union(enum) { 429 span, // clickable focusable cell 430 a: []const u8, // clickable focusable link 431 plain, // non-focusable, colored 432 433 const a_prefix = "a:"; 434 435 fn init(str: []const u8) @This() { 436 if (std.mem.startsWith(u8, str, a_prefix)) { 437 return .{ .a = str[a_prefix.len..] }; 438 } 439 return .span; 440 } 441 442 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 443 var id_buf: [32]u8 = undefined; 444 switch (self) { 445 .span => { 446 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 447 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 448 try out.appendSlice(alloc, "\""); 449 try out.appendSlice(alloc, style_attr); 450 try out.appendSlice(alloc, ">"); 451 }, 452 .a => |href| { 453 try out.appendSlice(alloc, "<a class=\"clickable\" data-focus-id=\""); 454 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 455 try out.appendSlice(alloc, "\" href=\""); 456 try appendEscapedHtml(alloc, out, href); 457 try out.appendSlice(alloc, "\""); 458 try out.appendSlice(alloc, style_attr); 459 try out.appendSlice(alloc, ">"); 460 }, 461 .plain => { 462 try out.appendSlice(alloc, "<span"); 463 try out.appendSlice(alloc, style_attr); 464 try out.appendSlice(alloc, ">"); 465 }, 466 } 467 } 468 469 fn closeTag(self: @This()) []const u8 { 470 return switch (self) { 471 .span, .plain => "</span>", 472 .a => "</a>", 473 }; 474 } 475 }; 476 477 var out: std.ArrayList(u8) = .empty; 478 errdefer out.deinit(allocator); 479 480 for (0..grid.size.height) |y| { 481 var cur_id: ?usize = null; 482 var cur_fg: ?Grid.Color = null; 483 var cur_bg: ?Grid.Color = null; 484 var open_tag: ?Tag = null; 485 var first = true; 486 for (0..grid.size.width) |x| { 487 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 488 const cell_id = cellFocusId(root_focus, x, y); 489 const fg = cell.style.fg; 490 const bg = cell.style.bg; 491 492 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 493 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 494 495 var new_tag: ?Tag = null; 496 if (cell_id) |id| { 497 if (root_focus.children.get(id)) |child| { 498 new_tag = switch (child.focus.kind) { 499 .custom => |custom| Tag.init(custom), 500 else => .span, 501 }; 502 } 503 } 504 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 505 506 if (new_tag) |t| { 507 var style_buf: [64]u8 = undefined; 508 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 509 } 510 511 open_tag = new_tag; 512 cur_id = cell_id; 513 cur_fg = fg; 514 cur_bg = bg; 515 first = false; 516 } 517 518 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 519 } 520 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 521 try out.append(allocator, '\n'); 522 } 523 524 return try out.toOwnedSlice(allocator); 525 } 526 527 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 528 // widget tree, each wrapping the text inputs and submit button inside it, 529 // positioned absolutely over the matching grid cells. 530 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 531 const root_focus = root.getFocus(); 532 533 var out: std.ArrayList(u8) = .empty; 534 errdefer out.deinit(allocator); 535 536 const form_prefix = "form:"; 537 538 // Focus.children is an AutoArrayHashMap that preserves insertion order, 539 // which matches the order widgets were added in code 540 var iter = root_focus.children.iterator(); 541 while (iter.next()) |entry| { 542 const child = entry.value_ptr.*; 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