gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita80da7bda80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmrea80da7bd/plugins/mpackdb/msgpack.zig

30.3 KB

  1. // MessagePack codec for hl:mpackdb — byte-compatible with npm msgpackr 1.11.5
  2. // as mpackdb v1.0.7 uses it (decision D12).
  3. //
  4. // Measured msgpackr surface (probed against the real library, see
  5. // testdata/gen_corpus.mjs):
  6. // - NO record/shared-structure extensions: the standalone pack() export
  7. // serializes plain objects as ordinary MessagePack maps.
  8. // - Objects ALWAYS encode as map16 (0xde) — even empty — never fixmap/map32.
  9. // Maps with > 65535 keys throw in msgpackr; we mirror with error.MapTooLarge.
  10. // - Numbers: integer-valued f64 in [-2^31, 2^32) uses the smallest
  11. // uint/int family (fixint, cc, cd, ce / negfixint, d0, d1, d2). Everything
  12. // else (non-integers, |v| outside that range, NaN, ±Inf) is float64 (0xcb).
  13. // msgpackr never emits float32 or int64/uint64 for JS numbers.
  14. // - Strings: fixstr ≤31 bytes, str8 ≤255, str16 ≤65535, str32 beyond.
  15. // - Arrays: fixarray ≤15, array16 ≤65535, array32 beyond.
  16. // - Binary: bin8/16/32 by length.
  17. // - undefined: fixext1 type 0x00 data 0x00 (d4 00 00) — kept as a distinct
  18. // Value so re-encode is byte-exact; it surfaces as null in Hybriel.
  19. // - Date: timestamp ext -1 (d6ff / d7ff / c70cff). Kept as a raw ext Value
  20. // for byte-exact round-trips; timestampMs() interprets it.
  21. //
  22. // Decode accepts the FULL MessagePack spec (all int/str/bin/array/map families,
  23. // float32, int64/uint64, all ext forms); encode emits only the canonical
  24. // msgpackr subset above.
  25. const std = @import("std");
  26. pub const Error = error{
  27. Truncated,
  28. InvalidFormat, // 0xc1
  29. MapTooLarge,
  30. OutOfMemory,
  31. };
  32. pub const Ext = struct {
  33. type: i8,
  34. data: []const u8,
  35. };
  36. pub const Entry = struct {
  37. key: Value,
  38. value: Value,
  39. };
  40. pub const Value = union(enum) {
  41. nil,
  42. undef, // msgpackr `undefined` (fixext1 type 0)
  43. boolean: bool,
  44. number: f64,
  45. str: []const u8,
  46. bin: []const u8,
  47. array: []Value,
  48. map: []Entry,
  49. ext: Ext,
  50. /// Interpret a timestamp ext (-1) as milliseconds since epoch.
  51. pub fn timestampMs(self: Value) ?f64 {
  52. if (self != .ext or self.ext.type != -1) return null;
  53. const d = self.ext.data;
  54. switch (d.len) {
  55. 4 => {
  56. const sec = std.mem.readInt(u32, d[0..4], .big);
  57. return @as(f64, @floatFromInt(sec)) * 1000.0;
  58. },
  59. 8 => {
  60. const packed_v = std.mem.readInt(u64, d[0..8], .big);
  61. const ns: f64 = @floatFromInt(packed_v >> 34);
  62. const sec: f64 = @floatFromInt(packed_v & 0x3ffffffff);
  63. return sec * 1000.0 + ns / 1_000_000.0;
  64. },
  65. 12 => {
  66. const ns = std.mem.readInt(u32, d[0..4], .big);
  67. const sec = std.mem.readInt(i64, d[4..12], .big);
  68. return @as(f64, @floatFromInt(sec)) * 1000.0 + @as(f64, @floatFromInt(ns)) / 1_000_000.0;
  69. },
  70. else => return null,
  71. }
  72. }
  73. /// Map field lookup by string key (returns null for missing / non-map).
  74. pub fn get(self: Value, key: []const u8) ?Value {
  75. if (self != .map) return null;
  76. for (self.map) |e| {
  77. if (e.key == .str and std.mem.eql(u8, e.key.str, key)) return e.value;
  78. }
  79. return null;
  80. }
  81. };
  82. pub const Decoded = struct {
  83. value: Value,
  84. len: usize, // bytes consumed
  85. };
  86. /// Decode one MessagePack value from `bytes`. All slices in the returned Value
  87. /// reference memory allocated from `alloc` (str/bin/ext data are duplicated,
  88. /// so the Value outlives `bytes`). Use an arena and free it wholesale.
  89. pub fn decode(alloc: std.mem.Allocator, bytes: []const u8) Error!Decoded {
  90. var d = Decoder{ .alloc = alloc, .bytes = bytes, .pos = 0 };
  91. const v = try d.readValue();
  92. return .{ .value = v, .len = d.pos };
  93. }
  94. const Decoder = struct {
  95. alloc: std.mem.Allocator,
  96. bytes: []const u8,
  97. pos: usize,
  98. fn need(self: *Decoder, n: usize) Error!void {
  99. if (self.pos + n > self.bytes.len) return Error.Truncated;
  100. }
  101. fn take(self: *Decoder, n: usize) Error![]const u8 {
  102. try self.need(n);
  103. const s = self.bytes[self.pos .. self.pos + n];
  104. self.pos += n;
  105. return s;
  106. }
  107. fn readBigInt(self: *Decoder, comptime T: type) Error!T {
  108. const n = @divExact(@typeInfo(T).int.bits, 8);
  109. const s = try self.take(n);
  110. return std.mem.readInt(T, s[0..n], .big);
  111. }
  112. fn dupSlice(self: *Decoder, n: usize) Error![]const u8 {
  113. const s = try self.take(n);
  114. return self.alloc.dupe(u8, s) catch return Error.OutOfMemory;
  115. }
  116. fn readArray(self: *Decoder, n: usize) Error!Value {
  117. const items = self.alloc.alloc(Value, n) catch return Error.OutOfMemory;
  118. for (items) |*it| it.* = try self.readValue();
  119. return .{ .array = items };
  120. }
  121. fn readMap(self: *Decoder, n: usize) Error!Value {
  122. const entries = self.alloc.alloc(Entry, n) catch return Error.OutOfMemory;
  123. for (entries) |*e| {
  124. e.key = try self.readValue();
  125. e.value = try self.readValue();
  126. }
  127. return .{ .map = entries };
  128. }
  129. fn readExt(self: *Decoder, n: usize) Error!Value {
  130. try self.need(1 + n);
  131. const t: i8 = @bitCast(self.bytes[self.pos]);
  132. self.pos += 1;
  133. const data = try self.dupSlice(n);
  134. // msgpackr undefined: fixext1 type 0, data byte 0
  135. if (t == 0 and n == 1 and data[0] == 0) return .undef;
  136. return .{ .ext = .{ .type = t, .data = data } };
  137. }
  138. /// Walk one value without building it: the checks `readValue` makes (a short buffer, 0xc1).
  139. fn skipValue(self: *Decoder) Error!void {
  140. var pending: usize = 1;
  141. while (pending > 0) {
  142. pending -= 1;
  143. try self.need(1);
  144. const b = self.bytes[self.pos];
  145. self.pos += 1;
  146. switch (b) {
  147. 0x00...0x7f, 0xc0, 0xc2, 0xc3, 0xe0...0xff => {},
  148. 0x80...0x8f => pending += 2 * @as(usize, b & 0x0f),
  149. 0x90...0x9f => pending += b & 0x0f,
  150. 0xa0...0xbf => _ = try self.take(b & 0x1f),
  151. 0xc1 => return Error.InvalidFormat,
  152. 0xc4, 0xd9 => _ = try self.take(try self.readBigInt(u8)),
  153. 0xc5, 0xda => _ = try self.take(try self.readBigInt(u16)),
  154. 0xc6, 0xdb => _ = try self.take(try self.readBigInt(u32)),
  155. 0xc7 => _ = try self.take(1 + @as(usize, try self.readBigInt(u8))),
  156. 0xc8 => _ = try self.take(1 + @as(usize, try self.readBigInt(u16))),
  157. 0xc9 => _ = try self.take(1 + @as(usize, try self.readBigInt(u32))),
  158. 0xca, 0xce, 0xd2 => _ = try self.take(4),
  159. 0xcb, 0xcf, 0xd3 => _ = try self.take(8),
  160. 0xcc, 0xd0 => _ = try self.take(1),
  161. 0xcd, 0xd1 => _ = try self.take(2),
  162. 0xd4 => _ = try self.take(2),
  163. 0xd5 => _ = try self.take(3),
  164. 0xd6 => _ = try self.take(5),
  165. 0xd7 => _ = try self.take(9),
  166. 0xd8 => _ = try self.take(17),
  167. 0xdc => pending += try self.readBigInt(u16),
  168. 0xdd => pending += try self.readBigInt(u32),
  169. 0xde => pending += 2 * @as(usize, try self.readBigInt(u16)),
  170. 0xdf => pending += 2 * @as(usize, try self.readBigInt(u32)),
  171. }
  172. }
  173. }
  174. fn readValue(self: *Decoder) Error!Value {
  175. try self.need(1);
  176. const b = self.bytes[self.pos];
  177. self.pos += 1;
  178. switch (b) {
  179. 0x00...0x7f => return .{ .number = @floatFromInt(b) },
  180. 0x80...0x8f => return self.readMap(b & 0x0f),
  181. 0x90...0x9f => return self.readArray(b & 0x0f),
  182. 0xa0...0xbf => return .{ .str = try self.dupSlice(b & 0x1f) },
  183. 0xc0 => return .nil,
  184. 0xc1 => return Error.InvalidFormat,
  185. 0xc2 => return .{ .boolean = false },
  186. 0xc3 => return .{ .boolean = true },
  187. 0xc4 => return .{ .bin = try self.dupSlice(try self.readBigInt(u8)) },
  188. 0xc5 => return .{ .bin = try self.dupSlice(try self.readBigInt(u16)) },
  189. 0xc6 => return .{ .bin = try self.dupSlice(try self.readBigInt(u32)) },
  190. 0xc7 => return self.readExt(try self.readBigInt(u8)),
  191. 0xc8 => return self.readExt(try self.readBigInt(u16)),
  192. 0xc9 => return self.readExt(try self.readBigInt(u32)),
  193. 0xca => {
  194. const bits = try self.readBigInt(u32);
  195. return .{ .number = @as(f32, @bitCast(bits)) };
  196. },
  197. 0xcb => {
  198. const bits = try self.readBigInt(u64);
  199. return .{ .number = @bitCast(bits) };
  200. },
  201. 0xcc => return .{ .number = @floatFromInt(try self.readBigInt(u8)) },
  202. 0xcd => return .{ .number = @floatFromInt(try self.readBigInt(u16)) },
  203. 0xce => return .{ .number = @floatFromInt(try self.readBigInt(u32)) },
  204. 0xcf => return .{ .number = @floatFromInt(try self.readBigInt(u64)) },
  205. 0xd0 => return .{ .number = @floatFromInt(@as(i8, @bitCast(try self.readBigInt(u8)))) },
  206. 0xd1 => return .{ .number = @floatFromInt(@as(i16, @bitCast(try self.readBigInt(u16)))) },
  207. 0xd2 => return .{ .number = @floatFromInt(@as(i32, @bitCast(try self.readBigInt(u32)))) },
  208. 0xd3 => return .{ .number = @floatFromInt(@as(i64, @bitCast(try self.readBigInt(u64)))) },
  209. 0xd4 => return self.readExt(1),
  210. 0xd5 => return self.readExt(2),
  211. 0xd6 => return self.readExt(4),
  212. 0xd7 => return self.readExt(8),
  213. 0xd8 => return self.readExt(16),
  214. 0xd9 => return .{ .str = try self.dupSlice(try self.readBigInt(u8)) },
  215. 0xda => return .{ .str = try self.dupSlice(try self.readBigInt(u16)) },
  216. 0xdb => return .{ .str = try self.dupSlice(try self.readBigInt(u32)) },
  217. 0xdc => return self.readArray(try self.readBigInt(u16)),
  218. 0xdd => return self.readArray(try self.readBigInt(u32)),
  219. 0xde => return self.readMap(try self.readBigInt(u16)),
  220. 0xdf => return self.readMap(try self.readBigInt(u32)),
  221. 0xe0...0xff => return .{ .number = @floatFromInt(@as(i8, @bitCast(b))) },
  222. }
  223. }
  224. };
  225. /// MISSION 436: decode only some top-level fields of a record. `bytes` is one msgpack value;
  226. /// `out[i]` becomes the value of the FIRST entry of that map whose key is the string `names[i]`
  227. /// (what `Value.get` returns for the fully decoded record), or null when there is none or the
  228. /// value is not a map. Every other value is skipped without being built, but the whole value
  229. /// is walked: an invalid or truncated part fails exactly where `decode` fails.
  230. pub fn decodeFields(alloc: std.mem.Allocator, bytes: []const u8, names: []const []const u8, out: []?Value) Error!void {
  231. for (out) |*o| o.* = null;
  232. var d = Decoder{ .alloc = alloc, .bytes = bytes, .pos = 0 };
  233. try d.need(1);
  234. const b = bytes[0];
  235. const n: usize = switch (b) {
  236. 0x80...0x8f => b & 0x0f,
  237. 0xde => blk: {
  238. d.pos = 1;
  239. break :blk try d.readBigInt(u16);
  240. },
  241. 0xdf => blk: {
  242. d.pos = 1;
  243. break :blk try d.readBigInt(u32);
  244. },
  245. else => {
  246. try d.skipValue(); // not a map: no fields, but still a value that must decode
  247. return;
  248. },
  249. };
  250. if (b >= 0x80 and b <= 0x8f) d.pos = 1;
  251. var i: usize = 0;
  252. while (i < n) : (i += 1) {
  253. // the key: a string is compared in place, anything else is skipped
  254. try d.need(1);
  255. const kb = bytes[d.pos];
  256. const klen: ?usize = switch (kb) {
  257. 0xa0...0xbf => blk: {
  258. d.pos += 1;
  259. break :blk kb & 0x1f;
  260. },
  261. 0xd9 => blk: {
  262. d.pos += 1;
  263. break :blk try d.readBigInt(u8);
  264. },
  265. 0xda => blk: {
  266. d.pos += 1;
  267. break :blk try d.readBigInt(u16);
  268. },
  269. 0xdb => blk: {
  270. d.pos += 1;
  271. break :blk try d.readBigInt(u32);
  272. },
  273. else => null,
  274. };
  275. var hit: ?usize = null;
  276. if (klen) |kl| {
  277. const ks = try d.take(kl);
  278. for (names, 0..) |nm, j| {
  279. if (out[j] == null and std.mem.eql(u8, nm, ks)) {
  280. hit = j;
  281. break;
  282. }
  283. }
  284. } else {
  285. try d.skipValue();
  286. }
  287. if (hit) |j| {
  288. out[j] = try d.readValue();
  289. } else {
  290. try d.skipValue();
  291. }
  292. }
  293. }
  294. /// Encode a Value in the canonical msgpackr form (see header comment).
  295. pub fn encode(alloc: std.mem.Allocator, value: Value) Error![]u8 {
  296. var buf: std.ArrayList(u8) = .empty;
  297. errdefer buf.deinit(alloc);
  298. try encodeInto(alloc, &buf, value);
  299. return buf.toOwnedSlice(alloc) catch Error.OutOfMemory;
  300. }
  301. pub fn encodeInto(alloc: std.mem.Allocator, buf: *std.ArrayList(u8), value: Value) Error!void {
  302. const w = Writer{ .alloc = alloc, .buf = buf };
  303. try w.writeValue(value);
  304. }
  305. const Writer = struct {
  306. alloc: std.mem.Allocator,
  307. buf: *std.ArrayList(u8),
  308. fn byte(self: Writer, b: u8) Error!void {
  309. self.buf.append(self.alloc, b) catch return Error.OutOfMemory;
  310. }
  311. fn raw(self: Writer, s: []const u8) Error!void {
  312. self.buf.appendSlice(self.alloc, s) catch return Error.OutOfMemory;
  313. }
  314. fn big(self: Writer, comptime T: type, v: T) Error!void {
  315. var tmp: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined;
  316. std.mem.writeInt(T, &tmp, v, .big);
  317. try self.raw(&tmp);
  318. }
  319. fn writeNumber(self: Writer, v: f64) Error!void {
  320. // msgpackr rule (measured): integer-valued and within [-2^31, 2^32) →
  321. // smallest int family; else float64. -0 encodes as fixint 0.
  322. if (v == @floor(v) and v >= -2147483648.0 and v <= 4294967295.0) {
  323. if (v >= 0) {
  324. const u: u32 = @intFromFloat(v);
  325. if (u < 0x80) return self.byte(@intCast(u));
  326. if (u <= 0xff) {
  327. try self.byte(0xcc);
  328. return self.byte(@intCast(u));
  329. }
  330. if (u <= 0xffff) {
  331. try self.byte(0xcd);
  332. return self.big(u16, @intCast(u));
  333. }
  334. try self.byte(0xce);
  335. return self.big(u32, u);
  336. } else {
  337. const i: i32 = @intFromFloat(v);
  338. if (i >= -32) return self.byte(@bitCast(@as(i8, @intCast(i))));
  339. if (i >= -128) {
  340. try self.byte(0xd0);
  341. return self.byte(@bitCast(@as(i8, @intCast(i))));
  342. }
  343. if (i >= -32768) {
  344. try self.byte(0xd1);
  345. return self.big(u16, @bitCast(@as(i16, @intCast(i))));
  346. }
  347. try self.byte(0xd2);
  348. return self.big(u32, @bitCast(i));
  349. }
  350. }
  351. try self.byte(0xcb);
  352. return self.big(u64, @bitCast(v));
  353. }
  354. fn writeStr(self: Writer, s: []const u8) Error!void {
  355. if (s.len <= 31) {
  356. try self.byte(0xa0 | @as(u8, @intCast(s.len)));
  357. } else if (s.len <= 0xff) {
  358. try self.byte(0xd9);
  359. try self.byte(@intCast(s.len));
  360. } else if (s.len <= 0xffff) {
  361. try self.byte(0xda);
  362. try self.big(u16, @intCast(s.len));
  363. } else {
  364. try self.byte(0xdb);
  365. try self.big(u32, @intCast(s.len));
  366. }
  367. return self.raw(s);
  368. }
  369. fn writeValue(self: Writer, value: Value) Error!void {
  370. switch (value) {
  371. .nil => try self.byte(0xc0),
  372. .undef => try self.raw(&[_]u8{ 0xd4, 0x00, 0x00 }),
  373. .boolean => |b| try self.byte(if (b) 0xc3 else 0xc2),
  374. .number => |n| try self.writeNumber(n),
  375. .str => |s| try self.writeStr(s),
  376. .bin => |s| {
  377. if (s.len <= 0xff) {
  378. try self.byte(0xc4);
  379. try self.byte(@intCast(s.len));
  380. } else if (s.len <= 0xffff) {
  381. try self.byte(0xc5);
  382. try self.big(u16, @intCast(s.len));
  383. } else {
  384. try self.byte(0xc6);
  385. try self.big(u32, @intCast(s.len));
  386. }
  387. try self.raw(s);
  388. },
  389. .array => |items| {
  390. if (items.len <= 15) {
  391. try self.byte(0x90 | @as(u8, @intCast(items.len)));
  392. } else if (items.len <= 0xffff) {
  393. try self.byte(0xdc);
  394. try self.big(u16, @intCast(items.len));
  395. } else {
  396. try self.byte(0xdd);
  397. try self.big(u32, @intCast(items.len));
  398. }
  399. for (items) |it| try self.writeValue(it);
  400. },
  401. .map => |entries| {
  402. // msgpackr: objects are ALWAYS map16, >65535 keys throws.
  403. if (entries.len > 0xffff) return Error.MapTooLarge;
  404. try self.byte(0xde);
  405. try self.big(u16, @intCast(entries.len));
  406. for (entries) |e| {
  407. try self.writeValue(e.key);
  408. try self.writeValue(e.value);
  409. }
  410. },
  411. .ext => |e| {
  412. switch (e.data.len) {
  413. 1 => try self.byte(0xd4),
  414. 2 => try self.byte(0xd5),
  415. 4 => try self.byte(0xd6),
  416. 8 => try self.byte(0xd7),
  417. 16 => try self.byte(0xd8),
  418. else => {
  419. if (e.data.len <= 0xff) {
  420. try self.byte(0xc7);
  421. try self.byte(@intCast(e.data.len));
  422. } else if (e.data.len <= 0xffff) {
  423. try self.byte(0xc8);
  424. try self.big(u16, @intCast(e.data.len));
  425. } else {
  426. try self.byte(0xc9);
  427. try self.big(u32, @intCast(e.data.len));
  428. }
  429. },
  430. }
  431. try self.byte(@bitCast(e.type));
  432. try self.raw(e.data);
  433. },
  434. }
  435. }
  436. };
  437. // =========================================================================
  438. // mpackdb record framing: [4-byte LE total size incl. prefix][msgpack]
  439. // =========================================================================
  440. /// Serialize a value with mpackdb's 4-byte little-endian length prefix.
  441. pub fn serialize(alloc: std.mem.Allocator, value: Value) Error![]u8 {
  442. var buf: std.ArrayList(u8) = .empty;
  443. errdefer buf.deinit(alloc);
  444. buf.appendSlice(alloc, &[_]u8{ 0, 0, 0, 0 }) catch return Error.OutOfMemory;
  445. try encodeInto(alloc, &buf, value);
  446. const total: u32 = @intCast(buf.items.len);
  447. std.mem.writeInt(u32, buf.items[0..4], total, .little);
  448. return buf.toOwnedSlice(alloc) catch Error.OutOfMemory;
  449. }
  450. /// Read the length prefix of a framed record (total size incl. the 4 bytes).
  451. pub fn readSize(bytes: []const u8) Error!u32 {
  452. if (bytes.len < 4) return Error.Truncated;
  453. return std.mem.readInt(u32, bytes[0..4], .little);
  454. }
  455. /// Deserialize a framed record ([4-byte LE size][msgpack]).
  456. pub fn deserializeFramed(alloc: std.mem.Allocator, bytes: []const u8) Error!Value {
  457. const total = try readSize(bytes);
  458. if (total < 5 or total > bytes.len) return Error.Truncated;
  459. const d = try decode(alloc, bytes[4..total]);
  460. return d.value;
  461. }
  462. // =========================================================================
  463. // Tests
  464. // =========================================================================
  465. const testing = std.testing;
  466. /// Linux-syscall file read (plugins avoid std.Io plumbing; same pattern as
  467. /// plugins/fs/fs.zig). Returns null when the file cannot be opened.
  468. fn readFileLinux(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
  469. const linux = std.os.linux;
  470. const path_z = alloc.dupeZ(u8, path) catch return null;
  471. defer alloc.free(path_z);
  472. const rc = linux.open(path_z, .{}, 0);
  473. const fd: i32 = @bitCast(@as(u32, @truncate(rc)));
  474. if (fd < 0) return null;
  475. defer _ = linux.close(fd);
  476. var content: std.ArrayList(u8) = .empty;
  477. var buf: [65536]u8 = undefined;
  478. while (true) {
  479. const n = linux.read(fd, &buf, buf.len);
  480. if (@as(isize, @bitCast(n)) <= 0) break;
  481. content.appendSlice(alloc, buf[0..n]) catch return null;
  482. }
  483. return content.toOwnedSlice(alloc) catch null;
  484. }
  485. test "corpus: decode + canonical re-encode is byte-identical (msgpackr 1.11.5)" {
  486. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  487. defer arena.deinit();
  488. const alloc = arena.allocator();
  489. // Corpus lives next to this file; zig build test runs with cwd native/.
  490. const candidates = [_][]const u8{
  491. "../plugins/mpackdb/testdata/corpus.json",
  492. "plugins/mpackdb/testdata/corpus.json",
  493. };
  494. var content: ?[]u8 = null;
  495. for (candidates) |p| {
  496. content = readFileLinux(alloc, p) orelse continue;
  497. break;
  498. }
  499. const json = content orelse return error.CorpusNotFound;
  500. const parsed = try std.json.parseFromSlice(std.json.Value, alloc, json, .{});
  501. const arr = parsed.value.array;
  502. try testing.expect(arr.items.len >= 70);
  503. var checked: usize = 0;
  504. for (arr.items) |item| {
  505. const obj = item.object;
  506. const hex = obj.get("hex").?.string;
  507. const framed = if (obj.get("framed")) |f| f.bool else false;
  508. const bytes = try alloc.alloc(u8, hex.len / 2);
  509. _ = try std.fmt.hexToBytes(bytes, hex);
  510. if (framed) {
  511. // Frame round-trip: parse prefix, decode, re-serialize, compare all.
  512. const total = try readSize(bytes);
  513. try testing.expectEqual(bytes.len, @as(usize, total));
  514. const v = try deserializeFramed(alloc, bytes);
  515. const re = try serialize(alloc, v);
  516. try testing.expectEqualSlices(u8, bytes, re);
  517. } else {
  518. const d = try decode(alloc, bytes);
  519. try testing.expectEqual(bytes.len, d.len);
  520. const re = try encode(alloc, d.value);
  521. try testing.expectEqualSlices(u8, bytes, re);
  522. }
  523. checked += 1;
  524. }
  525. try testing.expect(checked == arr.items.len);
  526. }
  527. test "decode spot checks" {
  528. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  529. defer arena.deinit();
  530. const alloc = arena.allocator();
  531. // {name:'Alice', age:30} as msgpackr encodes it (map16)
  532. var bytes: [19]u8 = undefined;
  533. _ = try std.fmt.hexToBytes(&bytes, "de0002a46e616d65a5416c696365a36167651e");
  534. const d = try decode(alloc, &bytes);
  535. const name = d.value.get("name").?;
  536. try testing.expectEqualStrings("Alice", name.str);
  537. try testing.expectEqual(@as(f64, 30), d.value.get("age").?.number);
  538. }
  539. test "decode non-canonical families (full spec)" {
  540. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  541. defer arena.deinit();
  542. const alloc = arena.allocator();
  543. // fixmap {a:1}
  544. var b1: [4]u8 = undefined;
  545. _ = try std.fmt.hexToBytes(&b1, "81a16101");
  546. const v1 = try decode(alloc, &b1);
  547. try testing.expectEqual(@as(f64, 1), v1.value.get("a").?.number);
  548. // map32 {a:1}
  549. var b2: [8]u8 = undefined;
  550. _ = try std.fmt.hexToBytes(&b2, "df00000001a16101");
  551. const v2 = try decode(alloc, &b2);
  552. try testing.expectEqual(@as(f64, 1), v2.value.get("a").?.number);
  553. // int64 -1 (d3 ffffffffffffffff)
  554. var b3: [9]u8 = undefined;
  555. _ = try std.fmt.hexToBytes(&b3, "d3ffffffffffffffff");
  556. const v3 = try decode(alloc, &b3);
  557. try testing.expectEqual(@as(f64, -1), v3.value.number);
  558. // uint64 2^32 (cf 0000000100000000)
  559. var b4: [9]u8 = undefined;
  560. _ = try std.fmt.hexToBytes(&b4, "cf0000000100000000");
  561. const v4 = try decode(alloc, &b4);
  562. try testing.expectEqual(@as(f64, 4294967296), v4.value.number);
  563. // float32 0.5 (ca 3f000000)
  564. var b5: [5]u8 = undefined;
  565. _ = try std.fmt.hexToBytes(&b5, "ca3f000000");
  566. const v5 = try decode(alloc, &b5);
  567. try testing.expectEqual(@as(f64, 0.5), v5.value.number);
  568. // 0xc1 is invalid
  569. const bad = [_]u8{0xc1};
  570. try testing.expectError(Error.InvalidFormat, decode(alloc, &bad));
  571. }
  572. test "undefined is distinct and byte-exact" {
  573. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  574. defer arena.deinit();
  575. const alloc = arena.allocator();
  576. const bytes = [_]u8{ 0xd4, 0x00, 0x00 };
  577. const d = try decode(alloc, &bytes);
  578. try testing.expect(d.value == .undef);
  579. const re = try encode(alloc, d.value);
  580. try testing.expectEqualSlices(u8, &bytes, re);
  581. }
  582. test "timestamp ext interpretation" {
  583. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  584. defer arena.deinit();
  585. const alloc = arena.allocator();
  586. // date whole sec: d6 ff 66a39486 → 1721996422000 ms
  587. var b: [6]u8 = undefined;
  588. _ = try std.fmt.hexToBytes(&b, "d6ff66a39486");
  589. const d = try decode(alloc, &b);
  590. try testing.expectEqual(@as(f64, 1721996422000), d.value.timestampMs().?);
  591. // date ms: d7 ff 1d53530066a39486 → 1721996422123 ms
  592. var b2: [10]u8 = undefined;
  593. _ = try std.fmt.hexToBytes(&b2, "d7ff1d53530066a39486");
  594. const d2 = try decode(alloc, &b2);
  595. try testing.expectApproxEqAbs(@as(f64, 1721996422123), d2.value.timestampMs().?, 0.001);
  596. }
  597. test "framing" {
  598. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  599. defer arena.deinit();
  600. const alloc = arena.allocator();
  601. var entries = [_]Entry{
  602. .{ .key = .{ .str = "id" }, .value = .{ .number = 1 } },
  603. };
  604. const v = Value{ .map = &entries };
  605. const framed = try serialize(alloc, v);
  606. try testing.expectEqual(@as(u32, @intCast(framed.len)), try readSize(framed));
  607. const back = try deserializeFramed(alloc, framed);
  608. try testing.expectEqual(@as(f64, 1), back.get("id").?.number);
  609. }
  610. test "encode number boundaries match msgpackr" {
  611. var arena = std.heap.ArenaAllocator.init(testing.allocator);
  612. defer arena.deinit();
  613. const alloc = arena.allocator();
  614. const cases = [_]struct { v: f64, hex: []const u8 }{
  615. .{ .v = 0, .hex = "00" },
  616. .{ .v = 127, .hex = "7f" },
  617. .{ .v = 128, .hex = "cc80" },
  618. .{ .v = 256, .hex = "cd0100" },
  619. .{ .v = 65536, .hex = "ce00010000" },
  620. .{ .v = 2147483648, .hex = "ce80000000" },
  621. .{ .v = 4294967296, .hex = "cb41f0000000000000" },
  622. .{ .v = -1, .hex = "ff" },
  623. .{ .v = -32, .hex = "e0" },
  624. .{ .v = -33, .hex = "d0df" },
  625. .{ .v = -129, .hex = "d1ff7f" },
  626. .{ .v = -32769, .hex = "d2ffff7fff" },
  627. .{ .v = -2147483648, .hex = "d280000000" },
  628. .{ .v = -2147483649, .hex = "cbc1e0000000200000" },
  629. .{ .v = 0.5, .hex = "cb3fe0000000000000" },
  630. };
  631. for (cases) |c| {
  632. const enc = try encode(alloc, Value{ .number = c.v });
  633. const expect_bytes = try alloc.alloc(u8, c.hex.len / 2);
  634. _ = try std.fmt.hexToBytes(expect_bytes, c.hex);
  635. try testing.expectEqualSlices(u8, expect_bytes, enc);
  636. }
  637. }
  638. // =========================================================================
  639. // Mission 436: decodeFields gives what decode + Value.get give
  640. // =========================================================================
  641. fn randValue(r: std.Random, arena: std.mem.Allocator, depth: u8) error{OutOfMemory}!Value {
  642. const kinds: u8 = if (depth > 3) 6 else 9;
  643. return switch (r.uintLessThan(u8, kinds)) {
  644. 0 => .nil,
  645. 1 => .{ .boolean = r.boolean() },
  646. 2 => .{ .number = @floatFromInt(r.int(i32)) },
  647. 3 => .{ .number = @as(f64, @floatFromInt(r.int(u16))) / 7.0 },
  648. 4 => blk: {
  649. const n = r.uintLessThan(usize, 40);
  650. const b = try arena.alloc(u8, n);
  651. for (b) |*c| c.* = 'a' + r.uintLessThan(u8, 26);
  652. break :blk .{ .str = b };
  653. },
  654. 5 => .{ .bin = try arena.dupe(u8, "\x01\x02\x03") },
  655. 6 => blk: {
  656. const n = r.uintLessThan(usize, 4);
  657. const items = try arena.alloc(Value, n);
  658. for (items) |*it| it.* = try randValue(r, arena, depth + 1);
  659. break :blk .{ .array = items };
  660. },
  661. 7 => try randMap(r, arena, depth + 1),
  662. else => .{ .ext = .{ .type = -1, .data = try arena.dupe(u8, "\x00\x00\x00\x01") } },
  663. };
  664. }
  665. fn randMap(r: std.Random, arena: std.mem.Allocator, depth: u8) error{OutOfMemory}!Value {
  666. const names = [_][]const u8{ "id", "oldId", "name", "n" };
  667. const n = r.uintLessThan(usize, 6);
  668. const es = try arena.alloc(Entry, n);
  669. for (es) |*e| {
  670. e.key = if (r.uintLessThan(u8, 8) == 0) Value{ .number = 3 } else Value{ .str = names[r.uintLessThan(usize, names.len)] };
  671. e.value = try randValue(r, arena, depth);
  672. }
  673. return .{ .map = es };
  674. }
  675. fn sameValue(a: ?Value, b: ?Value) bool {
  676. if (a == null or b == null) return a == null and b == null;
  677. return std.meta.activeTag(a.?) == std.meta.activeTag(b.?) and switch (a.?) {
  678. .str => |s| std.mem.eql(u8, s, b.?.str),
  679. .number => |x| x == b.?.number or (std.math.isNan(x) and std.math.isNan(b.?.number)),
  680. .boolean => |x| x == b.?.boolean,
  681. else => true,
  682. };
  683. }
  684. test "436: decodeFields = decode + get, on random records and on damaged ones" {
  685. var prng = std.Random.DefaultPrng.init(436);
  686. const r = prng.random();
  687. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  688. defer arena_state.deinit();
  689. const names = [_][]const u8{ "id", "oldId", "zzz" };
  690. var round: usize = 0;
  691. while (round < 20000) : (round += 1) {
  692. _ = arena_state.reset(.retain_capacity);
  693. const arena = arena_state.allocator();
  694. const v = if (r.uintLessThan(u8, 12) == 0) try randValue(r, arena, 0) else try randMap(r, arena, 0);
  695. var bytes = try encode(arena, v);
  696. switch (r.uintLessThan(u8, 6)) {
  697. 0 => bytes = bytes[0..r.uintLessThan(usize, bytes.len + 1)],
  698. 1 => {
  699. if (bytes.len > 0) bytes[r.uintLessThan(usize, bytes.len)] = r.uintLessThan(u8, 0xc2); // no big counts: decode allocates n values up front
  700. },
  701. else => {},
  702. }
  703. var out: [3]?Value = undefined;
  704. const got = decodeFields(arena, bytes, &names, &out);
  705. const want = decode(arena, bytes);
  706. if (want) |w| {
  707. try testing.expect(got != error.Truncated and got != error.InvalidFormat);
  708. try got;
  709. for (names, 0..) |nm, i| try testing.expect(sameValue(out[i], w.value.get(nm)));
  710. } else |_| {
  711. try testing.expect(std.meta.isError(got));
  712. }
  713. }
  714. }

Branches

Latest commits

  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre