Add owner-controlled personal room mailboxes and WiFi management
This commit is contained in:
1 parent
5165b6f490
commit
2c1c2c8e99
24 files changed
+3607
-24
No files matched your search
@@ -0,0 +1,443 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "RoomMailStore.h"
|
||||
|
||||
namespace mesh {
|
||||
|
||||
static constexpr uint8_t ROOM_MAIL_REQUEST_SUBTYPE = 0x0b;
|
||||
static constexpr size_t ROOM_MAIL_PROTOCOL_READ_CHUNK = 128;
|
||||
static constexpr size_t ROOM_MAIL_MAX_COMMAND_LENGTH = 600;
|
||||
|
||||
// Requests follow the existing encrypted room request tag. The trusted caller
|
||||
// supplies the authenticated full sender key, send permission and durable nonce;
|
||||
// requests never supply an inbox owner. All integers below are little-endian.
|
||||
// Every response starts [0x0b, operation, status]. Status values follow
|
||||
// RoomMailResult: 0 success, 1 invalid, 2 unavailable, 3 write failure,
|
||||
// 4 not found, 5 stale revision, 6 forbidden, 7 full, 8 successful duplicate,
|
||||
// 9 nonce/body mismatch. A short invalid response may contain only this header.
|
||||
//
|
||||
// op request after [0x0b, op] response after common header
|
||||
// 0 expected revision u32, allow cursor u8 revision u32, mode u8,
|
||||
// mailbox-only u8, allow-count u8,
|
||||
// start u8, next u8, queued u8,
|
||||
// zero or more full 32-byte keys
|
||||
// 1 expected revision u32, cursor u8 revision u32, total u8, start u8,
|
||||
// next u8, copied u8, entries:
|
||||
// id u32, sender key[32], length u16
|
||||
// 2 message id u32, offset u16 id u32, offset u16, total u16,
|
||||
// copied u8, sender key[32], bytes
|
||||
// 3 recipient key[32], body length u16, message id u32
|
||||
// complete UTF-8 body bytes
|
||||
// 4 message id u32 (acknowledge receipt) message id u32
|
||||
// 5 message id u32 (delete) message id u32
|
||||
// 6 expected revision u32, allowed key[32] new revision u32
|
||||
// 7 expected revision u32, denied key[32] new revision u32
|
||||
// 8 expected revision u32, mode u8 new revision u32
|
||||
// 9 expected revision u32, mailbox-only u8 new revision u32
|
||||
//
|
||||
// Mode values: 0 closed, 1 public, 2 private (allow list). All queue entries are
|
||||
// unacknowledged; ACK durably removes a message, preserving its retry receipt.
|
||||
// Index responses contain at most two whole entries. next==255 means complete.
|
||||
// Start an inbox index at revision=0,cursor=0, then retain its returned revision.
|
||||
// Settings are private to this owner; their index uses the same revision rules.
|
||||
// Policy changes must echo the current revision, including 0 for a new inbox.
|
||||
// Message IDs identify immutable content; reads can resume by offset. Empty
|
||||
// inboxes are closed by default and reads/checks never provision an inbox.
|
||||
// Every mutating operation checks its complete response fits BEFORE writing.
|
||||
// Bodies are not fragmented on upload: each send must fit its request route.
|
||||
// Decrypted room packets include AES zero padding. Logical request lengths are
|
||||
// determined by the operation (and send's declared body length); only zero bytes
|
||||
// may follow the logical request. Padding never becomes part of a stored body.
|
||||
|
||||
namespace room_mail_protocol_detail {
|
||||
|
||||
inline uint16_t get16(const uint8_t* bytes) {
|
||||
return uint16_t(bytes[0]) | (uint16_t(bytes[1]) << 8);
|
||||
}
|
||||
inline uint32_t get32(const uint8_t* bytes) {
|
||||
return uint32_t(bytes[0]) | (uint32_t(bytes[1]) << 8)
|
||||
| (uint32_t(bytes[2]) << 16) | (uint32_t(bytes[3]) << 24);
|
||||
}
|
||||
inline void put16(uint8_t* bytes, uint16_t value) {
|
||||
bytes[0] = uint8_t(value); bytes[1] = uint8_t(value >> 8);
|
||||
}
|
||||
inline void put32(uint8_t* bytes, uint32_t value) {
|
||||
for (uint8_t i = 0; i < 4; ++i) bytes[i] = uint8_t(value >> (8 * i));
|
||||
}
|
||||
inline uint8_t status(RoomMailResult result) {
|
||||
switch (result) {
|
||||
case RoomMailResult::Success: return 0;
|
||||
case RoomMailResult::Invalid: return 1;
|
||||
case RoomMailResult::Unavailable: return 2;
|
||||
case RoomMailResult::WriteFailure: return 3;
|
||||
case RoomMailResult::NotFound: return 4;
|
||||
case RoomMailResult::StaleVersion: return 5;
|
||||
case RoomMailResult::Forbidden: return 6;
|
||||
case RoomMailResult::Full: return 7;
|
||||
case RoomMailResult::Duplicate: return 8;
|
||||
case RoomMailResult::Mismatch: return 9;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
inline size_t header(uint8_t operation, RoomMailResult result,
|
||||
uint8_t* reply, size_t capacity) {
|
||||
if (!reply || capacity < 3) return 0;
|
||||
reply[0] = ROOM_MAIL_REQUEST_SUBTYPE; reply[1] = operation;
|
||||
reply[2] = status(result); return 3;
|
||||
}
|
||||
inline bool successful(RoomMailResult result) {
|
||||
return result == RoomMailResult::Success || result == RoomMailResult::Duplicate;
|
||||
}
|
||||
inline bool validKey(const uint8_t* key) {
|
||||
if (!key) return false;
|
||||
uint8_t nonzero = 0;
|
||||
for (size_t i = 0; i < 32; ++i) nonzero |= key[i];
|
||||
return nonzero != 0;
|
||||
}
|
||||
inline bool paddedLength(const uint8_t* payload, size_t length, size_t logical) {
|
||||
if (!payload || length < logical) return false;
|
||||
for (size_t i = logical; i < length; ++i) if (payload[i] != 0) return false;
|
||||
return true;
|
||||
}
|
||||
inline bool key(const char* text, uint8_t (&out)[32]) {
|
||||
if (!text || strlen(text) != 64) return false;
|
||||
uint8_t parsed[32];
|
||||
for (size_t i = 0; i < 32; ++i) {
|
||||
unsigned value = 0;
|
||||
for (size_t j = 0; j < 2; ++j) {
|
||||
const char c = text[i * 2 + j]; unsigned digit;
|
||||
if (c >= '0' && c <= '9') digit = unsigned(c - '0');
|
||||
else if (c >= 'a' && c <= 'f') digit = unsigned(c - 'a' + 10);
|
||||
else if (c >= 'A' && c <= 'F') digit = unsigned(c - 'A' + 10);
|
||||
else return false;
|
||||
value = (value << 4) | digit;
|
||||
}
|
||||
parsed[i] = uint8_t(value);
|
||||
}
|
||||
if (!validKey(parsed)) return false;
|
||||
memcpy(out, parsed, 32); return true;
|
||||
}
|
||||
inline void hex(const uint8_t* bytes, char (&out)[65]) {
|
||||
static const char alphabet[] = "0123456789abcdef";
|
||||
for (size_t i = 0; i < 32; ++i) {
|
||||
out[i * 2] = alphabet[bytes[i] >> 4]; out[i * 2 + 1] = alphabet[bytes[i] & 15];
|
||||
}
|
||||
out[64] = 0;
|
||||
}
|
||||
inline const char* modeName(RoomMailMode mode) {
|
||||
return mode == RoomMailMode::Public ? "public" : mode == RoomMailMode::Private ? "private" : "closed";
|
||||
}
|
||||
inline const char* spaces(const char* cursor) { while (*cursor == ' ') ++cursor; return cursor; }
|
||||
inline bool prefix(const char* command, const char* expected) {
|
||||
const size_t length = strlen(expected);
|
||||
return strncmp(command, expected, length) == 0 && (command[length] == 0 || command[length] == ' ');
|
||||
}
|
||||
inline bool number(const char*& cursor, uint32_t maximum, uint32_t& value) {
|
||||
cursor = spaces(cursor); value = 0;
|
||||
if (*cursor < '0' || *cursor > '9') return false;
|
||||
do {
|
||||
const uint8_t digit = uint8_t(*cursor++ - '0');
|
||||
if (value > maximum / 10 || (value == maximum / 10 && digit > maximum % 10)) return false;
|
||||
value = value * 10 + digit;
|
||||
} while (*cursor >= '0' && *cursor <= '9');
|
||||
return *cursor == 0 || *cursor == ' ';
|
||||
}
|
||||
inline size_t utf8Prefix(const uint8_t* text, size_t length) {
|
||||
size_t cursor = 0;
|
||||
while (cursor < length) {
|
||||
const uint8_t first = text[cursor];
|
||||
const size_t width = first < 0x80 ? 1 : first < 0xe0 ? 2 : first < 0xf0 ? 3 : 4;
|
||||
if (width > length - cursor) break;
|
||||
cursor += width;
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
inline void textResult(char* reply, size_t capacity, RoomMailResult result,
|
||||
uint32_t id = 0, bool message = false) {
|
||||
if (!reply || !capacity) return;
|
||||
if (successful(result)) {
|
||||
if (message) snprintf(reply, capacity, "OK id=%lu%s", (unsigned long)id,
|
||||
result == RoomMailResult::Duplicate ? " duplicate" : "");
|
||||
else snprintf(reply, capacity, "OK");
|
||||
return;
|
||||
}
|
||||
const char* error = "invalid";
|
||||
switch (result) {
|
||||
case RoomMailResult::Unavailable: error = "unavailable"; break;
|
||||
case RoomMailResult::WriteFailure: error = "write failure"; break;
|
||||
case RoomMailResult::NotFound: error = "not found"; break;
|
||||
case RoomMailResult::StaleVersion: error = "stale revision"; break;
|
||||
case RoomMailResult::Forbidden: error = "permission denied"; break;
|
||||
case RoomMailResult::Full: error = "mailbox full"; break;
|
||||
case RoomMailResult::Mismatch: error = "request changed"; break;
|
||||
default: break;
|
||||
}
|
||||
snprintf(reply, capacity, "Error %s", error);
|
||||
}
|
||||
template <typename Filesystem>
|
||||
RoomMailResult ownStatus(Filesystem* fs, const uint8_t* owner, RoomMailStatus& value) {
|
||||
const RoomMailResult result = getRoomMailStatus(fs, owner, value);
|
||||
return result == RoomMailResult::NotFound ? RoomMailResult::Success : result;
|
||||
}
|
||||
inline RoomMailResult editSettings(RoomMailSettings& settings, uint8_t operation,
|
||||
const uint8_t* value) {
|
||||
if (operation == 8) {
|
||||
if (*value > 2) return RoomMailResult::Invalid;
|
||||
settings.mode = static_cast<RoomMailMode>(*value); return RoomMailResult::Success;
|
||||
}
|
||||
if (operation == 9) {
|
||||
if (*value > 1) return RoomMailResult::Invalid;
|
||||
settings.mailbox_only = *value != 0; return RoomMailResult::Success;
|
||||
}
|
||||
if (!validKey(value)) return RoomMailResult::Invalid;
|
||||
uint8_t position = 0;
|
||||
while (position < settings.allowed_count && memcmp(settings.allowed[position], value, 32) != 0) ++position;
|
||||
if (operation == 6) {
|
||||
if (position < settings.allowed_count) return RoomMailResult::Success;
|
||||
if (settings.allowed_count >= 8) return RoomMailResult::Full;
|
||||
memcpy(settings.allowed[settings.allowed_count++], value, 32);
|
||||
} else {
|
||||
if (position == settings.allowed_count) return RoomMailResult::Success;
|
||||
for (uint8_t i = position; i + 1 < settings.allowed_count; ++i)
|
||||
memcpy(settings.allowed[i], settings.allowed[i + 1], 32);
|
||||
memset(settings.allowed[--settings.allowed_count], 0, 32);
|
||||
}
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
} // namespace room_mail_protocol_detail
|
||||
|
||||
template <typename Filesystem>
|
||||
size_t handleRoomMailRequest(Filesystem* fs, const uint8_t* owner, bool can_send,
|
||||
uint64_t request_id, const uint8_t* payload, size_t length,
|
||||
uint8_t* reply, size_t capacity, uint32_t created = 0) {
|
||||
using namespace room_mail_protocol_detail;
|
||||
const uint8_t operation = payload && length > 1 ? payload[1] : 255;
|
||||
if (!payload || length < 2 || payload[0] != ROOM_MAIL_REQUEST_SUBTYPE || operation > 9
|
||||
|| !validKey(owner) || !reply || capacity < 3)
|
||||
return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
RoomMailResult result = RoomMailResult::Invalid;
|
||||
if (operation == 0 || operation == 1) {
|
||||
if (!paddedLength(payload, length, 7) || capacity < (operation == 0 ? 13U : 11U))
|
||||
return header(operation, result, reply, capacity);
|
||||
RoomMailStatus state;
|
||||
result = ownStatus(fs, owner, state);
|
||||
if (result != RoomMailResult::Success) return header(operation, result, reply, capacity);
|
||||
const uint32_t expected = get32(payload + 2); const uint8_t start = payload[6];
|
||||
if ((expected && expected != state.revision) || (!expected && start))
|
||||
return header(operation, RoomMailResult::StaleVersion, reply, capacity);
|
||||
header(operation, result, reply, capacity); put32(reply + 3, state.revision);
|
||||
if (operation == 0) {
|
||||
if (start > state.settings.allowed_count) return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
reply[7] = static_cast<uint8_t>(state.settings.mode); reply[8] = state.settings.mailbox_only ? 1 : 0;
|
||||
reply[9] = state.settings.allowed_count; reply[10] = start; reply[12] = state.count;
|
||||
size_t used = 13; uint8_t next = start;
|
||||
while (next < state.settings.allowed_count && capacity - used >= 32) {
|
||||
memcpy(reply + used, state.settings.allowed[next++], 32); used += 32;
|
||||
}
|
||||
if (next == start && next < state.settings.allowed_count)
|
||||
return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
reply[11] = next < state.settings.allowed_count ? next : 255; return used;
|
||||
}
|
||||
if (start > state.count) return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
const size_t room = (capacity - 11) / 38;
|
||||
if (!room && start < state.count) return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
RoomMailMessage messages[2]; size_t copied = 0;
|
||||
if (state.count) result = listRoomMail(fs, owner, state.revision, start, messages, room < 2 ? room : 2, copied);
|
||||
if (result != RoomMailResult::Success) return header(operation, result, reply, capacity);
|
||||
reply[7] = state.count; reply[8] = start; reply[9] = start + copied < state.count ? uint8_t(start + copied) : 255;
|
||||
reply[10] = uint8_t(copied); size_t used = 11;
|
||||
for (size_t i = 0; i < copied; ++i) {
|
||||
put32(reply + used, messages[i].id); memcpy(reply + used + 4, messages[i].sender, 32);
|
||||
put16(reply + used + 36, messages[i].length); used += 38;
|
||||
}
|
||||
return used;
|
||||
}
|
||||
if (operation == 2) {
|
||||
if (!paddedLength(payload, length, 8) || capacity < 44) return header(operation, result, reply, capacity);
|
||||
const uint32_t id = get32(payload + 2); const uint16_t offset = get16(payload + 6);
|
||||
const size_t available = capacity - 44;
|
||||
uint8_t bytes[ROOM_MAIL_PROTOCOL_READ_CHUNK]; size_t copied = 0; RoomMailMessage message;
|
||||
// A zero-byte EOF still requires a nonzero read capacity in the store.
|
||||
result = readRoomMail(fs, owner, id, offset, bytes,
|
||||
available ? (available < sizeof(bytes) ? available : sizeof(bytes)) : 1, copied, message);
|
||||
if (result != RoomMailResult::Success) return header(operation, result, reply, capacity);
|
||||
if (copied > available) return header(operation, RoomMailResult::Invalid, reply, capacity);
|
||||
header(operation, result, reply, capacity); put32(reply + 3, id); put16(reply + 7, offset);
|
||||
put16(reply + 9, message.length); reply[11] = uint8_t(copied); memcpy(reply + 12, message.sender, 32);
|
||||
if (copied) memcpy(reply + 44, bytes, copied);
|
||||
return 44 + copied;
|
||||
}
|
||||
if (capacity < 7) return header(operation, result, reply, capacity);
|
||||
uint32_t id = 0;
|
||||
if (operation == 3) {
|
||||
if (length < 36 || !validKey(payload + 2))
|
||||
return header(operation, result, reply, capacity);
|
||||
const size_t body_length = get16(payload + 34);
|
||||
if (!paddedLength(payload, length, 36 + body_length)) return header(operation, result, reply, capacity);
|
||||
result = can_send ? sendRoomMail(fs, owner, payload + 2, request_id,
|
||||
reinterpret_cast<const char*>(payload + 36), body_length, id, created) : RoomMailResult::Forbidden;
|
||||
} else if (operation == 4 || operation == 5) {
|
||||
if (!paddedLength(payload, length, 6) || !(id = get32(payload + 2))) return header(operation, result, reply, capacity);
|
||||
result = operation == 4 ? acknowledgeRoomMail(fs, owner, id) : deleteRoomMail(fs, owner, id);
|
||||
} else {
|
||||
if (!paddedLength(payload, length, operation <= 7 ? 38U : 7U)) return header(operation, result, reply, capacity);
|
||||
RoomMailStatus state; result = ownStatus(fs, owner, state);
|
||||
if (result != RoomMailResult::Success) return header(operation, result, reply, capacity);
|
||||
if (get32(payload + 2) != state.revision) return header(operation, RoomMailResult::StaleVersion, reply, capacity);
|
||||
result = editSettings(state.settings, operation, payload + 6);
|
||||
if (result == RoomMailResult::Success) result = saveRoomMailSettings(fs, owner, state.settings, state.revision);
|
||||
if (result == RoomMailResult::Success) {
|
||||
result = ownStatus(fs, owner, state); id = state.revision;
|
||||
}
|
||||
}
|
||||
header(operation, result, reply, capacity); put32(reply + 3, id); return 7;
|
||||
}
|
||||
|
||||
// The caller strips an optional ! prefix for the stock-app !mail fallback.
|
||||
// Only the trusted owner is used for settings/list/read/ack/delete. Ordinary
|
||||
// authenticated readers may manage their own inbox; sends additionally require
|
||||
// can_send. CLI reads return complete UTF-8 characters with the next byte offset.
|
||||
// An offset in the middle of a character is rejected. Mutating replies
|
||||
// require capacity >=32 so their ID/confirmation cannot be silently truncated.
|
||||
// CLI next==total (or allowed count) completes an index. A short route may show
|
||||
// a sender key prefix followed by ".."; only complete keys authorize/send mail.
|
||||
template <typename Filesystem>
|
||||
bool handleRoomMailCommand(Filesystem* fs, const uint8_t* owner, bool can_send,
|
||||
uint64_t request_id, const char* command,
|
||||
char* reply, size_t capacity, uint32_t created = 0) {
|
||||
using namespace room_mail_protocol_detail;
|
||||
if (!command || !prefix(command, "mail")) return false;
|
||||
if (!reply || !capacity) return true;
|
||||
reply[0] = 0;
|
||||
size_t length = 0;
|
||||
while (length <= ROOM_MAIL_MAX_COMMAND_LENGTH && command[length]) ++length;
|
||||
if (length > ROOM_MAIL_MAX_COMMAND_LENGTH || !validKey(owner)) {
|
||||
textResult(reply, capacity, RoomMailResult::Invalid); return true;
|
||||
}
|
||||
const char* body = spaces(command + 4);
|
||||
const bool settings = prefix(body, "settings") || prefix(body, "check");
|
||||
const bool inbox = prefix(body, "inbox");
|
||||
const bool list = prefix(body, "list") || inbox, read = prefix(body, "read");
|
||||
const bool send = prefix(body, "send"), ack = prefix(body, "ack"), del = prefix(body, "delete");
|
||||
const bool mode = prefix(body, "mode"), delivery = prefix(body, "delivery");
|
||||
const bool allow = prefix(body, "allow"), deny = prefix(body, "deny");
|
||||
if (!(settings || list || read || send || ack || del || mode || delivery || allow || deny)) {
|
||||
textResult(reply, capacity, RoomMailResult::Invalid); return true;
|
||||
}
|
||||
if (!(settings || list || read) && capacity < 32) {
|
||||
textResult(reply, capacity, RoomMailResult::Invalid); return true;
|
||||
}
|
||||
RoomMailResult result = RoomMailResult::Invalid;
|
||||
if (send) {
|
||||
const char* cursor = spaces(body + 4); const char* end = strchr(cursor, ' ');
|
||||
uint8_t recipient[32]; char text_key[65];
|
||||
if (!end || end - cursor != 64) { textResult(reply, capacity, result); return true; }
|
||||
memcpy(text_key, cursor, 64); text_key[64] = 0;
|
||||
const char* text = spaces(end);
|
||||
uint32_t id = 0;
|
||||
if (key(text_key, recipient) && *text)
|
||||
result = can_send ? sendRoomMail(fs, owner, recipient, request_id, text, strlen(text), id, created) : RoomMailResult::Forbidden;
|
||||
textResult(reply, capacity, result, id, true); return true;
|
||||
}
|
||||
if (ack || del || read) {
|
||||
const char* cursor = body + (ack ? 3 : del ? 6 : 4); uint32_t id, offset = 0;
|
||||
if (!number(cursor, UINT32_MAX, id) || id == 0
|
||||
|| (read && *spaces(cursor) && !number(cursor, 512, offset)) || *spaces(cursor)) {
|
||||
textResult(reply, capacity, result); return true;
|
||||
}
|
||||
if (!read) {
|
||||
result = ack ? acknowledgeRoomMail(fs, owner, id) : deleteRoomMail(fs, owner, id);
|
||||
textResult(reply, capacity, result, id, true); return true;
|
||||
}
|
||||
RoomMailMessage message; uint8_t bytes[ROOM_MAIL_PROTOCOL_READ_CHUNK]; size_t copied = 0;
|
||||
result = readRoomMail(fs, owner, id, offset, bytes, sizeof(bytes), copied, message);
|
||||
if (result != RoomMailResult::Success) { textResult(reply, capacity, result); return true; }
|
||||
if (copied && (bytes[0] & 0xc0) == 0x80) {
|
||||
snprintf(reply, capacity, "Error offset inside UTF-8 character"); return true;
|
||||
}
|
||||
size_t count = utf8Prefix(bytes, copied); int prefix_length;
|
||||
do {
|
||||
prefix_length = snprintf(reply, capacity, "id=%lu off=%lu next=%lu total=%u text=",
|
||||
(unsigned long)id, (unsigned long)offset, (unsigned long)(offset + count), unsigned(message.length));
|
||||
if (prefix_length >= 0 && size_t(prefix_length) + count < capacity) break;
|
||||
if (!count) { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
count = utf8Prefix(bytes, count - 1);
|
||||
} while (true);
|
||||
if (!count && copied) { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
memcpy(reply + prefix_length, bytes, count); reply[prefix_length + count] = 0; return true;
|
||||
}
|
||||
RoomMailStatus state; result = ownStatus(fs, owner, state);
|
||||
if (result != RoomMailResult::Success) { textResult(reply, capacity, result); return true; }
|
||||
if (settings || list) {
|
||||
const char* cursor = body + (settings ? (prefix(body, "check") ? 5 : 8) : inbox ? 5 : 4); uint32_t start = 0;
|
||||
const uint8_t total = settings ? state.settings.allowed_count : state.count;
|
||||
if ((*spaces(cursor) && !number(cursor, total, start)) || *spaces(cursor)) {
|
||||
textResult(reply, capacity, RoomMailResult::Invalid); return true;
|
||||
}
|
||||
char entries[160] = {}; size_t used = 0; uint32_t next = start; int prefix_length;
|
||||
RoomMailMessage messages[2]; size_t copied = 0;
|
||||
if (list && state.count) result = listRoomMail(fs, owner, state.revision, start, messages, 2, copied);
|
||||
if (result != RoomMailResult::Success) { textResult(reply, capacity, result); return true; }
|
||||
while (next < total && (settings || next - start < copied)) {
|
||||
char full_key[65]; char entry[90];
|
||||
if (settings) { hex(state.settings.allowed[next], full_key); snprintf(entry, sizeof(entry), " %s", full_key); }
|
||||
else {
|
||||
const auto& message = messages[next - start]; hex(message.sender, full_key);
|
||||
snprintf(entry, sizeof(entry), " %lu/%u:%s", (unsigned long)message.id, unsigned(message.length), full_key);
|
||||
}
|
||||
char header_text[128];
|
||||
const int n = settings ? snprintf(header_text, sizeof(header_text),
|
||||
"rev=%lu mode=%s delivery=%s queued=%u allowed=%u start=%lu next=%lu",
|
||||
(unsigned long)state.revision, modeName(state.settings.mode), state.settings.mailbox_only ? "mailbox" : "chat",
|
||||
unsigned(state.count), unsigned(total), (unsigned long)start, (unsigned long)(next + 1))
|
||||
: snprintf(header_text, sizeof(header_text), "rev=%lu total=%u start=%lu next=%lu",
|
||||
(unsigned long)state.revision, unsigned(total), (unsigned long)start, (unsigned long)(next + 1));
|
||||
if (!settings && n >= 0 && size_t(n) + used + strlen(entry) >= capacity) {
|
||||
const auto& message = messages[next - start];
|
||||
for (size_t digits = 16; digits >= 8; digits -= 8) {
|
||||
full_key[digits] = 0;
|
||||
snprintf(entry, sizeof(entry), " %lu/%u:%s..", (unsigned long)message.id, unsigned(message.length), full_key);
|
||||
if (size_t(n) + used + strlen(entry) < capacity) break;
|
||||
}
|
||||
}
|
||||
const size_t entry_length = strlen(entry);
|
||||
if (n < 0 || size_t(n) >= sizeof(header_text) || entry_length >= sizeof(entries) - used
|
||||
|| size_t(n) + used + entry_length >= capacity) break;
|
||||
memcpy(entries + used, entry, entry_length + 1); used += entry_length; ++next;
|
||||
}
|
||||
if (next == start && next < total) { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
prefix_length = settings ? snprintf(reply, capacity,
|
||||
"rev=%lu mode=%s delivery=%s queued=%u allowed=%u start=%lu next=%lu%s",
|
||||
(unsigned long)state.revision, modeName(state.settings.mode), state.settings.mailbox_only ? "mailbox" : "chat",
|
||||
unsigned(state.count), unsigned(total), (unsigned long)start, (unsigned long)next, entries)
|
||||
: snprintf(reply, capacity, "rev=%lu total=%u start=%lu next=%lu%s", (unsigned long)state.revision,
|
||||
unsigned(total), (unsigned long)start, (unsigned long)next, entries);
|
||||
if (prefix_length < 0 || size_t(prefix_length) >= capacity) textResult(reply, capacity, RoomMailResult::Invalid);
|
||||
return true;
|
||||
}
|
||||
const char* value = spaces(body + (mode ? 4 : delivery ? 8 : allow ? 5 : 4));
|
||||
uint8_t bytes[32] = {}; uint8_t operation;
|
||||
if (mode) {
|
||||
operation = 8;
|
||||
if (strcmp(value, "closed") == 0) bytes[0] = 0;
|
||||
else if (strcmp(value, "public") == 0) bytes[0] = 1;
|
||||
else if (strcmp(value, "private") == 0) bytes[0] = 2;
|
||||
else { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
} else if (delivery) {
|
||||
operation = 9;
|
||||
if (strcmp(value, "mailbox") == 0) bytes[0] = 1;
|
||||
else if (strcmp(value, "chat") != 0) { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
} else {
|
||||
operation = allow ? 6 : 7;
|
||||
if (!key(value, bytes)) { textResult(reply, capacity, RoomMailResult::Invalid); return true; }
|
||||
}
|
||||
result = editSettings(state.settings, operation, bytes);
|
||||
if (result == RoomMailResult::Success) result = saveRoomMailSettings(fs, owner, state.settings, state.revision);
|
||||
textResult(reply, capacity, result); return true;
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,729 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <SHA256.h>
|
||||
#include "FilePresence.h"
|
||||
|
||||
namespace mesh {
|
||||
|
||||
static constexpr uint8_t ROOM_MAIL_MAX_OWNERS = 32;
|
||||
static constexpr uint8_t ROOM_MAIL_MAX_MESSAGES = 16;
|
||||
static constexpr uint8_t ROOM_MAIL_MAX_PER_OWNER = 4;
|
||||
static constexpr uint8_t ROOM_MAIL_MAX_ALLOWED = 8;
|
||||
static constexpr uint8_t ROOM_MAIL_RETRY_RECEIPTS = 8;
|
||||
static constexpr size_t ROOM_MAIL_MAX_BODY_LENGTH = 512;
|
||||
static constexpr size_t ROOM_MAIL_READ_MAX_CHUNK = 128;
|
||||
static const char ROOM_MAIL_PRIMARY_PATH[] = "/room_mail";
|
||||
static const char ROOM_MAIL_TEMP_PATH[] = "/room_mail.tmp";
|
||||
static const char ROOM_MAIL_BACKUP_PATH[] = "/room_mail.bak";
|
||||
|
||||
enum class RoomMailResult : uint8_t {
|
||||
Success, Invalid, Unavailable, WriteFailure, NotFound, StaleVersion,
|
||||
Forbidden, Full, Duplicate, Mismatch
|
||||
};
|
||||
enum class RoomMailMode : uint8_t { Closed = 0, Public = 1, Private = 2 };
|
||||
struct RoomMailSettings {
|
||||
RoomMailMode mode = RoomMailMode::Closed;
|
||||
bool mailbox_only = false;
|
||||
uint8_t allowed_count = 0;
|
||||
uint8_t allowed[ROOM_MAIL_MAX_ALLOWED][32] = {};
|
||||
};
|
||||
struct RoomMailStatus {
|
||||
uint32_t revision = 0;
|
||||
uint8_t count = 0;
|
||||
RoomMailSettings settings;
|
||||
};
|
||||
struct RoomMailMessage {
|
||||
uint32_t id = 0;
|
||||
uint64_t request_id = 0;
|
||||
uint8_t sender[32] = {};
|
||||
uint16_t length = 0;
|
||||
uint32_t created = 0;
|
||||
};
|
||||
struct RoomMailStats {
|
||||
uint32_t revision = 0;
|
||||
uint8_t owners = 0;
|
||||
uint8_t messages = 0;
|
||||
};
|
||||
|
||||
// The caller supplies the authenticated full identity for owner operations.
|
||||
// Public means eligible room writers; room roles and bans remain the caller's
|
||||
// responsibility. The room operator is trusted: bodies are plaintext at rest.
|
||||
inline bool roomMailSenderAllowed(const RoomMailSettings& settings,
|
||||
const uint8_t* owner, const uint8_t* sender) {
|
||||
if (!owner || !sender) return false;
|
||||
if (memcmp(owner, sender, 32) == 0) return true;
|
||||
if (settings.mode == RoomMailMode::Public) return true;
|
||||
if (settings.mode != RoomMailMode::Private) return false;
|
||||
for (uint8_t i = 0; i < settings.allowed_count && i < ROOM_MAIL_MAX_ALLOWED; ++i)
|
||||
if (memcmp(settings.allowed[i], sender, 32) == 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace room_mail_detail {
|
||||
static constexpr size_t INDEX_HEADER_SIZE = 16;
|
||||
static constexpr size_t INDEX_ENTRY_SIZE = 36;
|
||||
static constexpr size_t OWNER_HEADER_SIZE = 48;
|
||||
static constexpr size_t POLICY_SIZE = 260;
|
||||
static constexpr size_t RECORD_SIZE = 88;
|
||||
static constexpr size_t BODY_START = OWNER_HEADER_SIZE + POLICY_SIZE
|
||||
+ ROOM_MAIL_RETRY_RECEIPTS * RECORD_SIZE;
|
||||
static constexpr size_t STREAM_CHUNK = 64;
|
||||
static const uint8_t INDEX_MAGIC[4] = {'R', 'M', 'I', 1};
|
||||
static const uint8_t OWNER_MAGIC[4] = {'R', 'M', 'O', 1};
|
||||
enum : uint8_t { Queued = 1, Acknowledged = 2, Deleted = 3 };
|
||||
struct Entry {
|
||||
uint8_t owner[32] = {};
|
||||
uint8_t slot = 0, bank = 0, count = 0;
|
||||
};
|
||||
struct Index {
|
||||
uint32_t revision = 0, slots = 0;
|
||||
uint8_t count = 0, messages = 0;
|
||||
};
|
||||
struct Record {
|
||||
RoomMailMessage message;
|
||||
uint8_t digest[32] = {};
|
||||
uint16_t offset = 0;
|
||||
uint8_t state = 0;
|
||||
};
|
||||
struct Owner {
|
||||
RoomMailSettings settings;
|
||||
uint32_t revision = 0;
|
||||
uint8_t count = 0, receipts = 0;
|
||||
Record records[ROOM_MAIL_RETRY_RECEIPTS];
|
||||
};
|
||||
static_assert(sizeof(Owner) <= 1152, "Mailbox working metadata must remain bounded");
|
||||
|
||||
inline void clearSettings(RoomMailSettings& settings) {
|
||||
settings.mode = RoomMailMode::Closed;
|
||||
settings.mailbox_only = false; settings.allowed_count = 0;
|
||||
memset(settings.allowed, 0, sizeof(settings.allowed));
|
||||
}
|
||||
inline void clearStatus(RoomMailStatus& status) {
|
||||
status.revision = 0; status.count = 0; clearSettings(status.settings);
|
||||
}
|
||||
|
||||
// Avoid an aggregate Owner{} assignment: some size-optimized embedded builds
|
||||
// reserve a second full Owner temporary on the stack even for the error path.
|
||||
inline void clearOwner(Owner& owner) {
|
||||
owner.revision = 0; owner.count = 0; owner.receipts = 0;
|
||||
clearSettings(owner.settings);
|
||||
for (uint8_t i = 0; i < ROOM_MAIL_RETRY_RECEIPTS; ++i) {
|
||||
Record& record = owner.records[i];
|
||||
record.message.id = 0; record.message.request_id = 0;
|
||||
record.message.length = 0; record.message.created = 0;
|
||||
memset(record.message.sender, 0, sizeof(record.message.sender));
|
||||
memset(record.digest, 0, sizeof(record.digest));
|
||||
record.offset = 0; record.state = 0;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool nonzero(const uint8_t* key) {
|
||||
if (!key) return false;
|
||||
for (uint8_t i = 0; i < 32; ++i) if (key[i]) return true;
|
||||
return false;
|
||||
}
|
||||
inline uint32_t get32(const uint8_t* p) {
|
||||
return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
|
||||
}
|
||||
inline void put32(uint8_t* p, uint32_t value) {
|
||||
for (uint8_t i = 0; i < 4; ++i) p[i] = uint8_t(value >> (8 * i));
|
||||
}
|
||||
inline uint16_t get16(const uint8_t* p) { return uint16_t(p[0]) | (uint16_t(p[1]) << 8); }
|
||||
inline void put16(uint8_t* p, uint16_t value) { p[0] = uint8_t(value); p[1] = uint8_t(value >> 8); }
|
||||
inline uint64_t get64(const uint8_t* p) {
|
||||
return uint64_t(get32(p)) | (uint64_t(get32(p + 4)) << 32);
|
||||
}
|
||||
inline void put64(uint8_t* p, uint64_t value) {
|
||||
put32(p, uint32_t(value)); put32(p + 4, uint32_t(value >> 32));
|
||||
}
|
||||
inline uint32_t crc(uint32_t value, const uint8_t* bytes, size_t length) {
|
||||
while (length--) {
|
||||
value ^= *bytes++;
|
||||
for (uint8_t bit = 0; bit < 8; ++bit)
|
||||
value = (value >> 1) ^ ((value & 1) ? UINT32_C(0xedb88320) : 0);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
inline bool zero(const uint8_t* bytes, size_t length) {
|
||||
while (length--) if (*bytes++) return false;
|
||||
return true;
|
||||
}
|
||||
inline bool validSettings(const RoomMailSettings& s) {
|
||||
if (uint8_t(s.mode) > 2 || s.allowed_count > ROOM_MAIL_MAX_ALLOWED) return false;
|
||||
for (uint8_t i = 0; i < s.allowed_count; ++i) {
|
||||
if (!nonzero(s.allowed[i])) return false;
|
||||
for (uint8_t j = 0; j < i; ++j) if (!memcmp(s.allowed[i], s.allowed[j], 32)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Complete UTF-8 text only. Newlines and tabs are valid; embedded NUL is not.
|
||||
inline bool validBody(const char* body, size_t length) {
|
||||
if (!body || !length || length > ROOM_MAIL_MAX_BODY_LENGTH) return false;
|
||||
for (size_t i = 0; i < length;) {
|
||||
const uint8_t first = uint8_t(body[i++]);
|
||||
if (!first) return false;
|
||||
if (first < 0x80) continue;
|
||||
uint8_t count; uint32_t point, minimum;
|
||||
if (first >= 0xc2 && first <= 0xdf) { count = 1; point = first & 0x1f; minimum = 0x80; }
|
||||
else if (first >= 0xe0 && first <= 0xef) { count = 2; point = first & 0x0f; minimum = 0x800; }
|
||||
else if (first >= 0xf0 && first <= 0xf4) { count = 3; point = first & 7; minimum = 0x10000; }
|
||||
else return false;
|
||||
if (count > length - i) return false;
|
||||
while (count--) {
|
||||
const uint8_t next = uint8_t(body[i++]);
|
||||
if ((next & 0xc0) != 0x80) return false;
|
||||
point = (point << 6) | (next & 0x3f);
|
||||
}
|
||||
if (point < minimum || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
inline void bodyDigest(const char* body, size_t length, uint8_t* output) {
|
||||
SHA256 sha; sha.update(body, length); sha.finalize(output, 32);
|
||||
}
|
||||
inline void ownerPath(const Entry& entry, char (&path)[24]) {
|
||||
snprintf(path, sizeof(path), "/room_mail_%u.%c", unsigned(entry.slot), entry.bank ? 'b' : 'a');
|
||||
}
|
||||
inline void encodeEntry(const Entry& entry, uint8_t (&bytes)[INDEX_ENTRY_SIZE]) {
|
||||
memcpy(bytes, entry.owner, 32); bytes[32] = entry.slot; bytes[33] = entry.bank;
|
||||
bytes[34] = entry.count; bytes[35] = 0;
|
||||
}
|
||||
inline void encodeRecord(const Record& r, uint8_t (&bytes)[RECORD_SIZE]) {
|
||||
memset(bytes, 0, sizeof(bytes));
|
||||
if (!r.state) return;
|
||||
memcpy(bytes, r.message.sender, 32); put64(bytes + 32, r.message.request_id);
|
||||
put32(bytes + 40, r.message.id); put32(bytes + 44, r.message.created);
|
||||
put16(bytes + 48, r.message.length); bytes[50] = r.state;
|
||||
memcpy(bytes + 52, r.digest, 32);
|
||||
}
|
||||
template <typename Filesystem>
|
||||
auto openRead(Filesystem* fs, const char* path)
|
||||
#if defined(RP2040_PLATFORM)
|
||||
-> decltype(fs->open(path, static_cast<const char*>(nullptr))) { return fs->open(path, "r"); }
|
||||
#else
|
||||
-> decltype(fs->open(path)) { return fs->open(path); }
|
||||
#endif
|
||||
|
||||
template <typename Filesystem>
|
||||
auto openWrite(Filesystem* fs, const char* path)
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
-> decltype(fs->open(path, FILE_O_WRITE)) { return fs->open(path, FILE_O_WRITE); }
|
||||
#elif defined(ESP32_PLATFORM)
|
||||
-> decltype(fs->open(path, static_cast<const char*>(nullptr), true)) { return fs->open(path, "w", true); }
|
||||
#else
|
||||
-> decltype(fs->open(path, static_cast<const char*>(nullptr))) { return fs->open(path, "w"); }
|
||||
#endif
|
||||
|
||||
template <typename Filesystem>
|
||||
bool removeArtifact(Filesystem* fs, const char* path) {
|
||||
bool present;
|
||||
if (!filePresence(fs, path, present)) return false;
|
||||
if (!present) return true;
|
||||
fs->remove(path);
|
||||
return filePresence(fs, path, present) && !present;
|
||||
}
|
||||
|
||||
// Index validation is streamed: no 32-owner RAM registry. Keys are sorted and
|
||||
// slots are stable independently of ACL eviction or index cursor changes.
|
||||
template <typename Filesystem>
|
||||
bool readIndex(Filesystem* fs, const char* path, Index& index,
|
||||
const uint8_t* owner = nullptr, Entry* found = nullptr,
|
||||
bool* has_owner = nullptr, const uint32_t* expected_crc = nullptr) {
|
||||
index = Index{}; if (has_owner) *has_owner = false;
|
||||
auto file = openRead(fs, path); if (!file) return false;
|
||||
uint8_t header[INDEX_HEADER_SIZE];
|
||||
bool valid = !file.isDirectory() && size_t(file.read(header, sizeof(header))) == sizeof(header);
|
||||
if (valid) valid = !memcmp(header, INDEX_MAGIC, 4) && get32(header + 4) != 0
|
||||
&& header[8] <= ROOM_MAIL_MAX_OWNERS && header[9] <= ROOM_MAIL_MAX_MESSAGES
|
||||
&& zero(header + 10, 6) && file.size() == INDEX_HEADER_SIZE + header[8] * INDEX_ENTRY_SIZE + 4;
|
||||
uint32_t sum = valid ? crc(UINT32_C(0xffffffff), header, sizeof(header)) : 0;
|
||||
uint8_t previous[32] = {}; uint8_t total = 0;
|
||||
if (valid) { index.revision = get32(header + 4); index.count = header[8]; index.messages = header[9]; }
|
||||
for (uint8_t i = 0; valid && i < index.count; ++i) {
|
||||
uint8_t bytes[INDEX_ENTRY_SIZE];
|
||||
valid = size_t(file.read(bytes, sizeof(bytes))) == sizeof(bytes);
|
||||
if (!valid) break;
|
||||
sum = crc(sum, bytes, sizeof(bytes));
|
||||
valid = nonzero(bytes) && bytes[32] < ROOM_MAIL_MAX_OWNERS && bytes[33] <= 1
|
||||
&& bytes[34] <= ROOM_MAIL_MAX_PER_OWNER && bytes[35] == 0
|
||||
&& !(index.slots & (UINT32_C(1) << bytes[32]))
|
||||
&& (i == 0 || memcmp(previous, bytes, 32) < 0);
|
||||
if (!valid) break;
|
||||
index.slots |= UINT32_C(1) << bytes[32]; total += bytes[34]; memcpy(previous, bytes, 32);
|
||||
if (owner && !memcmp(owner, bytes, 32)) {
|
||||
if (found) { memcpy(found->owner, bytes, 32); found->slot = bytes[32]; found->bank = bytes[33]; found->count = bytes[34]; }
|
||||
if (has_owner) *has_owner = true;
|
||||
}
|
||||
}
|
||||
uint8_t trailer[4]; sum ^= UINT32_C(0xffffffff);
|
||||
if (valid) valid = total == index.messages && size_t(file.read(trailer, 4)) == 4
|
||||
&& get32(trailer) == sum && (!expected_crc || sum == *expected_crc);
|
||||
file.close();
|
||||
if (!valid) { index = Index{}; if (has_owner) *has_owner = false; }
|
||||
return valid;
|
||||
}
|
||||
|
||||
// Present but invalid primary metadata is authoritative. Preserve all evidence.
|
||||
// Only absence permits restoration of a verified backup. Temp is uncommitted.
|
||||
template <typename Filesystem>
|
||||
bool recover(Filesystem* fs, Index& index, const uint8_t* owner,
|
||||
Entry& entry, bool& found, bool cleanup) {
|
||||
index = Index{}; found = false;
|
||||
bool present;
|
||||
if (!fs || !filePresence(fs, ROOM_MAIL_PRIMARY_PATH, present)) return false;
|
||||
if (present) {
|
||||
if (!readIndex(fs, ROOM_MAIL_PRIMARY_PATH, index, owner, &entry, &found)) return false;
|
||||
} else {
|
||||
if (!filePresence(fs, ROOM_MAIL_BACKUP_PATH, present)) return false;
|
||||
if (present) {
|
||||
if (!readIndex(fs, ROOM_MAIL_BACKUP_PATH, index, owner, &entry, &found)
|
||||
|| !fs->rename(ROOM_MAIL_BACKUP_PATH, ROOM_MAIL_PRIMARY_PATH)) return false;
|
||||
}
|
||||
}
|
||||
if (cleanup) return removeArtifact(fs, ROOM_MAIL_TEMP_PATH) && removeArtifact(fs, ROOM_MAIL_BACKUP_PATH);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Entire selected bank is verified before releasing any requested slice. Owner
|
||||
// metadata is optional: validation needs only fixed 88-byte/64-byte buffers.
|
||||
template <typename Filesystem>
|
||||
bool readOwner(Filesystem* fs, const Entry& entry, Owner* out,
|
||||
uint32_t selected_id = 0, size_t offset = 0,
|
||||
uint8_t* output = nullptr, size_t capacity = 0,
|
||||
const uint32_t* expected_crc = nullptr,
|
||||
RoomMailStatus* status = nullptr, bool* mailbox_only = nullptr,
|
||||
uint32_t max_revision = UINT32_MAX) {
|
||||
if (out) clearOwner(*out);
|
||||
if (status) clearStatus(*status);
|
||||
if (mailbox_only) *mailbox_only = false;
|
||||
char path[24]; ownerPath(entry, path);
|
||||
auto file = openRead(fs, path); if (!file) return false;
|
||||
uint8_t header[OWNER_HEADER_SIZE];
|
||||
bool valid = !file.isDirectory() && size_t(file.read(header, sizeof(header))) == sizeof(header);
|
||||
if (valid) valid = !memcmp(header, OWNER_MAGIC, 4) && !memcmp(header + 4, entry.owner, 32)
|
||||
&& get32(header + 36) != 0 && get32(header + 36) <= max_revision
|
||||
&& header[40] == entry.slot && header[41] == entry.bank
|
||||
&& header[42] == entry.count && header[43] <= ROOM_MAIL_RETRY_RECEIPTS
|
||||
&& zero(header + 44, 4);
|
||||
uint32_t sum = valid ? crc(UINT32_C(0xffffffff), header, sizeof(header)) : 0;
|
||||
uint8_t policy[4];
|
||||
if (valid) valid = size_t(file.read(policy, 4)) == 4 && policy[0] <= 2 && policy[1] <= 1
|
||||
&& policy[2] <= ROOM_MAIL_MAX_ALLOWED && policy[3] == 0;
|
||||
if (valid) {
|
||||
sum = crc(sum, policy, 4);
|
||||
if (out) { out->revision = get32(header + 36); out->count = header[42]; out->receipts = header[43];
|
||||
out->settings.mode = RoomMailMode(policy[0]); out->settings.mailbox_only = policy[1] != 0;
|
||||
out->settings.allowed_count = policy[2]; }
|
||||
if (status) {
|
||||
status->revision = get32(header + 36); status->count = header[42];
|
||||
status->settings.mode = RoomMailMode(policy[0]);
|
||||
status->settings.mailbox_only = policy[1] != 0;
|
||||
status->settings.allowed_count = policy[2];
|
||||
}
|
||||
}
|
||||
uint8_t previous[32] = {};
|
||||
for (uint8_t i = 0; valid && i < ROOM_MAIL_MAX_ALLOWED; ++i) {
|
||||
uint8_t key[32]; valid = size_t(file.read(key, 32)) == 32;
|
||||
if (!valid) break;
|
||||
sum = crc(sum, key, 32);
|
||||
valid = i < policy[2] ? nonzero(key) && (i == 0 || memcmp(previous, key, 32) < 0) : zero(key, 32);
|
||||
if (i < policy[2]) memcpy(previous, key, 32);
|
||||
if (out) memcpy(out->settings.allowed[i], key, 32);
|
||||
if (status) memcpy(status->settings.allowed[i], key, 32);
|
||||
}
|
||||
uint32_t previous_id = 0; uint8_t queued = 0;
|
||||
size_t body_length = 0, selected_position = 0, selected_length = 0;
|
||||
for (uint8_t i = 0; valid && i < ROOM_MAIL_RETRY_RECEIPTS; ++i) {
|
||||
uint8_t bytes[RECORD_SIZE]; valid = size_t(file.read(bytes, sizeof(bytes))) == sizeof(bytes);
|
||||
if (!valid) break;
|
||||
sum = crc(sum, bytes, sizeof(bytes));
|
||||
if (i >= header[43]) { valid = zero(bytes, sizeof(bytes)); continue; }
|
||||
const uint32_t id = get32(bytes + 40); const uint16_t length = get16(bytes + 48);
|
||||
valid = nonzero(bytes) && get64(bytes + 32) != 0 && id > previous_id
|
||||
&& id <= get32(header + 36) && length != 0 && length <= ROOM_MAIL_MAX_BODY_LENGTH
|
||||
&& bytes[50] >= Queued && bytes[50] <= Deleted && bytes[51] == 0 && zero(bytes + 84, 4);
|
||||
previous_id = id;
|
||||
if (out) {
|
||||
Record& record = out->records[i]; memcpy(record.message.sender, bytes, 32);
|
||||
record.message.request_id = get64(bytes + 32); record.message.id = id;
|
||||
record.message.created = get32(bytes + 44); record.message.length = length;
|
||||
record.state = bytes[50]; memcpy(record.digest, bytes + 52, 32);
|
||||
record.offset = uint16_t(BODY_START + body_length);
|
||||
}
|
||||
if (bytes[50] == Queued) {
|
||||
if (id == selected_id) { selected_position = body_length; selected_length = length; }
|
||||
body_length += length; ++queued;
|
||||
}
|
||||
}
|
||||
if (valid) valid = queued == entry.count && file.size() == BODY_START + body_length + 4;
|
||||
uint8_t chunk[STREAM_CHUNK];
|
||||
for (size_t position = 0; valid && position < body_length;) {
|
||||
const size_t remaining = body_length - position;
|
||||
const size_t length = remaining < sizeof(chunk) ? remaining : sizeof(chunk);
|
||||
valid = size_t(file.read(chunk, length)) == length;
|
||||
if (!valid) break;
|
||||
sum = crc(sum, chunk, length);
|
||||
const size_t begin = selected_position + offset;
|
||||
size_t wanted = selected_length > offset ? selected_length - offset : 0;
|
||||
if (wanted > capacity) wanted = capacity;
|
||||
if (output && selected_length && position + length > begin && position < begin + wanted) {
|
||||
const size_t start = position < begin ? begin - position : 0;
|
||||
size_t end = length; if (position + end > begin + wanted) end = begin + wanted - position;
|
||||
memcpy(output + position + start - begin, chunk + start, end - start);
|
||||
}
|
||||
position += length;
|
||||
}
|
||||
uint8_t trailer[4]; sum ^= UINT32_C(0xffffffff);
|
||||
if (valid) valid = size_t(file.read(trailer, 4)) == 4 && get32(trailer) == sum
|
||||
&& (!expected_crc || sum == *expected_crc);
|
||||
file.close();
|
||||
if (!valid) {
|
||||
if (out) clearOwner(*out);
|
||||
if (status) clearStatus(*status);
|
||||
if (output) memset(output, 0, capacity);
|
||||
} else if (mailbox_only) *mailbox_only = policy[1] != 0;
|
||||
return valid;
|
||||
}
|
||||
|
||||
template <typename File>
|
||||
bool writeBytes(File& file, uint32_t& sum, const uint8_t* bytes, size_t length) {
|
||||
if (file.write(bytes, length) != length) return false;
|
||||
sum = crc(sum, bytes, length); return true;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
bool writeOwner(Filesystem* fs, const Entry& entry, const Owner& owner,
|
||||
bool had_owner, const Entry& previous,
|
||||
uint32_t& written_checksum,
|
||||
uint32_t new_id = 0, const char* new_body = nullptr) {
|
||||
char path[24]; ownerPath(entry, path);
|
||||
if (!removeArtifact(fs, path)) return false;
|
||||
auto file = openWrite(fs, path); if (!file) return false;
|
||||
uint8_t header[OWNER_HEADER_SIZE] = {};
|
||||
memcpy(header, OWNER_MAGIC, 4); memcpy(header + 4, entry.owner, 32);
|
||||
put32(header + 36, owner.revision); header[40] = entry.slot; header[41] = entry.bank;
|
||||
header[42] = owner.count; header[43] = owner.receipts;
|
||||
uint32_t sum = UINT32_C(0xffffffff);
|
||||
bool okay = !file.isDirectory() && writeBytes(file, sum, header, sizeof(header));
|
||||
uint8_t policy[4] = {uint8_t(owner.settings.mode), uint8_t(owner.settings.mailbox_only), owner.settings.allowed_count, 0};
|
||||
okay = okay && writeBytes(file, sum, policy, 4);
|
||||
for (uint8_t i = 0; okay && i < ROOM_MAIL_MAX_ALLOWED; ++i)
|
||||
okay = writeBytes(file, sum, owner.settings.allowed[i], 32);
|
||||
for (uint8_t i = 0; okay && i < ROOM_MAIL_RETRY_RECEIPTS; ++i) {
|
||||
uint8_t bytes[RECORD_SIZE]; encodeRecord(owner.records[i], bytes);
|
||||
okay = writeBytes(file, sum, bytes, sizeof(bytes));
|
||||
}
|
||||
// Adafruit LittleFS File requires its filesystem at construction. Obtain
|
||||
// the source through open(), including its valid filesystem-bound failure
|
||||
// value, rather than default-constructing an optional File handle.
|
||||
Entry source_entry = previous;
|
||||
if (!had_owner) source_entry.bank = 1 - entry.bank;
|
||||
char source_path[24]; ownerPath(source_entry, source_path);
|
||||
auto source = openRead(fs, source_path);
|
||||
if (!had_owner && source) source.close();
|
||||
size_t source_position = 0;
|
||||
uint8_t chunk[STREAM_CHUNK];
|
||||
for (uint8_t i = 0; okay && i < owner.receipts; ++i) {
|
||||
const Record& record = owner.records[i]; if (record.state != Queued) continue;
|
||||
if (record.message.id != new_id && (!had_owner || !source || source.isDirectory())) { okay = false; break; }
|
||||
while (okay && record.message.id != new_id && source_position < record.offset) {
|
||||
size_t length = record.offset - source_position; if (length > sizeof(chunk)) length = sizeof(chunk);
|
||||
okay = size_t(source.read(chunk, length)) == length; source_position += length;
|
||||
}
|
||||
for (size_t position = 0; okay && position < record.message.length;) {
|
||||
size_t length = record.message.length - position; if (length > sizeof(chunk)) length = sizeof(chunk);
|
||||
if (record.message.id == new_id) {
|
||||
if (!new_body) { okay = false; break; }
|
||||
memcpy(chunk, new_body + position, length);
|
||||
} else { okay = size_t(source.read(chunk, length)) == length; source_position += length; }
|
||||
okay = okay && writeBytes(file, sum, chunk, length); position += length;
|
||||
}
|
||||
}
|
||||
if (source) source.close();
|
||||
sum ^= UINT32_C(0xffffffff); uint8_t trailer[4]; put32(trailer, sum);
|
||||
okay = okay && file.write(trailer, 4) == 4; file.flush(); file.close();
|
||||
written_checksum = sum;
|
||||
return okay;
|
||||
}
|
||||
|
||||
// Publish a streamed sorted registry pointing at an already verified bank.
|
||||
// A failed rename can leave a verified backup; recover() restores it on retry.
|
||||
template <typename Filesystem>
|
||||
RoomMailResult publish(Filesystem* fs, const Index& prior, const Entry& entry, bool existed,
|
||||
uint32_t revision) {
|
||||
if (!removeArtifact(fs, ROOM_MAIL_TEMP_PATH) || !removeArtifact(fs, ROOM_MAIL_BACKUP_PATH))
|
||||
return RoomMailResult::WriteFailure;
|
||||
auto file = openWrite(fs, ROOM_MAIL_TEMP_PATH); if (!file) return RoomMailResult::WriteFailure;
|
||||
uint8_t header[INDEX_HEADER_SIZE] = {};
|
||||
memcpy(header, INDEX_MAGIC, 4); put32(header + 4, revision);
|
||||
header[8] = prior.count + (existed ? 0 : 1);
|
||||
uint8_t old_count = 0;
|
||||
Entry ignored; Index checked; bool found = false;
|
||||
if (existed && !readIndex(fs, ROOM_MAIL_PRIMARY_PATH, checked, entry.owner, &ignored, &found)) {
|
||||
file.close(); return RoomMailResult::WriteFailure;
|
||||
}
|
||||
if (found) old_count = ignored.count;
|
||||
header[9] = prior.messages - old_count + entry.count;
|
||||
uint32_t sum = UINT32_C(0xffffffff);
|
||||
bool okay = !file.isDirectory() && writeBytes(file, sum, header, sizeof(header));
|
||||
auto source = openRead(fs, ROOM_MAIL_PRIMARY_PATH);
|
||||
if (prior.revision) {
|
||||
uint8_t skipped[INDEX_HEADER_SIZE];
|
||||
okay = okay && source && !source.isDirectory() && size_t(source.read(skipped, sizeof(skipped))) == sizeof(skipped);
|
||||
}
|
||||
bool emitted = false;
|
||||
for (uint8_t i = 0; okay && i < prior.count; ++i) {
|
||||
uint8_t bytes[INDEX_ENTRY_SIZE]; okay = size_t(source.read(bytes, sizeof(bytes))) == sizeof(bytes);
|
||||
if (!okay) break;
|
||||
const int comparison = memcmp(entry.owner, bytes, 32);
|
||||
if (!emitted && comparison <= 0) {
|
||||
uint8_t added[INDEX_ENTRY_SIZE]; encodeEntry(entry, added);
|
||||
okay = writeBytes(file, sum, added, sizeof(added)); emitted = true;
|
||||
}
|
||||
if (comparison != 0) okay = okay && writeBytes(file, sum, bytes, sizeof(bytes));
|
||||
}
|
||||
if (okay && !emitted) { uint8_t bytes[INDEX_ENTRY_SIZE]; encodeEntry(entry, bytes); okay = writeBytes(file, sum, bytes, sizeof(bytes)); }
|
||||
if (source) source.close();
|
||||
sum ^= UINT32_C(0xffffffff); uint8_t trailer[4]; put32(trailer, sum);
|
||||
okay = okay && file.write(trailer, 4) == 4; file.flush(); file.close();
|
||||
Index verify;
|
||||
if (!okay || !readIndex(fs, ROOM_MAIL_TEMP_PATH, verify, nullptr, nullptr, nullptr, &sum))
|
||||
return RoomMailResult::WriteFailure;
|
||||
bool primary;
|
||||
if (!filePresence(fs, ROOM_MAIL_PRIMARY_PATH, primary)
|
||||
|| (primary && !fs->rename(ROOM_MAIL_PRIMARY_PATH, ROOM_MAIL_BACKUP_PATH)))
|
||||
return RoomMailResult::WriteFailure;
|
||||
if (!fs->rename(ROOM_MAIL_TEMP_PATH, ROOM_MAIL_PRIMARY_PATH)) {
|
||||
if (primary) fs->rename(ROOM_MAIL_BACKUP_PATH, ROOM_MAIL_PRIMARY_PATH);
|
||||
return RoomMailResult::WriteFailure;
|
||||
}
|
||||
// Registry rename is the commit. Housekeeping failure never undoes success.
|
||||
removeArtifact(fs, ROOM_MAIL_BACKUP_PATH);
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult commit(Filesystem* fs, Index& index, Entry& entry, Owner& owner,
|
||||
bool existed, uint32_t new_id = 0, const char* new_body = nullptr) {
|
||||
if (index.revision == UINT32_MAX) return RoomMailResult::Unavailable;
|
||||
Entry previous = entry;
|
||||
owner.revision = index.revision + 1; entry.bank = existed ? 1 - entry.bank : 0; entry.count = owner.count;
|
||||
uint32_t checksum;
|
||||
if (!writeOwner(fs, entry, owner, existed, previous, checksum, new_id, new_body)
|
||||
|| !readOwner(fs, entry, nullptr, 0, 0, nullptr, 0, &checksum))
|
||||
return RoomMailResult::WriteFailure;
|
||||
return publish(fs, index, entry, existed, owner.revision);
|
||||
}
|
||||
template <typename Filesystem>
|
||||
RoomMailResult load(Filesystem* fs, const uint8_t* key, Index& index, Entry& entry, Owner& owner,
|
||||
bool& found, bool cleanup = false) {
|
||||
if (!nonzero(key)) return RoomMailResult::Invalid;
|
||||
if (!recover(fs, index, key, entry, found, false)) return RoomMailResult::Unavailable;
|
||||
if (found && (!readOwner(fs, entry, &owner) || owner.revision > index.revision))
|
||||
return RoomMailResult::Unavailable;
|
||||
// Validate the selected committed bank before removing recovery evidence.
|
||||
if (cleanup && (!removeArtifact(fs, ROOM_MAIL_TEMP_PATH)
|
||||
|| !removeArtifact(fs, ROOM_MAIL_BACKUP_PATH))) return RoomMailResult::Unavailable;
|
||||
if (!found) { clearOwner(owner); return RoomMailResult::NotFound; }
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
} // namespace room_mail_detail
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult getRoomMailStatus(Filesystem* fs, const uint8_t* owner, RoomMailStatus& status) {
|
||||
room_mail_detail::clearStatus(status); room_mail_detail::Index index; room_mail_detail::Entry entry;
|
||||
bool found;
|
||||
if (!room_mail_detail::nonzero(owner)) return RoomMailResult::Invalid;
|
||||
if (!room_mail_detail::recover(fs, index, owner, entry, found, false)) return RoomMailResult::Unavailable;
|
||||
if (!found) return RoomMailResult::NotFound;
|
||||
return room_mail_detail::readOwner(fs, entry, nullptr, 0, 0, nullptr, 0,
|
||||
nullptr, &status, nullptr, index.revision) ? RoomMailResult::Success : RoomMailResult::Unavailable;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult getRoomMailboxOnly(Filesystem* fs, const uint8_t* owner, bool& value) {
|
||||
value = false; room_mail_detail::Index index; room_mail_detail::Entry entry; bool found;
|
||||
if (!room_mail_detail::nonzero(owner)) return RoomMailResult::Invalid;
|
||||
if (!room_mail_detail::recover(fs, index, owner, entry, found, false)) return RoomMailResult::Unavailable;
|
||||
if (!found) return RoomMailResult::Success;
|
||||
return room_mail_detail::readOwner(fs, entry, nullptr, 0, 0, nullptr, 0,
|
||||
nullptr, nullptr, &value, index.revision) ? RoomMailResult::Success : RoomMailResult::Unavailable;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult saveRoomMailSettings(Filesystem* fs, const uint8_t* key,
|
||||
const RoomMailSettings& settings, uint32_t expected_revision) {
|
||||
using namespace room_mail_detail;
|
||||
if (!nonzero(key) || !validSettings(settings)) return RoomMailResult::Invalid;
|
||||
Index index; Entry entry; Owner state; bool found;
|
||||
const auto result = load(fs, key, index, entry, state, found, true);
|
||||
if (result != RoomMailResult::Success && result != RoomMailResult::NotFound) return result;
|
||||
if (expected_revision != state.revision) return RoomMailResult::StaleVersion;
|
||||
if (!found) {
|
||||
if (index.count >= ROOM_MAIL_MAX_OWNERS) return RoomMailResult::Full;
|
||||
memcpy(entry.owner, key, 32); entry.slot = 0;
|
||||
while (index.slots & (UINT32_C(1) << entry.slot)) ++entry.slot;
|
||||
}
|
||||
state.settings = settings;
|
||||
for (uint8_t i = settings.allowed_count; i < ROOM_MAIL_MAX_ALLOWED; ++i) memset(state.settings.allowed[i], 0, 32);
|
||||
for (uint8_t i = 1; i < settings.allowed_count; ++i)
|
||||
for (uint8_t j = i; j > 0 && memcmp(state.settings.allowed[j - 1], state.settings.allowed[j], 32) > 0; --j) {
|
||||
uint8_t swap[32]; memcpy(swap, state.settings.allowed[j - 1], 32);
|
||||
memcpy(state.settings.allowed[j - 1], state.settings.allowed[j], 32); memcpy(state.settings.allowed[j], swap, 32);
|
||||
}
|
||||
return commit(fs, index, entry, state, found);
|
||||
}
|
||||
|
||||
// Convenience for local single-loop callers. Explicit revision arguments are
|
||||
// always strict: revision zero can provision only a still-absent mailbox.
|
||||
template <typename Filesystem>
|
||||
RoomMailResult saveRoomMailSettings(Filesystem* fs, const uint8_t* key,
|
||||
const RoomMailSettings& settings) {
|
||||
RoomMailStatus status;
|
||||
const auto result = getRoomMailStatus(fs, key, status);
|
||||
if (result != RoomMailResult::Success && result != RoomMailResult::NotFound) return result;
|
||||
return saveRoomMailSettings(fs, key, settings, status.revision);
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult listRoomMail(Filesystem* fs, const uint8_t* key, uint32_t expected_revision,
|
||||
size_t start, RoomMailMessage* output, size_t capacity, size_t& copied) {
|
||||
copied = 0;
|
||||
if (!output || !capacity || capacity > ROOM_MAIL_MAX_PER_OWNER) return RoomMailResult::Invalid;
|
||||
room_mail_detail::Index index; room_mail_detail::Entry entry; room_mail_detail::Owner state; bool found;
|
||||
const auto result = room_mail_detail::load(fs, key, index, entry, state, found);
|
||||
if (result != RoomMailResult::Success) return result;
|
||||
if (expected_revision && expected_revision != state.revision) return RoomMailResult::StaleVersion;
|
||||
if (start > state.count) return RoomMailResult::Invalid;
|
||||
size_t cursor = 0;
|
||||
for (uint8_t i = 0; i < state.receipts && copied < capacity; ++i)
|
||||
if (state.records[i].state == room_mail_detail::Queued && cursor++ >= start) output[copied++] = state.records[i].message;
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult readRoomMail(Filesystem* fs, const uint8_t* key, uint32_t id, size_t offset,
|
||||
uint8_t* output, size_t capacity, size_t& copied, RoomMailMessage& message) {
|
||||
copied = 0; message = RoomMailMessage{};
|
||||
if (!id || !output || !capacity || capacity > ROOM_MAIL_READ_MAX_CHUNK) return RoomMailResult::Invalid;
|
||||
room_mail_detail::Index index; room_mail_detail::Entry entry; room_mail_detail::Owner state; bool found;
|
||||
const auto result = room_mail_detail::load(fs, key, index, entry, state, found);
|
||||
if (result != RoomMailResult::Success) return result;
|
||||
for (uint8_t i = 0; i < state.receipts; ++i) {
|
||||
const auto& record = state.records[i];
|
||||
if (record.message.id != id || record.state != room_mail_detail::Queued) continue;
|
||||
if (offset > record.message.length) return RoomMailResult::Invalid;
|
||||
if (!room_mail_detail::readOwner(fs, entry, nullptr, id, offset, output, capacity)) return RoomMailResult::Unavailable;
|
||||
message = record.message; copied = message.length - offset; if (copied > capacity) copied = capacity;
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
return RoomMailResult::NotFound;
|
||||
}
|
||||
|
||||
// Up to eight accepted submission receipts remain: queued receipts never evict,
|
||||
// and the oldest retired receipt is replaced when needed. Exact nonce/body
|
||||
// retries return Duplicate across reboot and after
|
||||
// ACK/delete. Reusing a retained nonce with different content returns Mismatch.
|
||||
// An ancient retry after its retired receipt is evicted can enqueue again.
|
||||
template <typename Filesystem>
|
||||
RoomMailResult sendRoomMail(Filesystem* fs, const uint8_t* sender, const uint8_t* key,
|
||||
uint64_t request_id, const char* body, size_t length,
|
||||
uint32_t& id, uint32_t created = 0) {
|
||||
using namespace room_mail_detail;
|
||||
id = 0;
|
||||
if (!nonzero(sender) || !nonzero(key) || !request_id || !validBody(body, length)) return RoomMailResult::Invalid;
|
||||
Index index; Entry entry; Owner state; bool found;
|
||||
const auto result = load(fs, key, index, entry, state, found, true);
|
||||
if (result != RoomMailResult::Success) return result;
|
||||
if (!roomMailSenderAllowed(state.settings, key, sender)) return RoomMailResult::Forbidden;
|
||||
uint8_t digest[32]; bodyDigest(body, length, digest);
|
||||
for (uint8_t i = 0; i < state.receipts; ++i) {
|
||||
const auto& record = state.records[i];
|
||||
if (record.message.request_id != request_id || memcmp(record.message.sender, sender, 32)) continue;
|
||||
if (record.message.length != length || memcmp(record.digest, digest, 32)) return RoomMailResult::Mismatch;
|
||||
id = record.message.id; return RoomMailResult::Duplicate;
|
||||
}
|
||||
if (state.count >= ROOM_MAIL_MAX_PER_OWNER || index.messages >= ROOM_MAIL_MAX_MESSAGES) return RoomMailResult::Full;
|
||||
if (index.revision == UINT32_MAX) return RoomMailResult::Unavailable;
|
||||
if (state.receipts == ROOM_MAIL_RETRY_RECEIPTS) {
|
||||
uint8_t retired = 0; while (retired < state.receipts && state.records[retired].state == Queued) ++retired;
|
||||
if (retired == state.receipts) return RoomMailResult::Full;
|
||||
for (uint8_t i = retired; i + 1 < state.receipts; ++i) state.records[i] = state.records[i + 1];
|
||||
--state.receipts;
|
||||
}
|
||||
Record& added = state.records[state.receipts++]; added = Record{};
|
||||
added.message.id = index.revision + 1; added.message.request_id = request_id;
|
||||
added.message.created = created; added.message.length = uint16_t(length);
|
||||
memcpy(added.message.sender, sender, 32); memcpy(added.digest, digest, 32);
|
||||
added.state = Queued; ++state.count;
|
||||
const auto saved = commit(fs, index, entry, state, true, added.message.id, body);
|
||||
if (saved == RoomMailResult::Success) id = added.message.id;
|
||||
return saved;
|
||||
}
|
||||
|
||||
namespace room_mail_detail {
|
||||
template <typename Filesystem>
|
||||
RoomMailResult retire(Filesystem* fs, const uint8_t* key, uint32_t id, uint8_t kind, bool purge) {
|
||||
Index index; Entry entry; Owner state; bool found;
|
||||
const auto result = load(fs, key, index, entry, state, found, true);
|
||||
if (result != RoomMailResult::Success) return result;
|
||||
bool known = false, changed = false;
|
||||
for (uint8_t i = 0; i < state.receipts; ++i) {
|
||||
auto& record = state.records[i];
|
||||
if (!purge && record.message.id != id) continue;
|
||||
known = true;
|
||||
if (record.state == Queued) { record.state = kind; --state.count; changed = true; }
|
||||
}
|
||||
if (!known && !purge) return RoomMailResult::NotFound;
|
||||
if (!changed) return RoomMailResult::Success;
|
||||
return commit(fs, index, entry, state, true);
|
||||
}
|
||||
} // namespace room_mail_detail
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult acknowledgeRoomMail(Filesystem* fs, const uint8_t* owner, uint32_t id) {
|
||||
if (!id) return RoomMailResult::Invalid;
|
||||
return room_mail_detail::retire(fs, owner, id, room_mail_detail::Acknowledged, false);
|
||||
}
|
||||
template <typename Filesystem>
|
||||
RoomMailResult deleteRoomMail(Filesystem* fs, const uint8_t* owner, uint32_t id) {
|
||||
return room_mail_detail::retire(fs, owner, id, room_mail_detail::Deleted, id == 0);
|
||||
}
|
||||
|
||||
template <typename Filesystem>
|
||||
RoomMailResult getRoomMailStats(Filesystem* fs, RoomMailStats& stats) {
|
||||
stats = RoomMailStats{}; room_mail_detail::Index index; room_mail_detail::Entry entry; bool found;
|
||||
if (!room_mail_detail::recover(fs, index, nullptr, entry, found, false)) return RoomMailResult::Unavailable;
|
||||
stats.revision = index.revision; stats.owners = index.count; stats.messages = index.messages;
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
|
||||
// Administrator-only owner enumeration. Caller must authorize this explicitly.
|
||||
// Public mailbox reads never disclose the registry or another owner's policy.
|
||||
template <typename Filesystem>
|
||||
RoomMailResult listRoomMailOwners(Filesystem* fs, uint32_t expected_revision, size_t start,
|
||||
uint8_t (*keys)[32], size_t capacity, size_t& copied,
|
||||
RoomMailStats& stats) {
|
||||
copied = 0;
|
||||
if (!keys || !capacity || capacity > ROOM_MAIL_MAX_OWNERS) return RoomMailResult::Invalid;
|
||||
const auto result = getRoomMailStats(fs, stats);
|
||||
if (result != RoomMailResult::Success) return result;
|
||||
if (expected_revision && expected_revision != stats.revision) return RoomMailResult::StaleVersion;
|
||||
if (start > stats.owners) return RoomMailResult::Invalid;
|
||||
if (!stats.owners) return RoomMailResult::Success;
|
||||
auto file = room_mail_detail::openRead(fs, ROOM_MAIL_PRIMARY_PATH); if (!file) return RoomMailResult::Unavailable;
|
||||
uint8_t header[room_mail_detail::INDEX_HEADER_SIZE];
|
||||
bool okay = size_t(file.read(header, sizeof(header))) == sizeof(header);
|
||||
for (size_t i = 0; okay && i < stats.owners && copied < capacity; ++i) {
|
||||
uint8_t bytes[room_mail_detail::INDEX_ENTRY_SIZE]; okay = size_t(file.read(bytes, sizeof(bytes))) == sizeof(bytes);
|
||||
if (okay && i >= start) memcpy(keys[copied++], bytes, 32);
|
||||
}
|
||||
file.close();
|
||||
if (!okay) { copied = 0; return RoomMailResult::Unavailable; }
|
||||
return RoomMailResult::Success;
|
||||
}
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,247 @@
|
||||
#pragma once
|
||||
|
||||
#include "RoomMailStore.h"
|
||||
#include "RoomWebJson.h"
|
||||
|
||||
namespace mesh {
|
||||
|
||||
inline void roomMailWebHex(char* output, const uint8_t* key, size_t length) {
|
||||
static const char digits[] = "0123456789abcdef";
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
output[2 * i] = digits[key[i] >> 4]; output[2 * i + 1] = digits[key[i] & 15];
|
||||
}
|
||||
output[length * 2] = 0;
|
||||
}
|
||||
|
||||
inline bool roomMailWebKey(uint8_t* output, size_t length, const char* text) {
|
||||
if (!text || strlen(text) != 2 * length) return false;
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
unsigned byte = 0;
|
||||
for (size_t n = 0; n < 2; ++n) {
|
||||
const char c = text[2 * i + n];
|
||||
unsigned digit;
|
||||
if (c >= '0' && c <= '9') digit = c - '0';
|
||||
else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10;
|
||||
else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10;
|
||||
else return false;
|
||||
byte = 16 * byte + digit;
|
||||
}
|
||||
output[i] = uint8_t(byte);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline const char* roomMailModeName(RoomMailMode mode) {
|
||||
return mode == RoomMailMode::Public ? "public" : mode == RoomMailMode::Private ? "private" : "closed";
|
||||
}
|
||||
|
||||
inline const char* roomMailError(RoomMailResult result) {
|
||||
switch (result) {
|
||||
case RoomMailResult::Invalid: return "invalid mailbox request";
|
||||
case RoomMailResult::Unavailable: return "mailbox storage unavailable; previous data retained";
|
||||
case RoomMailResult::WriteFailure: return "mailbox save failed; previous data retained";
|
||||
case RoomMailResult::NotFound: return "mailbox or message not found";
|
||||
case RoomMailResult::StaleVersion: return "mailbox changed; refresh before editing";
|
||||
case RoomMailResult::Forbidden: return "recipient is not accepting messages from this identity";
|
||||
case RoomMailResult::Full: return "mailbox or server queue full; message not accepted";
|
||||
case RoomMailResult::Mismatch: return "request identifier already used for different mail";
|
||||
default: return "mailbox request failed";
|
||||
}
|
||||
}
|
||||
|
||||
inline void writeRoomMailSettingsJson(RoomJsonWriter& json, const uint8_t* owner,
|
||||
const RoomMailStatus& status, bool blocked = false) {
|
||||
char key[65]; roomMailWebHex(key, owner, 32);
|
||||
json.raw("{\"owner\":"); json.string(key);
|
||||
json.raw(",\"revision\":"); json.number(status.revision);
|
||||
json.raw(",\"mode\":"); json.string(roomMailModeName(status.settings.mode));
|
||||
json.raw(",\"mailbox_only\":"); json.raw(status.settings.mailbox_only ? "true" : "false");
|
||||
json.raw(",\"allowlist\":[");
|
||||
for (uint8_t i = 0; i < status.settings.allowed_count; ++i) {
|
||||
if (i) json.raw(",");
|
||||
roomMailWebHex(key, status.settings.allowed[i], 32); json.string(key);
|
||||
}
|
||||
json.raw("],\"total\":"); json.number(status.count);
|
||||
json.raw(",\"unread\":"); json.number(status.count);
|
||||
json.raw(",\"blocked\":"); json.raw(blocked ? "true" : "false"); json.raw("}");
|
||||
}
|
||||
|
||||
// The caller has already authenticated the browser's own token identity and
|
||||
// charged room quotas. Only explicit administrator operations may select a
|
||||
// different owner; a shared room password never proves a radio's private key.
|
||||
template <typename Filesystem, typename AllowsIdentity>
|
||||
bool handleRoomMailWeb(Filesystem* fs, const uint8_t* caller, bool can_send,
|
||||
bool administrator, uint64_t request_id, uint32_t created,
|
||||
JsonObjectConst input, RoomJsonWriter& json,
|
||||
AllowsIdentity allows) {
|
||||
const char* operation = input["op"].as<const char*>();
|
||||
if (!operation) return false;
|
||||
const bool admin = strncmp(operation, "admin.mail.", 11) == 0;
|
||||
if (!admin && strncmp(operation, "mail.", 5) != 0) return false;
|
||||
auto error = [&json](const char* message) {
|
||||
json.reset();
|
||||
json.raw("{\"error\":"); json.string(message); json.raw("}"); json.finish();
|
||||
};
|
||||
if (json.capacity() < 1024) { error("mailbox reply capacity too small"); return true; }
|
||||
auto checked = [&error](RoomMailResult result) {
|
||||
if (result == RoomMailResult::Success || result == RoomMailResult::Duplicate) return true;
|
||||
error(roomMailError(result)); return false;
|
||||
};
|
||||
auto keyValue = [](JsonVariantConst value, uint8_t* out) {
|
||||
if (!value.is<const char*>()) return false;
|
||||
const JsonString text = value.as<JsonString>();
|
||||
if (text.size() != 64 || strlen(text.c_str()) != 64
|
||||
|| !roomMailWebKey(out, 32, text.c_str())) return false;
|
||||
uint8_t any = 0; for (size_t i = 0; i < 32; ++i) any |= out[i];
|
||||
return any != 0;
|
||||
};
|
||||
if (admin && !administrator) { error("admin permission required"); return true; }
|
||||
uint8_t owner[32]; memcpy(owner, caller, sizeof(owner));
|
||||
if (admin && strcmp(operation, "admin.mail.list") != 0
|
||||
&& !keyValue(input["owner"], owner)) {
|
||||
error("complete mailbox owner public key required"); return true;
|
||||
}
|
||||
if (strcmp(operation, "admin.mail.list") == 0) {
|
||||
if (!input["cursor"].is<uint8_t>() || !input["revision"].is<uint32_t>()
|
||||
|| (input["cursor"].as<uint8_t>() && !input["revision"].as<uint32_t>())) {
|
||||
error("mailbox cursor and snapshot revision required"); return true;
|
||||
}
|
||||
uint8_t keys[2][32]; size_t copied = 0; RoomMailStats stats;
|
||||
const uint8_t cursor = input["cursor"].as<uint8_t>();
|
||||
if (!checked(listRoomMailOwners(fs, input["revision"].as<uint32_t>(), cursor,
|
||||
keys, 2, copied, stats))) return true;
|
||||
json.raw("{\"mailboxes\":[");
|
||||
for (size_t i = 0; i < copied; ++i) {
|
||||
RoomMailStatus status;
|
||||
const auto result = getRoomMailStatus(fs, keys[i], status);
|
||||
if (result != RoomMailResult::Success) { error(roomMailError(result)); return true; }
|
||||
if (i) json.raw(",");
|
||||
char key[65]; roomMailWebHex(key, keys[i], 32);
|
||||
json.raw("{\"owner\":"); json.string(key);
|
||||
json.raw(",\"mode\":"); json.string(roomMailModeName(status.settings.mode));
|
||||
json.raw(",\"revision\":"); json.number(status.revision);
|
||||
json.raw(",\"mailbox_only\":"); json.raw(status.settings.mailbox_only ? "true" : "false");
|
||||
json.raw(",\"unread\":"); json.number(status.count);
|
||||
json.raw(",\"total\":"); json.number(status.count);
|
||||
json.raw(",\"blocked\":"); json.raw(allows(keys[i]) ? "false" : "true"); json.raw("}");
|
||||
}
|
||||
json.raw("],\"next\":");
|
||||
if (cursor + copied < stats.owners) json.number(cursor + copied); else json.raw("null");
|
||||
json.raw(",\"total\":"); json.number(stats.owners);
|
||||
json.raw(",\"queued\":"); json.number(stats.messages);
|
||||
json.raw(",\"revision\":"); json.number(stats.revision); json.raw("}"); json.finish(); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.send") == 0) {
|
||||
if (!can_send) { error("read-only room access cannot send mail"); return true; }
|
||||
uint8_t recipient[32];
|
||||
if (!keyValue(input["recipient"], recipient)) { error("complete recipient public key required"); return true; }
|
||||
if (!allows(recipient)) { error("recipient is blocked"); return true; }
|
||||
if (!input["text"].is<const char*>()) { error("message required"); return true; }
|
||||
const JsonString text = input["text"].as<JsonString>();
|
||||
if (!text.size() || text.size() > 512 || strlen(text.c_str()) != text.size()) {
|
||||
error("mail must contain 1-512 UTF-8 bytes"); return true;
|
||||
}
|
||||
uint32_t id = 0;
|
||||
if (!checked(sendRoomMail(fs, caller, recipient, request_id, text.c_str(), text.size(), id, created))) return true;
|
||||
json.raw("{\"ok\":true,\"id\":"); json.number(id); json.raw("}"); json.finish(); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.policy") == 0 || strcmp(operation, "admin.mail.policy") == 0) {
|
||||
if (!input["expected_revision"].is<uint32_t>() || !input["mailbox_only"].is<bool>()
|
||||
|| !input["mode"].is<const char*>() || !input["allowlist"].is<JsonArrayConst>()) {
|
||||
error("mailbox mode, delivery, sender list and expected revision required"); return true;
|
||||
}
|
||||
RoomMailSettings settings;
|
||||
const char* mode = input["mode"].as<const char*>();
|
||||
if (strcmp(mode, "public") == 0) settings.mode = RoomMailMode::Public;
|
||||
else if (strcmp(mode, "private") == 0) settings.mode = RoomMailMode::Private;
|
||||
else if (strcmp(mode, "closed") != 0) { error("use public, private or closed mailbox access"); return true; }
|
||||
settings.mailbox_only = input["mailbox_only"].as<bool>();
|
||||
JsonArrayConst allowed = input["allowlist"].as<JsonArrayConst>();
|
||||
if (allowed.size() > 8) { error("at most eight selected senders"); return true; }
|
||||
for (JsonVariantConst value : allowed) {
|
||||
if (!keyValue(value, settings.allowed[settings.allowed_count])) {
|
||||
error("selected senders need complete public keys"); return true;
|
||||
}
|
||||
++settings.allowed_count;
|
||||
}
|
||||
if (!checked(saveRoomMailSettings(fs, owner, settings, input["expected_revision"].as<uint32_t>()))) return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.ack") == 0 || strcmp(operation, "mail.delete") == 0
|
||||
|| strcmp(operation, "admin.mail.delete") == 0) {
|
||||
if (!input["id"].is<uint32_t>() || (!admin && input["id"].as<uint32_t>() == 0)) {
|
||||
error("message identifier required"); return true;
|
||||
}
|
||||
const auto result = strcmp(operation, "mail.ack") == 0
|
||||
? acknowledgeRoomMail(fs, owner, input["id"].as<uint32_t>())
|
||||
: deleteRoomMail(fs, owner, input["id"].as<uint32_t>());
|
||||
if (!checked(result)) return true;
|
||||
json.raw("{\"ok\":true}"); json.finish(); return true;
|
||||
}
|
||||
RoomMailStatus status;
|
||||
const auto loaded = getRoomMailStatus(fs, owner, status);
|
||||
if (loaded != RoomMailResult::Success && loaded != RoomMailResult::NotFound) {
|
||||
error(roomMailError(loaded)); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.settings") == 0 || strcmp(operation, "mail.policy") == 0
|
||||
|| strcmp(operation, "admin.mail.settings") == 0 || strcmp(operation, "admin.mail.policy") == 0) {
|
||||
writeRoomMailSettingsJson(json, owner, status, !allows(owner)); json.finish(); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.check") == 0) {
|
||||
char key[65]; roomMailWebHex(key, owner, 32);
|
||||
json.raw("{\"owner\":"); json.string(key);
|
||||
json.raw(",\"unread\":"); json.number(status.count);
|
||||
json.raw(",\"total\":"); json.number(status.count);
|
||||
json.raw(",\"revision\":"); json.number(status.revision);
|
||||
json.raw(",\"mailbox_only\":"); json.raw(status.settings.mailbox_only ? "true" : "false");
|
||||
json.raw("}"); json.finish(); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.list") == 0) {
|
||||
if (!input["cursor"].is<uint8_t>() || !input["revision"].is<uint32_t>()
|
||||
|| (input["cursor"].as<uint8_t>() && !input["revision"].as<uint32_t>())) {
|
||||
error("mail cursor and snapshot revision required"); return true;
|
||||
}
|
||||
const uint8_t cursor = input["cursor"].as<uint8_t>();
|
||||
const uint32_t expected_revision = input["revision"].as<uint32_t>();
|
||||
if (expected_revision && expected_revision != status.revision) {
|
||||
error(roomMailError(RoomMailResult::StaleVersion)); return true;
|
||||
}
|
||||
if (loaded == RoomMailResult::NotFound) {
|
||||
if (cursor) { error("invalid mail cursor"); return true; }
|
||||
json.raw("{\"messages\":[],\"next\":null,\"revision\":0}"); json.finish(); return true;
|
||||
}
|
||||
RoomMailMessage messages[2]; size_t copied = 0;
|
||||
if (!checked(listRoomMail(fs, owner, status.revision, cursor, messages, 2, copied))) return true;
|
||||
json.raw("{\"messages\":[");
|
||||
for (size_t i = 0; i < copied; ++i) {
|
||||
if (i) json.raw(","); char key[65]; roomMailWebHex(key, messages[i].sender, 32);
|
||||
json.raw("{\"id\":"); json.number(messages[i].id);
|
||||
json.raw(",\"sender\":"); json.string(key);
|
||||
json.raw(",\"created\":"); json.number(messages[i].created);
|
||||
json.raw(",\"length\":"); json.number(messages[i].length); json.raw(",\"acked\":false}");
|
||||
}
|
||||
json.raw("],\"next\":");
|
||||
if (cursor + copied < status.count) json.number(cursor + copied); else json.raw("null");
|
||||
json.raw(",\"revision\":"); json.number(status.revision); json.raw("}"); json.finish(); return true;
|
||||
}
|
||||
if (strcmp(operation, "mail.read") == 0) {
|
||||
if (!input["id"].is<uint32_t>() || !input["offset"].is<uint16_t>()) {
|
||||
error("message identifier and offset required"); return true;
|
||||
}
|
||||
uint8_t bytes[128]; char encoded[173]; size_t copied = 0; RoomMailMessage message;
|
||||
const uint16_t offset = input["offset"].as<uint16_t>();
|
||||
if (!checked(readRoomMail(fs, owner, input["id"].as<uint32_t>(), offset,
|
||||
bytes, sizeof(bytes), copied, message))) return true;
|
||||
roomEncodeBase64(bytes, copied, encoded); char key[65]; roomMailWebHex(key, message.sender, 32);
|
||||
json.raw("{\"id\":"); json.number(message.id);
|
||||
json.raw(",\"sender\":"); json.string(key);
|
||||
json.raw(",\"created\":"); json.number(message.created);
|
||||
json.raw(",\"length\":"); json.number(message.length);
|
||||
json.raw(",\"offset\":"); json.number(offset);
|
||||
json.raw(",\"count\":"); json.number(copied);
|
||||
json.raw(",\"next\":"); json.number(offset + copied);
|
||||
json.raw(",\"data64\":"); json.string(encoded); json.raw(",\"acked\":false}"); json.finish(); return true;
|
||||
}
|
||||
error("unknown mailbox operation"); return true;
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -48,6 +48,11 @@ public:
|
||||
if (!output || !capacity) valid_ = false;
|
||||
else output[0] = 0;
|
||||
}
|
||||
void reset() {
|
||||
used_ = 0; valid_ = output_ && capacity_;
|
||||
if (valid_) output_[0] = 0;
|
||||
}
|
||||
size_t capacity() const { return capacity_; }
|
||||
void raw(const char* text) {
|
||||
const size_t length = strlen(text);
|
||||
if (!valid_ || length >= capacity_ - used_) { valid_ = false; return; }
|
||||
|
||||
@@ -16,9 +16,10 @@ button:disabled{opacity:.45;cursor:default}label{display:block}.muted{color:#b5b
|
||||
.post{padding:10px 0;border-bottom:1px solid #364351}.post small{display:block;color:#b5beca}
|
||||
details{margin:18px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}a{color:#a8d5ff}[hidden]{display:none!important}
|
||||
.panel{border:1px solid #526273;border-radius:10px;padding:18px;margin:20px 0}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}.card{background:#202b38;padding:12px;border-radius:6px}.card strong{display:block;font-size:1.3em}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:.92em}th,td{text-align:left;padding:9px 7px;border-bottom:1px solid #364351;vertical-align:top}th{color:#b5beca}.key{font-family:monospace;overflow-wrap:anywhere}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:16px}.notice{padding:10px;background:#273947;border-radius:6px}.warning{color:#ffd3a3}.success{color:#a5e1b1}dl{display:grid;grid-template-columns:minmax(110px,1fr) 2fr;gap:8px}dt{color:#b5beca}dd{margin:0;overflow-wrap:anywhere}select{max-width:100%}.inline{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.inline label{display:inline}.inline input{width:auto;margin:0}fieldset{border:1px solid #526273;border-radius:6px;margin:14px 0;padding:12px}.small{font-size:.9em}
|
||||
#mail-panel fieldset,#mail-panel .grid>form{min-width:0}#mail-panel select{width:100%}
|
||||
</style></head><body>
|
||||
<h1 id="room-name">MeshCore Room</h1>
|
||||
<p class="muted">Chat and selected notices over local Wi-Fi. This page also works without internet access.</p>
|
||||
<p class="muted">Chat, personal mail and selected notices over local Wi-Fi. This page also works without internet access.</p>
|
||||
<form id="join"><label for="password">Room password (leave empty for public read-only access)</label>
|
||||
<input id="password" type="password" autocomplete="current-password" maxlength="64">
|
||||
<label for="name">Your display name</label><input id="name" autocomplete="nickname" value="Web">
|
||||
@@ -36,6 +37,26 @@ details{margin:18px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}a{color
|
||||
<p id="browser-catchup-result" class="muted" role="status"></p></details>
|
||||
<form id="compose"><label for="message">Message</label><textarea id="message"></textarea>
|
||||
<p id="budget" class="muted"></p><button id="send" type="submit">Send</button></form>
|
||||
<section class="panel" aria-labelledby="mail-heading"><h2 id="mail-heading">Personal mailbox</h2>
|
||||
<p class="muted">Mail waits on this room until you collect it. Your browser mailbox uses its own identity, separate from your radio.</p>
|
||||
<p id="mail-summary" class="notice" hidden></p>
|
||||
<button id="mail-open" type="button">Open my mailbox</button>
|
||||
<section id="mail-panel" hidden><p>Your complete mailbox address: <code id="mail-key" class="key"></code> <button id="mail-copy" type="button">Copy address</button></p>
|
||||
<p id="mail-state" class="notice" role="status"></p>
|
||||
<div class="grid"><form id="mail-policy"><fieldset><legend>Who can send you mail</legend>
|
||||
<label for="mail-mode">Mailbox access</label><select id="mail-mode"><option value="closed">Closed - receive no new mail</option><option value="public">Public - room writers may send</option><option value="private">Private - approved senders only</option></select>
|
||||
<label for="mail-allowlist">Approved sender addresses (up to 8 complete public keys, one per line)</label><textarea id="mail-allowlist" class="key" spellcheck="false" autocomplete="off"></textarea>
|
||||
<label class="inline"><input id="mail-only" type="checkbox"> Mailbox only: pause automatic chat downloads</label>
|
||||
<p class="muted small">A closed mailbox is the default. Reading mail leaves it queued; confirm receipt after a complete download to remove it from the server.</p>
|
||||
<button id="mail-policy-save" type="submit">Save mailbox settings</button><button id="mail-policy-reload" type="button">Reload settings</button><p id="mail-policy-result" role="status"></p></fieldset></form>
|
||||
<form id="mail-compose"><fieldset><legend>Send personal mail</legend><label for="mail-recipient">Recipient's complete mailbox address</label><input id="mail-recipient" class="key" maxlength="64" spellcheck="false" autocomplete="off">
|
||||
<label for="mail-text">Message (up to 512 UTF-8 bytes)</label><textarea id="mail-text"></textarea><p id="mail-budget" class="muted"></p>
|
||||
<button id="mail-send" type="submit">Send mail</button><p id="mail-send-result" role="status"></p></fieldset></form></div>
|
||||
<h3>Inbox</h3><button id="mail-refresh" type="button">Check and refresh inbox</button><p id="mail-count" role="status"></p>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">Sender</th><th scope="col">Sent</th><th scope="col">Receipt</th><th scope="col">Message</th></tr></thead><tbody id="mail-rows"></tbody></table></div>
|
||||
<div class="inline"><button id="mail-previous" type="button" disabled>Previous mail</button><button id="mail-next" type="button" disabled>Next mail</button><span id="mail-page" class="muted"></span></div>
|
||||
<section id="mail-selected" hidden><h3>Selected mail</h3><p id="mail-selected-meta" class="key"></p><pre id="mail-body" class="notice" style="white-space:pre-wrap;overflow-wrap:anywhere"></pre>
|
||||
<p id="mail-read-state" role="status"></p><button id="mail-resume" type="button">Read or resume download</button><button id="mail-ack" type="button" disabled>Confirm received and remove</button><button id="mail-delete" type="button">Delete this mail</button></section></section></section>
|
||||
<h2>Information board</h2><button id="refresh-board" type="button">Refresh notices</button>
|
||||
<div id="notices"></div><h3 id="article-title" hidden></h3><pre id="article" hidden></pre>
|
||||
<section id="editor" hidden><h3>Publish or edit a notice</h3><form id="publish">
|
||||
@@ -46,6 +67,14 @@ details{margin:18px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}a{color
|
||||
<button type="submit">Save notice</button><button id="delete" type="button">Delete selected notice</button></form></section>
|
||||
<section id="admin-panel" class="panel" hidden><h2>Room administration</h2>
|
||||
<p class="muted">Manage radio users, their room-to-user routes, and chat delivery. Activity and delivery details are available only with admin access.</p>
|
||||
<details id="admin-mail"><summary>Mailbox owners and delivery</summary><p class="muted">Review mailbox policies and counts. Private message bodies are available only to their recipients.</p><button id="admin-mail-refresh" type="button">Load mailbox owners</button><p id="admin-mail-state" role="status"></p>
|
||||
<label for="admin-mail-owner">Manage a radio or browser mailbox by its complete public key</label><input id="admin-mail-owner" class="key" maxlength="64" spellcheck="false" autocomplete="off"><button id="admin-mail-load-owner" type="button">Load mailbox by address</button><p class="muted small">A new address starts closed. Save its policy to create the mailbox.</p>
|
||||
<div class="table-wrap"><table><thead><tr><th scope="col">Complete owner address</th><th scope="col">Access</th><th scope="col">Mail</th><th scope="col">Manage</th></tr></thead><tbody id="admin-mail-rows"></tbody></table></div>
|
||||
<div class="inline"><button id="admin-mail-previous" type="button" disabled>Previous mailboxes</button><button id="admin-mail-next" type="button" disabled>Next mailboxes</button><span id="admin-mail-page" class="muted"></span></div>
|
||||
<form id="admin-mail-policy" hidden><fieldset><legend>Selected mailbox policy</legend><p id="admin-mail-key" class="key"></p><label for="admin-mail-mode">Mailbox access</label><select id="admin-mail-mode"><option value="closed">Closed</option><option value="public">Public</option><option value="private">Private</option></select>
|
||||
<label for="admin-mail-allowlist">Approved senders (up to 8 complete public keys, one per line)</label><textarea id="admin-mail-allowlist" class="key" spellcheck="false" autocomplete="off"></textarea>
|
||||
<label class="inline"><input id="admin-mail-only" type="checkbox"> Mailbox only</label><button id="admin-mail-save" type="submit">Save selected policy</button><button id="admin-mail-reload" type="button">Reload selected policy</button><button id="admin-mail-block" type="button">Block owner</button>
|
||||
<label for="admin-mail-delete-id">Message ID to delete</label><input id="admin-mail-delete-id" type="number" min="1" max="4294967295"><button id="admin-mail-delete" type="button">Review message deletion</button><button id="admin-mail-purge" type="button">Review inbox purge</button><p id="admin-mail-result" role="status"></p></fieldset></form></details>
|
||||
<div class="inline"><button id="admin-refresh" type="button">Load users and delivery</button><label><input id="admin-live" type="checkbox"> Refresh every 15 seconds</label></div>
|
||||
<p id="admin-state" role="status" class="muted">Load users to begin.</p>
|
||||
<div id="admin-cards" class="cards" hidden></div>
|
||||
@@ -74,6 +103,8 @@ let chain=Promise.resolve(), notices=new Map(), transfers=new Map();
|
||||
let sending=false, editId=1, editVersion=0;
|
||||
let adminLoaded=false, adminLoading=false, adminBusy=false, adminCursor=0, adminNext=null, adminPages=[];
|
||||
let selectedKey='', selectedUser=null, adminSettings=null;
|
||||
let mailPolicy=null,mailDirty=false,mailBusy=false,mailCursor=0,mailNext=null,mailPages=[],mailItems=new Map(),mailTransfers=new Map(),mailSelected=null,mailGeneration=0,mailboxOnly=false,mailSnapshot=0;
|
||||
let adminMailPolicy=null,adminMailDirty=false,adminMailBusy=false,adminMailCursor=0,adminMailNext=null,adminMailPages=[],adminMailSnapshot=0;
|
||||
const routeDirty={outpath:false,altpath:false},routeBaseline={outpath:'',altpath:''};
|
||||
function saved(key,fallback){try{return localStorage.getItem(key)||fallback}catch(e){return fallback}}
|
||||
function remember(key,value){try{localStorage.setItem(key,String(value))}catch(e){}}
|
||||
@@ -132,8 +163,10 @@ function updateBudget(){
|
||||
}
|
||||
async function status(){
|
||||
const result=await api('status');
|
||||
if(boot&&boot!==result.boot){after=0;$('posts').replaceChildren();transfers.clear();notices.clear();clearAdmin()}
|
||||
if(boot&&boot!==result.boot){after=0;$('posts').replaceChildren();transfers.clear();notices.clear();clearAdmin();clearMail()}
|
||||
if(role>result.role)clearMail();
|
||||
boot=result.boot;role=result.role;
|
||||
mailboxOnly=result.mailbox_only===true;updateMailSummary();
|
||||
$('room-name').textContent=result.name;$('topic').textContent=result.topic;
|
||||
$('web-key').textContent=result.web_key;
|
||||
$('history').textContent=result.persistent_history?'Radio retains its newest 32 posts across reboots.':'Radio history is in RAM and is lost on reboot.';
|
||||
@@ -141,10 +174,11 @@ async function status(){
|
||||
$('editor').hidden=role!==3;$('admin-panel').hidden=role!==3;
|
||||
if(role!==3)clearAdmin();updateAdminButtons();updateBudget();
|
||||
}
|
||||
async function refreshChat(){
|
||||
async function refreshChat(automatic=false){
|
||||
if(polling||!joined)return;polling=true;
|
||||
try{
|
||||
await status();
|
||||
if(automatic&&mailboxOnly)return;
|
||||
for(let i=0;i<32;i++){
|
||||
const result=await api('posts',{after:after}), post=result.post;if(!post)break;
|
||||
if(!Number.isInteger(post.timestamp)||post.timestamp<=after)throw Error('Invalid message cursor.');
|
||||
@@ -212,6 +246,7 @@ async function browserCatchup(mode){
|
||||
}
|
||||
function requireAdmin(){if(!joined||role!==3)throw Error('Admin permission required. Reconnect with the room admin password.');}
|
||||
function clearAdmin(){
|
||||
clearAdminMail();
|
||||
adminLoaded=false;adminCursor=0;adminNext=null;adminPages=[];selectedKey='';selectedUser=null;adminSettings=null;
|
||||
routeDirty.outpath=false;routeDirty.altpath=false;routeBaseline.outpath='';routeBaseline.altpath='';
|
||||
$('admin-user-rows').replaceChildren();$('admin-details').replaceChildren();$('admin-cards').replaceChildren();
|
||||
@@ -238,6 +273,7 @@ function updateAdminButtons(){
|
||||
$('admin-previous').disabled=locked||!adminPages.length;$('admin-next').disabled=locked||adminNext===null;
|
||||
for(const input of $('admin-panel').querySelectorAll('input,select,textarea'))if(input.id!=='admin-live')input.disabled=locked;
|
||||
for(const prefix of ['admin-out','admin-alt'])$(prefix+'-value').disabled=locked||$(prefix+'-mode').value!=='path';
|
||||
updateMailButtons();
|
||||
}
|
||||
function validKey(key){return typeof key==='string'&&/^[0-9a-fA-F]{64}$/.test(key)&&!/^0+$/.test(key);}
|
||||
function renderAdminCards(result){
|
||||
@@ -356,6 +392,176 @@ async function saveAdminSetting(which){
|
||||
await adminMutation(async()=>{await api('admin.'+which,values);await loadAdminSettings();},'Room '+which+' saved.');
|
||||
$('admin-settings-result').textContent='Saved. Changes are confirmed by the radio.';
|
||||
}
|
||||
function clearMail(){
|
||||
mailGeneration++;
|
||||
mailboxOnly=false;updateMailSummary();
|
||||
mailPolicy=null;mailDirty=false;mailCursor=0;mailNext=null;mailPages=[];mailSnapshot=0;mailItems.clear();mailTransfers.clear();mailSelected=null;
|
||||
$('mail-panel').hidden=true;$('mail-selected').hidden=true;$('mail-rows').replaceChildren();$('mail-key').textContent='';$('mail-body').textContent='';$('mail-selected-meta').textContent='';
|
||||
for(const id of ['mail-state','mail-policy-result','mail-send-result','mail-count','mail-page','mail-read-state'])$(id).textContent='';
|
||||
$('mail-mode').value='closed';$('mail-allowlist').value='';$('mail-only').checked=false;$('mail-recipient').value='';$('mail-text').value='';updateMailButtons();
|
||||
}
|
||||
function clearAdminMail(){
|
||||
adminMailPolicy=null;adminMailDirty=false;adminMailCursor=0;adminMailNext=null;adminMailPages=[];adminMailSnapshot=0;
|
||||
$('admin-mail-rows').replaceChildren();$('admin-mail-policy').hidden=true;$('admin-mail-key').textContent='';$('admin-mail-owner').value='';$('admin-mail-allowlist').value='';$('admin-mail-delete-id').value='';
|
||||
for(const id of ['admin-mail-state','admin-mail-page','admin-mail-result'])$(id).textContent='';updateMailButtons();
|
||||
}
|
||||
function requireMail(){if(!joined||![1,2,3].includes(role))throw Error('Connect to the room before opening mail.');}
|
||||
function updateMailSummary(){$('mail-summary').hidden=!mailboxOnly;$('mail-summary').textContent=mailboxOnly?'Mailbox only: automatic chat downloads are paused. Refresh chat downloads once.':'';}
|
||||
function mailApi(op,values={}){const generation=mailGeneration;return api(op,values).then(result=>{requireMail();if(generation!==mailGeneration)throw Error('Mailbox session changed; open your mailbox again.');return result;});}
|
||||
function policyValues(prefix){
|
||||
const mode=$(prefix+'mode').value,raw=$(prefix+'allowlist').value.trim();
|
||||
const allowlist=raw?raw.split(/[\s,]+/).map(key=>key.toLowerCase()):[];
|
||||
if(!['closed','public','private'].includes(mode)||allowlist.length>8||allowlist.some(key=>!validKey(key))||new Set(allowlist).size!==allowlist.length)throw Error('Choose up to 8 different complete nonzero public keys.');
|
||||
return {mode:mode,mailbox_only:$(prefix+'only').checked,allowlist:allowlist};
|
||||
}
|
||||
function checkedMailPolicy(result,owner){
|
||||
if(!result||!validKey(result.owner)||(owner&&result.owner.toLowerCase()!==owner.toLowerCase())||!Number.isInteger(result.revision)||result.revision<0
|
||||
||!['closed','public','private'].includes(result.mode)||!Array.isArray(result.allowlist)||result.allowlist.length>8||result.allowlist.some(key=>!validKey(key)))throw Error('Invalid mailbox settings; reload before editing.');
|
||||
return result;
|
||||
}
|
||||
function updateMailButtons(){
|
||||
const locked=!joined||mailBusy,writer=role===2||role===3,size=encoder.encode($('mail-text').value).length;
|
||||
$('mail-budget').textContent=size+' / 512 UTF-8 bytes'+(writer?'':' - read-only access cannot send mail');
|
||||
for(const button of $('mail-panel').querySelectorAll('button'))button.disabled=locked;
|
||||
$('mail-open').disabled=!joined||mailBusy;$('mail-send').disabled=locked||!writer||!validKey($('mail-recipient').value.trim())||size>512||!$('mail-text').value.trim();
|
||||
$('mail-previous').disabled=locked||!mailPages.length;$('mail-next').disabled=locked||mailNext===null;
|
||||
const transfer=mailSelected&&mailTransfers.get(mailSelected.id);
|
||||
$('mail-ack').disabled=locked||!mailSelected||!transfer||transfer.next!==mailSelected.length||!transfer.complete;
|
||||
$('mail-resume').disabled=locked||!mailSelected;$('mail-delete').disabled=locked||!mailSelected;
|
||||
const adminLocked=!joined||role!==3||adminBusy||adminLoading||adminMailBusy;
|
||||
for(const button of $('admin-mail').querySelectorAll('button'))button.disabled=adminLocked;
|
||||
for(const field of $('admin-mail').querySelectorAll('input,select,textarea'))field.disabled=adminLocked;
|
||||
$('admin-mail-previous').disabled=adminLocked||!adminMailPages.length;$('admin-mail-next').disabled=adminLocked||adminMailNext===null;
|
||||
}
|
||||
function renderMailPolicy(result,force=false){
|
||||
const previous=mailPolicy;checkedMailPolicy(result,$('web-key').textContent);
|
||||
mailboxOnly=result.mailbox_only===true;updateMailSummary();
|
||||
$('mail-key').textContent=result.owner;$('mail-panel').hidden=false;
|
||||
$('mail-state').textContent='Mailbox '+result.mode+'. '+(result.mailbox_only?'Automatic chat downloads are paused; Refresh chat still works.':'Automatic chat downloads are enabled.')+' Settings revision '+result.revision+'.';
|
||||
if(!mailDirty||force){mailPolicy=result;$('mail-mode').value=result.mode;$('mail-allowlist').value=result.allowlist.join('\n');$('mail-only').checked=result.mailbox_only;mailDirty=false;}
|
||||
else if(previous&&previous.revision!==result.revision)$('mail-policy-result').textContent='Settings changed on the radio. Your draft is preserved; reload before replacing them.';
|
||||
updateMailButtons();
|
||||
}
|
||||
async function loadMailSettings(force=false){
|
||||
requireMail();if(force&&mailDirty&&!confirm('Replace your unsaved mailbox settings with the current radio settings?'))return;
|
||||
const result=await mailApi('mail.settings');requireMail();renderMailPolicy(result,force);
|
||||
}
|
||||
async function openMailbox(){
|
||||
requireMail();if(mailBusy)return;mailBusy=true;updateMailButtons();
|
||||
try{await loadMailSettings();await refreshMail();}finally{mailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function saveMailPolicy(){
|
||||
requireMail();if(!mailPolicy)throw Error('Load your mailbox settings first.');if(mailBusy)return;
|
||||
const values=Object.assign(policyValues('mail-'),{expected_revision:mailPolicy.revision}),generation=connectionGeneration;
|
||||
mailBusy=true;updateMailButtons();$('mail-policy-result').textContent='Saving mailbox settings...';
|
||||
try{const result=await mailApi('mail.policy',values);requireMail();if(generation!==connectionGeneration)return;renderMailPolicy(result,true);$('mail-policy-result').textContent='Mailbox settings saved and confirmed.';}
|
||||
catch(error){$('mail-policy-result').textContent=String(error.message||error);throw error;}
|
||||
finally{mailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function sendMail(){
|
||||
requireMail();if(role!==2&&role!==3)throw Error('Read and write room access is required to send mail.');if(mailBusy)return;
|
||||
const recipient=$('mail-recipient').value.trim().toLowerCase(),text=$('mail-text').value;
|
||||
if(!validKey(recipient)||!text.trim()||encoder.encode(text).length>512)throw Error('Use a complete recipient address and a message up to 512 UTF-8 bytes.');
|
||||
mailBusy=true;updateMailButtons();$('mail-send-result').textContent='Waiting for the radio to save your mail...';
|
||||
try{const result=await mailApi('mail.send',{recipient:recipient,text:text});requireMail();
|
||||
if(result.ok!==true||!Number.isInteger(result.id)||result.id<1)throw Error('Mail was not confirmed; check before retrying.');
|
||||
if($('mail-text').value===text)$('mail-text').value='';$('mail-send-result').textContent='Mail '+result.id+' saved for '+recipient+'.';}
|
||||
catch(error){$('mail-send-result').textContent=String(error.message||error);throw error;}
|
||||
finally{mailBusy=false;updateMailButtons();}
|
||||
}
|
||||
function checkedMailItem(item){
|
||||
if(!item||!Number.isInteger(item.id)||item.id<1||!validKey(item.sender)||!Number.isInteger(item.created)||item.created<0||!Number.isInteger(item.length)||item.length<1||item.length>512)throw Error('Invalid inbox entry; refresh mail.');
|
||||
return item;
|
||||
}
|
||||
async function refreshMail(cursor=mailCursor){
|
||||
requireMail();const count=await mailApi('mail.check');requireMail();
|
||||
if(!Number.isInteger(count.total)||!Number.isInteger(count.unread))throw Error('Invalid mailbox counts.');
|
||||
$('mail-count').textContent=count.unread+' waiting for receipt; '+count.total+' queued messages.';
|
||||
const result=await mailApi('mail.list',{cursor:cursor,revision:cursor?mailSnapshot:0});requireMail();
|
||||
if(!Number.isInteger(result.revision)||result.revision<0||!Array.isArray(result.messages)||result.messages.length>16||(result.next!==null&&(!Number.isInteger(result.next)||result.next<=cursor)))throw Error('Invalid inbox page.');
|
||||
if(cursor&&result.revision!==mailSnapshot)throw Error('Mailbox changed; check and refresh the inbox before continuing.');
|
||||
const items=result.messages.map(checkedMailItem);mailCursor=cursor;mailNext=result.next;mailSnapshot=result.revision;mailItems=new Map(items.map(item=>[item.id,item]));$('mail-rows').replaceChildren();
|
||||
if(!items.length){const row=document.createElement('tr'),cell=document.createElement('td');cell.colSpan=4;cell.textContent='No mail on this page.';row.append(cell);$('mail-rows').append(row);}
|
||||
for(const item of items){const row=document.createElement('tr');
|
||||
for(const text of [item.sender,new Date(item.created*1000).toLocaleString(),'Waiting for receipt']){const cell=document.createElement('td');cell.textContent=text;if(text===item.sender)cell.className='key';row.append(cell);}
|
||||
const cell=document.createElement('td'),button=document.createElement('button');button.type='button';button.textContent='Read '+item.id+' ('+item.length+' bytes)';button.addEventListener('click',()=>openMail(item).catch(message));cell.append(button);row.append(cell);$('mail-rows').append(row);}
|
||||
$('mail-page').textContent='Page '+(mailPages.length+1);updateMailButtons();
|
||||
}
|
||||
async function openMail(item=mailSelected){
|
||||
requireMail();checkedMailItem(item);if(mailBusy)return;mailBusy=true;mailSelected=item;$('mail-selected').hidden=false;
|
||||
$('mail-selected-meta').textContent='Message '+item.id+' from '+item.sender+' - '+new Date(item.created*1000).toLocaleString();$('mail-body').textContent='';
|
||||
let transfer=mailTransfers.get(item.id);
|
||||
if(!transfer||transfer.sender!==item.sender||transfer.created!==item.created||transfer.bytes.length!==item.length){transfer={sender:item.sender,created:item.created,next:0,bytes:new Uint8Array(item.length),complete:false};mailTransfers.set(item.id,transfer);}
|
||||
updateMailButtons();
|
||||
try{while(transfer.next<item.length){
|
||||
$('mail-read-state').textContent='Downloaded '+transfer.next+' / '+item.length+' bytes. Receipt has not been confirmed.';
|
||||
const result=await mailApi('mail.read',{id:item.id,offset:transfer.next});requireMail();
|
||||
const bytes=Uint8Array.from(atob(result.data64),c=>c.charCodeAt(0));
|
||||
if(result.id!==item.id||result.sender!==item.sender||result.created!==item.created||result.length!==item.length||result.offset!==transfer.next||result.count!==bytes.length
|
||||
||!bytes.length||bytes.length>128||result.next!==transfer.next+bytes.length||result.next>item.length)throw Error('Mail changed or its download is invalid; refresh the inbox.');
|
||||
transfer.bytes.set(bytes,transfer.next);transfer.next=result.next;
|
||||
}
|
||||
const text=new TextDecoder('utf-8',{fatal:true}).decode(transfer.bytes);transfer.complete=true;$('mail-body').textContent=text;
|
||||
$('mail-read-state').textContent='Complete. Confirm receipt to remove the server copy, or keep it queued for later.';
|
||||
}catch(error){$('mail-read-state').textContent='Downloaded '+transfer.next+' / '+item.length+' bytes. '+String(error.message||error)+' Click Read or resume download to continue.';throw error;}
|
||||
finally{mailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function removeMail(received){
|
||||
requireMail();if(!mailSelected||mailBusy)return;const item=mailSelected,transfer=mailTransfers.get(item.id);
|
||||
if(received&&(!transfer||!transfer.complete))throw Error('Read the complete message before confirming receipt.');
|
||||
if(!confirm((received?'Confirm receipt and remove':'Delete without confirming receipt')+' for message '+item.id+'?'))return;
|
||||
mailBusy=true;updateMailButtons();
|
||||
try{const result=await mailApi(received?'mail.ack':'mail.delete',{id:item.id});requireMail();if(result.ok!==true)throw Error('Mail removal was not confirmed.');
|
||||
mailTransfers.delete(item.id);mailSelected=null;$('mail-body').textContent='';$('mail-selected').hidden=true;mailPages=[];await refreshMail(0);
|
||||
$('mail-count').textContent+=(received?' Receipt confirmed.':' Message deleted.');}
|
||||
finally{mailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function loadAdminMail(cursor=adminMailCursor){
|
||||
requireAdmin();if(adminMailBusy)return;adminMailBusy=true;updateMailButtons();
|
||||
try{const result=await api('admin.mail.list',{cursor:cursor,revision:cursor?adminMailSnapshot:0});requireAdmin();
|
||||
if(!Number.isInteger(result.revision)||result.revision<0||!Array.isArray(result.mailboxes)||result.mailboxes.length>16||(result.next!==null&&(!Number.isInteger(result.next)||result.next<=cursor)))throw Error('Invalid mailbox owner page.');
|
||||
if(cursor&&result.revision!==adminMailSnapshot)throw Error('Mailboxes changed; load mailbox owners again before continuing.');
|
||||
adminMailCursor=cursor;adminMailNext=result.next;adminMailSnapshot=result.revision;$('admin-mail-rows').replaceChildren();
|
||||
for(const owner of result.mailboxes){if(!validKey(owner.owner))throw Error('Invalid mailbox identity.');const row=document.createElement('tr');
|
||||
for(const text of [owner.owner,(owner.blocked?'Blocked; ':'')+owner.mode+' (revision '+owner.revision+')',owner.unread+' unread / '+owner.total+' queued']){const cell=document.createElement('td');cell.textContent=text;if(text===owner.owner)cell.className='key';row.append(cell);}
|
||||
const cell=document.createElement('td'),button=document.createElement('button');button.type='button';button.textContent='Manage policy';button.addEventListener('click',()=>selectAdminMail(owner.owner).catch(message));cell.append(button);row.append(cell);$('admin-mail-rows').append(row);}
|
||||
$('admin-mail-page').textContent='Page '+(adminMailPages.length+1);$('admin-mail-state').textContent=result.mailboxes.length?'Mailbox policies and counts loaded. No message bodies were downloaded.':'No configured mailboxes.';
|
||||
}finally{adminMailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function selectAdminMail(owner,force=false){
|
||||
requireAdmin();if(!validKey(owner))throw Error('Use a complete mailbox owner key.');
|
||||
if(adminMailDirty&&!confirm('Replace the unsaved selected mailbox policy?'))return;
|
||||
const result=await api('admin.mail.settings',{owner:owner});requireAdmin();adminMailPolicy=checkedMailPolicy(result,owner);adminMailDirty=false;
|
||||
$('admin-mail-key').textContent=result.owner;$('admin-mail-mode').value=result.mode;$('admin-mail-allowlist').value=result.allowlist.join('\n');$('admin-mail-only').checked=result.mailbox_only;
|
||||
$('admin-mail-block').textContent=result.blocked?'Unblock owner':'Block owner';$('admin-mail-delete-id').value='';$('admin-mail-result').textContent='Loaded policy revision '+result.revision+'.';$('admin-mail-policy').hidden=false;updateMailButtons();
|
||||
}
|
||||
async function saveAdminMailPolicy(){
|
||||
requireAdmin();if(!adminMailPolicy||adminMailBusy)return;const owner=adminMailPolicy.owner,values=Object.assign(policyValues('admin-mail-'),{owner:owner,expected_revision:adminMailPolicy.revision});
|
||||
if(!confirm('Save '+values.mode+' mailbox policy for '+owner+'?'))return;
|
||||
adminMailBusy=true;updateMailButtons();
|
||||
try{const result=await api('admin.mail.policy',values);requireAdmin();adminMailPolicy=checkedMailPolicy(result,owner);adminMailDirty=false;
|
||||
$('admin-mail-result').textContent='Policy saved and confirmed at revision '+result.revision+'.';if(mailPolicy&&mailPolicy.owner===owner)renderMailPolicy(result);}
|
||||
catch(error){$('admin-mail-result').textContent=String(error.message||error);throw error;}
|
||||
finally{adminMailBusy=false;updateMailButtons();}
|
||||
}
|
||||
async function deleteAdminMail(all=false){
|
||||
requireAdmin();if(!adminMailPolicy||adminMailBusy)return;const owner=adminMailPolicy.owner,value=$('admin-mail-delete-id').value,id=all?0:Number(value);
|
||||
if(!all&&(!/^\d+$/.test(value)||!Number.isInteger(id)||id<1||id>4294967295))throw Error('Enter a valid message ID.');
|
||||
if(!confirm((all?'Purge every queued message':'Delete queued message '+id)+' for mailbox '+owner+'?\nThis permanently removes server copies without confirming receipt.'))return;
|
||||
adminMailBusy=true;updateMailButtons();
|
||||
try{const result=await api('admin.mail.delete',{owner:owner,id:id});requireAdmin();if(result.ok!==true)throw Error('Mailbox deletion was not confirmed.');$('admin-mail-result').textContent=all?'Inbox purge confirmed.':'Message deletion confirmed.';
|
||||
if(mailPolicy&&mailPolicy.owner===owner){mailTransfers.clear();mailSelected=null;$('mail-body').textContent='';$('mail-selected').hidden=true;await refreshMail(0);}}
|
||||
finally{adminMailBusy=false;updateMailButtons();}
|
||||
await loadAdminMail();
|
||||
}
|
||||
async function blockAdminMail(){
|
||||
requireAdmin();if(!adminMailPolicy||adminMailBusy)return;const owner=adminMailPolicy.owner,banned=!adminMailPolicy.blocked;
|
||||
if(!confirm((banned?'Block ':'Unblock ')+owner+' for room access and mailbox operations?'))return;
|
||||
adminMailBusy=true;updateMailButtons();
|
||||
try{await api('admin.ban',{key:owner,banned:banned});requireAdmin();adminMailPolicy.blocked=banned;$('admin-mail-block').textContent=banned?'Unblock owner':'Block owner';$('admin-mail-result').textContent=banned?'Owner blocked for room access.':'Owner unblocked.';}
|
||||
finally{adminMailBusy=false;updateMailButtons();}
|
||||
await loadAdminMail();
|
||||
}
|
||||
async function openArticle(item){
|
||||
if(!Number.isInteger(item.length)||item.length<0||item.length>2048)throw Error("Article exceeds the radio's limit.");
|
||||
let transfer=transfers.get(item.id);
|
||||
@@ -383,7 +589,8 @@ async function openArticle(item){
|
||||
$('join').addEventListener('submit',async event=>{
|
||||
event.preventDefault();message('');
|
||||
connectionGeneration++;joined=false;role=0;clearAdmin();$('editor').hidden=true;$('admin-panel').hidden=true;$('room').hidden=true;updateBudget();
|
||||
try{makeIdentity();password=$('password').value;$('password').value='';await status();joined=true;$('room').hidden=false;updateBudget();await refreshChat();await refreshBoard()}
|
||||
clearMail();
|
||||
try{makeIdentity();password=$('password').value;$('password').value='';await status();joined=true;$('room').hidden=false;updateBudget();await refreshChat(true);await refreshBoard()}
|
||||
catch(e){message(e)}
|
||||
});
|
||||
$('name').value=saved('mc-room-name','Web');
|
||||
@@ -398,7 +605,37 @@ $('compose').addEventListener('submit',async event=>{
|
||||
$('refresh').addEventListener('click',()=>refreshChat().catch(message));
|
||||
$('disconnect').addEventListener('click',()=>{
|
||||
connectionGeneration++;joined=false;role=0;password='';clearAdmin();$('room').hidden=true;$('admin-panel').hidden=true;$('editor').hidden=true;$('state').textContent='Disconnected';updateBudget();
|
||||
clearMail();
|
||||
});
|
||||
$('mail-open').addEventListener('click',()=>openMailbox().catch(message));
|
||||
$('mail-copy').addEventListener('click',async()=>{
|
||||
try{requireMail();const key=$('mail-key').textContent;if(!validKey(key))throw Error('Open your mailbox first.');
|
||||
if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(key);
|
||||
else{const range=document.createRange();range.selectNodeContents($('mail-key'));const selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);if(!document.execCommand('copy'))throw Error('Select and copy the complete mailbox address above.');selection.removeAllRanges();}
|
||||
$('mail-state').textContent='Complete mailbox address copied.';
|
||||
}catch(error){message(error)}
|
||||
});
|
||||
for(const id of ['mail-mode','mail-only','mail-allowlist'])$(id).addEventListener(id==='mail-allowlist'?'input':'change',()=>{mailDirty=true});
|
||||
for(const id of ['mail-recipient','mail-text'])$(id).addEventListener('input',updateMailButtons);
|
||||
$('mail-policy').addEventListener('submit',event=>{event.preventDefault();saveMailPolicy().catch(message)});
|
||||
$('mail-policy-reload').addEventListener('click',()=>loadMailSettings(true).catch(message));
|
||||
$('mail-compose').addEventListener('submit',event=>{event.preventDefault();sendMail().catch(message)});
|
||||
$('mail-refresh').addEventListener('click',()=>{if(mailBusy)return;mailPages=[];refreshMail(0).catch(message)});
|
||||
$('mail-next').addEventListener('click',()=>{if(mailNext===null||mailBusy)return;const previous=mailCursor;mailPages.push(previous);refreshMail(mailNext).catch(error=>{mailPages.pop();message(error);updateMailButtons()})});
|
||||
$('mail-previous').addEventListener('click',()=>{if(!mailPages.length||mailBusy)return;const cursor=mailPages.pop();refreshMail(cursor).catch(error=>{mailPages.push(cursor);message(error);updateMailButtons()})});
|
||||
$('mail-resume').addEventListener('click',()=>openMail().catch(message));
|
||||
$('mail-ack').addEventListener('click',()=>removeMail(true).catch(message));
|
||||
$('mail-delete').addEventListener('click',()=>removeMail(false).catch(message));
|
||||
$('admin-mail-refresh').addEventListener('click',()=>{adminMailPages=[];loadAdminMail(0).catch(message)});
|
||||
$('admin-mail-load-owner').addEventListener('click',()=>selectAdminMail($('admin-mail-owner').value.trim().toLowerCase()).catch(message));
|
||||
$('admin-mail-next').addEventListener('click',()=>{if(adminMailNext===null||adminMailBusy)return;const previous=adminMailCursor;adminMailPages.push(previous);loadAdminMail(adminMailNext).catch(error=>{adminMailPages.pop();message(error);updateMailButtons()})});
|
||||
$('admin-mail-previous').addEventListener('click',()=>{if(!adminMailPages.length||adminMailBusy)return;const cursor=adminMailPages.pop();loadAdminMail(cursor).catch(error=>{adminMailPages.push(cursor);message(error);updateMailButtons()})});
|
||||
for(const id of ['admin-mail-mode','admin-mail-only','admin-mail-allowlist'])$(id).addEventListener(id==='admin-mail-allowlist'?'input':'change',()=>{adminMailDirty=true});
|
||||
$('admin-mail-policy').addEventListener('submit',event=>{event.preventDefault();saveAdminMailPolicy().catch(message)});
|
||||
$('admin-mail-reload').addEventListener('click',()=>{if(adminMailPolicy)selectAdminMail(adminMailPolicy.owner,true).catch(message)});
|
||||
$('admin-mail-delete').addEventListener('click',()=>deleteAdminMail(false).catch(message));
|
||||
$('admin-mail-purge').addEventListener('click',()=>deleteAdminMail(true).catch(message));
|
||||
$('admin-mail-block').addEventListener('click',()=>blockAdminMail().catch(message));
|
||||
$('browser-catchup-form').addEventListener('submit',event=>event.preventDefault());
|
||||
$('browser-skip-before').addEventListener('click',()=>browserCatchup('before').catch(message));
|
||||
$('browser-skip-number').addEventListener('click',()=>browserCatchup('keep').catch(message));
|
||||
@@ -449,7 +686,7 @@ $('delete').addEventListener('click',async()=>{
|
||||
try{await api('board.delete',{id:id,version:entry.version});transfers.delete(id);await refreshBoard();$('article').hidden=true;$('article-title').hidden=true}
|
||||
catch(e){message(e)}
|
||||
});
|
||||
setInterval(()=>{if(joined)refreshChat().catch(message);if(joined&&role===3&&adminLoaded&&$('admin-live').checked)loadAdmin().catch(message)},15000);
|
||||
setInterval(()=>{if(joined)refreshChat(true).catch(message);if(joined&&role===3&&adminLoaded&&$('admin-live').checked)loadAdmin().catch(message)},15000);
|
||||
updateBudget();
|
||||
updateAdminButtons();
|
||||
</script></body></html>)roomhtml";
|
||||
Reference in new issue
Block a user