╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1295 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1296 var id_buf: [32]u8 = undefined; 1297 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1298 if (ti.options.name.len > 0) { 1299 try out.appendSlice(allocator, "\" name=\""); 1300 try appendEscapedHtml(allocator, &out, ti.options.name); 1301 } 1302 // like the input above, only a page-constant initial value 1303 // inside: the browser tracks the live value and the 1304 // overlay diff must stay stable across keystrokes 1305 try out.appendSlice(allocator, "\" style=\"left:"); 1306 var pos_buf: [128]u8 = undefined; 1307 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 })); 1308 // textarea discards the first newline immediately following 1309 // its start tag, so add one of our own so text that begins 1310 // with a newline doesn't lose it 1311 try out.appendSlice(allocator, "\">\n"); 1312 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1313 try out.appendSlice(allocator, "</textarea>"); 1314 }, 1315 .custom => |custom| { 1316 if (std.mem.eql(u8, "submit", custom)) { 1317 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1318 var id_buf: [32]u8 = undefined; 1319 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1320 try out.appendSlice(allocator, "\" style=\"left:"); 1321 var pos_buf: [128]u8 = undefined; 1322 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1323 try out.appendSlice(allocator, "\"></button>"); 1324 } 1325 }, 1326 else => {}, 1327 } 1328 } 1329 1330 try out.appendSlice(allocator, "</form>"); 1331 } 1332 1333 return try out.toOwnedSlice(allocator); 1334 } 1335 1336 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1337 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1338 return b == null; 1339 } 1340 1341 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1342 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1343 // empty slice when neither is set. 1344 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1345 if (fg == null and bg == null) return buf[0..0]; 1346 const prefix = " style=\""; 1347 @memcpy(buf[0..prefix.len], prefix); 1348 var i: usize = prefix.len; 1349 if (fg) |c| { 1350 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]; 1351 i += s.len; 1352 } 1353 if (bg) |c| { 1354 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]; 1355 i += s.len; 1356 } 1357 buf[i] = '"'; 1358 i += 1; 1359 return buf[0..i]; 1360 } 1361 1362 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1363 for (input) |ch| { 1364 switch (ch) { 1365 '&' => try out.appendSlice(allocator, "&amp;"), 1366 '<' => try out.appendSlice(allocator, "&lt;"), 1367 '>' => try out.appendSlice(allocator, "&gt;"), 1368 '"' => try out.appendSlice(allocator, "&quot;"), 1369 '\'' => try out.appendSlice(allocator, "&#39;"), 1370 else => try out.append(allocator, ch), 1371 } 1372 } 1373 } 1374 1375 // --- helpers -------------------------------------------------------------- 1376 1377 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1378 var iter = request.iterateHeaders(); 1379 while (iter.next()) |header| { 1380 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1381 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1382 while (pairs.next()) |pair| { 1383 const trimmed = std.mem.trim(u8, pair, " \t"); 1384 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1385 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1386 return trimmed[eq + 1 ..]; 1387 } 1388 } 1389 } 1390 return null; 1391 } 1392 1393 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1394 var iter = std.mem.splitScalar(u8, body, '&'); 1395 while (iter.next()) |pair| { 1396 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1397 if (std.mem.eql(u8, pair[0..eq], key)) { 1398 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1399 } 1400 } 1401 return null; 1402 } 1403 1404 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1405 var out: std.ArrayList(u8) = .empty; 1406 errdefer out.deinit(allocator); 1407 var i: usize = 0; 1408 while (i < encoded.len) : (i += 1) { 1409 switch (encoded[i]) { 1410 '+' => try out.append(allocator, ' '), 1411 '%' => { 1412 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1413 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1414 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1415 try out.append(allocator, hi * 16 + lo); 1416 i += 2; 1417 }, 1418 else => try out.append(allocator, encoded[i]), 1419 } 1420 } 1421 return try out.toOwnedSlice(allocator); 1422 } 1423 1424 // disk-backed web session store. each login mints a random, opaque token 1425 // (not the user's id) that is stored as a file named by the token hex, whose 1426 // contents are the raw user_id bytes. authenticating a request is a lookup of 1427 // the cookie's token; logout deletes the file, revoking the session. there is 1428 // deliberately no expiry — a session lives until logout. 1429 pub const SessionStore = struct { 1430 io: std.Io, 1431 dir: std.Io.Dir, 1432 1433 pub const token_hex_len = evt.event_id_size * 2; 1434 1435 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1436 try data_dir.createDirPath(io, "sessions"); 1437 const dir = try data_dir.openDir(io, "sessions", .{}); 1438 return .{ .io = io, .dir = dir }; 1439 } 1440 1441 pub fn deinit(self: SessionStore) void { 1442 self.dir.close(self.io); 1443 } 1444 1445 // mint a new session for user_id, returning the token hex to set as the 1446 // cookie value. 1447 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1448 var token: [evt.event_id_size]u8 = undefined; 1449 self.io.random(&token); 1450 const token_hex = std.fmt.bytesToHex(token, .lower); 1451 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1452 defer file.close(self.io); 1453 try file.writeStreamingAll(self.io, user_id); 1454 return token_hex; 1455 } 1456 1457 // resolve a cookie's token to its user_id. returns false (logged out) for a 1458 // missing, malformed, or unknown token. 1459 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1460 if (!isToken(token_hex)) return false; 1461 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1462 defer file.close(self.io); 1463 var storage: [evt.event_id_size]u8 = undefined; 1464 var file_reader = file.reader(self.io, &storage); 1465 file_reader.interface.readSliceAll(out) catch return false; 1466 return true; 1467 } 1468 1469 // revoke a session. a no-op for a missing or malformed token. 1470 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1471 if (!isToken(token_hex)) return; 1472 self.dir.deleteFile(self.io, token_hex) catch {}; 1473 } 1474 1475 // leave `token_hex`'s session for the next visitor arriving without one. 1476 // only the `try` fixture writes one, and only a debug build honors it. the 1477 // name isn't token-shaped, so it can't collide with a session file. 1478 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1479 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1480 defer file.close(self.io); 1481 try file.writeStreamingAll(self.io, token_hex); 1482 } 1483 1484 // claim the offered session, if one is there. the delete picks the winner 1485 // of a race, so the offer is only ever taken once. a release build never 1486 // looks, because that would be an extra syscall for every GET request. 1487 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1488 if (builtin.mode != .Debug) return false; 1489 { 1490 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1491 defer file.close(self.io); 1492 var storage: [token_hex_len]u8 = undefined; 1493 var file_reader = file.reader(self.io, &storage); 1494 file_reader.interface.readSliceAll(out) catch return false; 1495 } 1496 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1497 return true; 1498 } 1499 1500 const auto_login_name = "auto-login"; 1501 1502 // a token is exactly token_hex_len hex chars. validating before using the 1503 // value as a path keeps attacker-supplied cookies from escaping the 1504 // sessions dir (e.g. via "/" or ".." bytes). 1505 fn isToken(token_hex: []const u8) bool { 1506 if (token_hex.len != token_hex_len) return false; 1507 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1508 return true; 1509 } 1510 }; 1511