commit 845fc9b2304f29a01fbab5ebcedebaea02dfc312
parent 23414e2fc90b9ea15cbf57cf645079107ba5eab4
Author: triesap <tyson@radroots.org>
Date: Mon, 5 Oct 2026 22:52:34 +0000
availability: implement exact decimal and bounded envelope values (HCP-023)
- Preserve canonical Food amounts as exact strings with twenty-eight digits.
- Validate pinned public units, currency and positive quantity without defaults.
- Reject unsafe envelope timestamps and unsupported publication values before conversion.
- Cover public authored fixtures and numeric precision with executable assertions.
Diffstat:
3 files changed, 362 insertions(+), 0 deletions(-)
diff --git a/web/src/lib/contracts/food-availability-v1/values.ts b/web/src/lib/contracts/food-availability-v1/values.ts
@@ -0,0 +1,94 @@
+// Strict authored values from public Radroots Lib189 Food Availability v1.
+// Tolerant inbound normalization belongs to the separate reader adapter.
+export const foodUnits = Object.freeze([
+ 'g',
+ 'kg',
+ 'lb',
+ 'oz',
+ 'each',
+ 'dozen',
+ 'bunch',
+ 'punnet',
+ 'bag',
+ 'basket'
+] as const);
+export type FoodUnit = (typeof foodUnits)[number];
+
+declare const decimalValue: unique symbol;
+export type CanonicalFoodAmount = string & {
+ readonly [decimalValue]: true;
+};
+declare const currencyValue: unique symbol;
+export type FoodCurrency = string & { readonly [currencyValue]: true };
+
+export function canonicalFoodAmount(
+ value: unknown
+): CanonicalFoodAmount | undefined {
+ // Twenty-eight ASCII digits and at most one decimal point. Check length
+ // before regex work; keep the exact string rather than convert to Number.
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > 29 ||
+ !/^(?:0|[1-9][0-9]*)(?:\.[0-9]*[1-9])?$/u.test(value)
+ )
+ return undefined;
+ const digits = value.length - (value.includes('.') ? 1 : 0);
+ if (digits > 28) return undefined;
+ return value as CanonicalFoodAmount;
+}
+
+export function foodCurrency(value: unknown): FoodCurrency | undefined {
+ if (
+ typeof value !== 'string' ||
+ value.length !== 3 ||
+ !/^[A-Z]{3}$/u.test(value)
+ )
+ return undefined;
+ return value as FoodCurrency;
+}
+
+export function foodUnit(value: unknown): FoodUnit | undefined {
+ if (
+ typeof value !== 'string' ||
+ value.length > 6 ||
+ !foodUnits.includes(value as FoodUnit)
+ )
+ return undefined;
+ return value as FoodUnit;
+}
+
+export type FoodPrice = Readonly<{
+ amount: CanonicalFoodAmount;
+ currency: FoodCurrency;
+ unit: FoodUnit;
+}>;
+export function foodPrice(
+ amountValue: unknown,
+ currencyInput: unknown,
+ unitInput: unknown
+): FoodPrice | undefined {
+ const amount = canonicalFoodAmount(amountValue);
+ const currency = foodCurrency(currencyInput);
+ const unit = foodUnit(unitInput);
+ if (amount === undefined || currency === undefined || unit === undefined)
+ return undefined;
+ return { amount, currency, unit };
+}
+
+export type FoodQuantity = Readonly<{
+ amount: CanonicalFoodAmount;
+ unit: FoodUnit;
+}>;
+export function foodQuantity(
+ amountValue: unknown,
+ unitInput: unknown
+): FoodQuantity | undefined {
+ const amount = canonicalFoodAmount(amountValue);
+ const unit = foodUnit(unitInput);
+ // Canonical zero has exactly one spelling. Missing/invalid data remains
+ // absent; it is never converted into zero inventory.
+ if (amount === undefined || amount === '0' || unit === undefined)
+ return undefined;
+ return { amount, unit };
+}
diff --git a/web/src/lib/nostr/envelope-bounds.ts b/web/src/lib/nostr/envelope-bounds.ts
@@ -0,0 +1,43 @@
+// Numeric preflight only: these values are not signature or profile admission.
+export function safeUnsignedInteger(value: unknown): number | undefined {
+ if (
+ typeof value !== 'number' ||
+ !Number.isSafeInteger(value) ||
+ value < 0 ||
+ (value === 0 && 1 / value === -Infinity)
+ )
+ return undefined;
+ return value;
+}
+
+export type BoundedEnvelopeNumbers = Readonly<{
+ kind: number;
+ created_at: number;
+}>;
+export function boundedEnvelopeNumbers(
+ kindInput: unknown,
+ timestampInput: unknown
+): BoundedEnvelopeNumbers | undefined {
+ const kind = safeUnsignedInteger(kindInput);
+ const createdAt = safeUnsignedInteger(timestampInput);
+ // Frozen NIP-01 kind range; the browser's timestamp envelope is narrower
+ // than the public Rust u64 type. Unsupported numbers never get rounded.
+ if (kind === undefined || kind > 65535 || createdAt === undefined)
+ return undefined;
+ return { kind, created_at: createdAt };
+}
+
+export function foodPublishedAt(value: unknown): number | undefined {
+ // Public FoodPublishedAt requires a positive canonical unsigned integer.
+ // Compare the ASCII magnitude before Number conversion, so u64 values
+ // outside the exact JavaScript range cannot be rounded into trusted data.
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > 16 ||
+ !/^[1-9][0-9]*$/u.test(value) ||
+ (value.length === 16 && value > '9007199254740991')
+ )
+ return undefined;
+ return Number(value);
+}
diff --git a/web/tests/unit/food-values.test.ts b/web/tests/unit/food-values.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ canonicalFoodAmount,
+ foodCurrency,
+ foodPrice,
+ foodQuantity,
+ foodUnit,
+ foodUnits
+} from '../../src/lib/contracts/food-availability-v1/values';
+import {
+ boundedEnvelopeNumbers,
+ foodPublishedAt,
+ safeUnsignedInteger
+} from '../../src/lib/nostr/envelope-bounds';
+import corpus from '../../../contracts/interop/food_availability/corpus.v1.json';
+
+describe('exact Food decimal values from pinned public Rust', () => {
+ for (const vector of corpus.vectors.slice(0, 10))
+ it(`preserves actual authored ${vector.id} values without numeric conversion`, () => {
+ const details = vector.input.details!;
+ expect(foodUnit(details.price.unit)).toBe(details.price.unit);
+ expect(
+ foodPrice(
+ details.price.amount,
+ details.price.currency,
+ details.price.unit
+ )
+ ).toEqual(details.price);
+ if (details.quantity)
+ expect(
+ foodQuantity(details.quantity.amount, details.quantity.unit)
+ ).toEqual(details.quantity);
+ else expect(details.quantity).toBeNull();
+ });
+
+ it('has exactly the ten pinned public units with no unknown fallback', () => {
+ expect(foodUnits).toEqual([
+ 'g',
+ 'kg',
+ 'lb',
+ 'oz',
+ 'each',
+ 'dozen',
+ 'bunch',
+ 'punnet',
+ 'bag',
+ 'basket'
+ ]);
+ for (const value of ['KG', 'lbs', 'item', '', ' kg', undefined, 1])
+ expect(foodUnit(value)).toBeUndefined();
+ });
+
+ for (const amount of [
+ '0',
+ '1',
+ '0.01',
+ '1234567890123456789012345678',
+ '12345678901234.56789012345678',
+ '0.000000000000000000000000001'
+ ])
+ it(`retains exact canonical decimal ${amount}`, () => {
+ expect(canonicalFoodAmount(amount)).toBe(amount);
+ expect(foodPrice(amount, 'CAD', 'lb')?.amount).toBe(amount);
+ });
+
+ for (const amount of [
+ '',
+ '01',
+ '00',
+ '.1',
+ '1.',
+ '1.0',
+ '0.0',
+ '1.20',
+ '+1',
+ '-1',
+ '-0',
+ '1e2',
+ '1E-2',
+ '1,000',
+ '1_000',
+ '1 000',
+ ' 1',
+ '1 ',
+ '1\n',
+ '1',
+ '١',
+ '0x10',
+ 'NaN',
+ 'Infinity',
+ '12345678901234567890123456789',
+ '0.0000000000000000000000000001'
+ ])
+ it(`rejects noncanonical or oversized decimal ${JSON.stringify(amount)}`, () => {
+ expect(canonicalFoodAmount(amount)).toBeUndefined();
+ expect(foodPrice(amount, 'CAD', 'lb')).toBeUndefined();
+ expect(foodQuantity(amount, 'lb')).toBeUndefined();
+ });
+
+ it('keeps missing price distinct from a valid zero price and rejects zero quantity', () => {
+ expect(canonicalFoodAmount(undefined)).toBeUndefined();
+ expect(canonicalFoodAmount('0')).toBe('0');
+ expect(foodPrice('0', 'CAD', 'lb')).toEqual({
+ amount: '0',
+ currency: 'CAD',
+ unit: 'lb'
+ });
+ expect(foodQuantity('0', 'lb')).toBeUndefined();
+ expect(foodQuantity(undefined, 'lb')).toBeUndefined();
+ expect(foodQuantity('0.01', 'lb')).toEqual({ amount: '0.01', unit: 'lb' });
+ });
+
+ it('uses exactly three uppercase ASCII currency letters without inventing an ISO registry', () => {
+ for (const value of ['CAD', 'USD', 'EUR', 'AAA'])
+ expect(foodCurrency(value)).toBe(value);
+ for (const value of [
+ '',
+ 'CA',
+ 'CADD',
+ 'cad',
+ ' Cad',
+ 'CAD\n',
+ 'C1D',
+ 'CAD',
+ null
+ ]) {
+ expect(foodCurrency(value)).toBeUndefined();
+ expect(foodPrice('1', value, 'lb')).toBeUndefined();
+ }
+ expect(foodPrice('1', 'CAD', 'unknown')).toBeUndefined();
+ expect(foodQuantity('1', 'unknown')).toBeUndefined();
+ });
+
+ it('rejects huge strings and nonstrings before coercion or normalization', () => {
+ const toString = vi.fn(() => '1');
+ for (const value of [
+ '1'.repeat(1024 * 1024),
+ { toString },
+ 1,
+ 1n,
+ null,
+ Symbol('amount')
+ ]) {
+ expect(canonicalFoodAmount(value)).toBeUndefined();
+ expect(foodCurrency(value)).toBeUndefined();
+ expect(foodUnit(value)).toBeUndefined();
+ }
+ expect(toString).not.toHaveBeenCalled();
+ });
+});
+
+describe('bounded browser numeric envelopes without an authenticity claim', () => {
+ for (const value of [0, 1, 4294967296, Number.MAX_SAFE_INTEGER])
+ it(`accepts exact nonnegative safe integer ${value}`, () => {
+ expect(safeUnsignedInteger(value)).toBe(value);
+ expect(boundedEnvelopeNumbers(30402, value)).toEqual({
+ kind: 30402,
+ created_at: value
+ });
+ });
+
+ for (const value of [
+ -0,
+ -1,
+ 0.5,
+ NaN,
+ Infinity,
+ -Infinity,
+ Number.MAX_SAFE_INTEGER + 1,
+ '1',
+ 1n,
+ null,
+ undefined
+ ])
+ it(`rejects unsupported numeric input ${String(value)}`, () => {
+ expect(safeUnsignedInteger(value)).toBeUndefined();
+ expect(boundedEnvelopeNumbers(30402, value)).toBeUndefined();
+ expect(boundedEnvelopeNumbers(value, 1)).toBeUndefined();
+ });
+
+ it('bounds kind to the frozen NIP-01 unsigned 16-bit range', () => {
+ expect(boundedEnvelopeNumbers(0, 0)).toEqual({ kind: 0, created_at: 0 });
+ expect(boundedEnvelopeNumbers(65535, 1)).toEqual({
+ kind: 65535,
+ created_at: 1
+ });
+ expect(boundedEnvelopeNumbers(65536, 1)).toBeUndefined();
+ });
+
+ it('rejects a parsed maximum-u64 event timestamp instead of silently rounding', () => {
+ const raw = JSON.parse(
+ '{"kind":30402,"created_at":18446744073709551615}'
+ ) as { kind: number; created_at: number };
+ expect(Number.isSafeInteger(raw.created_at)).toBe(false);
+ expect(boundedEnvelopeNumbers(raw.kind, raw.created_at)).toBeUndefined();
+ });
+
+ for (const value of ['1', '4294967296', '9007199254740991'])
+ it(`accepts supported exact positive published_at ${value}`, () => {
+ expect(foodPublishedAt(value)).toBe(Number(value));
+ expect(String(foodPublishedAt(value))).toBe(value);
+ });
+
+ for (const value of [
+ '0',
+ '01',
+ '+1',
+ '-1',
+ '1.0',
+ '1e2',
+ ' 1',
+ '1 ',
+ '1\n',
+ '١',
+ '9007199254740992',
+ '9007199254740993',
+ '18446744073709551615',
+ '9'.repeat(1024 * 1024),
+ 1,
+ null
+ ])
+ it(`rejects invalid or unsupported published_at ${typeof value === 'string' && value.length > 40 ? 'oversized string' : JSON.stringify(value)}`, () => {
+ expect(foodPublishedAt(value)).toBeUndefined();
+ });
+});