╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1530 1531 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1532 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1533 // empty slice when neither is set. 1534 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1535 if (fg == null and bg == null) return buf[0..0]; 1536 const prefix = " style=\""; 1537 @memcpy(buf[0..prefix.len], prefix); 1538 var i: usize = prefix.len; 1539 if (fg) |c| { 1540 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]; 1541 i += s.len; 1542 } 1543 if (bg) |c| { 1544 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]; 1545 i += s.len; 1546 } 1547 buf[i] = '"'; 1548 i += 1; 1549 return buf[0..i]; 1550 } 1551 1552 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1553 for (input) |ch| { 1554 switch (ch) { 1555 '&' => try out.appendSlice(allocator, "&amp;"), 1556 '<' => try out.appendSlice(allocator, "&lt;"), 1557 '>' => try out.appendSlice(allocator, "&gt;"), 1558 '"' => try out.appendSlice(allocator, "&quot;"), 1559 '\'' => try out.appendSlice(allocator, "&#39;"), 1560 else => try out.append(allocator, ch), 1561 } 1562 } 1563 } 1564 1565 // --- helpers -------------------------------------------------------------- 1566 1567 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1568 var iter = request.iterateHeaders(); 1569 while (iter.next()) |header| { 1570 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1571 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1572 while (pairs.next()) |pair| { 1573 const trimmed = std.mem.trim(u8, pair, " \t"); 1574 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1575 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1576 return trimmed[eq + 1 ..]; 1577 } 1578 } 1579 } 1580 return null; 1581 } 1582 1583 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1584 var iter = std.mem.splitScalar(u8, body, '&'); 1585 while (iter.next()) |pair| { 1586 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1587 if (std.mem.eql(u8, pair[0..eq], key)) { 1588 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1589 } 1590 } 1591 return null; 1592 } 1593 1594 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1595 var out: std.ArrayList(u8) = .empty; 1596 errdefer out.deinit(allocator); 1597 var i: usize = 0; 1598 while (i < encoded.len) : (i += 1) { 1599 switch (encoded[i]) { 1600 '+' => try out.append(allocator, ' '), 1601 '%' => { 1602 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1603 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1604 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1605 try out.append(allocator, hi * 16 + lo); 1606 i += 2; 1607 }, 1608 else => try out.append(allocator, encoded[i]), 1609 } 1610 } 1611 return try out.toOwnedSlice(allocator); 1612 } 1613 1614 // disk-backed web session store. each login mints a random, opaque token 1615 // (not the user's id) that is stored as a file named by the token hex, whose 1616 // contents are the raw user_id bytes. authenticating a request is a lookup of 1617 // the cookie's token; logout deletes the file, revoking the session. there is 1618 // deliberately no expiry — a session lives until logout. 1619 pub const SessionStore = struct { 1620 io: std.Io, 1621 dir: std.Io.Dir, 1622 1623 pub const token_hex_len = evt.event_id_size * 2; 1624 1625 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1626 try data_dir.createDirPath(io, "sessions"); 1627 const dir = try data_dir.openDir(io, "sessions", .{}); 1628 return .{ .io = io, .dir = dir }; 1629 } 1630 1631 pub fn deinit(self: SessionStore) void { 1632 self.dir.close(self.io); 1633 } 1634 1635 // mint a new session for user_id, returning the token hex to set as the 1636 // cookie value. 1637 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1638 var token: [evt.event_id_size]u8 = undefined; 1639 self.io.random(&token); 1640 const token_hex = std.fmt.bytesToHex(token, .lower); 1641 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1642 defer file.close(self.io); 1643 try file.writeStreamingAll(self.io, user_id); 1644 return token_hex; 1645 } 1646 1647 // resolve a cookie's token to its user_id. returns false (logged out) for a 1648 // missing, malformed, or unknown token. 1649 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1650 if (!isToken(token_hex)) return false; 1651 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1652 defer file.close(self.io); 1653 var storage: [evt.event_id_size]u8 = undefined; 1654 var file_reader = file.reader(self.io, &storage); 1655 file_reader.interface.readSliceAll(out) catch return false; 1656 return true; 1657 } 1658 1659 // revoke a session. a no-op for a missing or malformed token. 1660 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1661 if (!isToken(token_hex)) return; 1662 self.dir.deleteFile(self.io, token_hex) catch {}; 1663 } 1664 1665 // leave `token_hex`'s session for the next visitor arriving without one. 1666 // only the `try` fixture writes one, and only a debug build honors it. the 1667 // name isn't token-shaped, so it can't collide with a session file. 1668 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1669 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1670 defer file.close(self.io); 1671 try file.writeStreamingAll(self.io, token_hex); 1672 } 1673 1674 // claim the offered session, if one is there. the delete picks the winner 1675 // of a race, so the offer is only ever taken once. a release build never 1676 // looks, because that would be an extra syscall for every GET request. 1677 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1678 if (builtin.mode != .Debug) return false; 1679 { 1680 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1681 defer file.close(self.io); 1682 var storage: [token_hex_len]u8 = undefined; 1683 var file_reader = file.reader(self.io, &storage); 1684 file_reader.interface.readSliceAll(out) catch return false; 1685 } 1686 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1687 return true; 1688 } 1689 1690 const auto_login_name = "auto-login"; 1691 1692 // a token is exactly token_hex_len hex chars. validating before using the 1693 // value as a path keeps attacker-supplied cookies from escaping the 1694 // sessions dir (e.g. via "/" or ".." bytes). 1695 fn isToken(token_hex: []const u8) bool { 1696 if (token_hex.len != token_hex_len) return false; 1697 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1698 return true; 1699 } 1700 }; 1701