app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

contact.ts (2132B)


      1 import { navigationHref } from '../../navigation-url.ts';
      2 import { boundedUtf8 } from './text.ts';
      3 export type PublicContactInput = Readonly<{
      4   type: 'email' | 'phone' | 'https';
      5   value: string;
      6   public: true;
      7 }>;
      8 export type PublicContact = Readonly<{
      9   type: 'email' | 'phone' | 'https';
     10   href: string;
     11 }>;
     12 function email(value: string): boolean {
     13   // Deliberately bounded ASCII mailbox input, without headers or URI queries.
     14   if (
     15     value.length > 254 ||
     16     /[?#%]/u.test(value) ||
     17     !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+$/u.test(value)
     18   )
     19     return false;
     20   const [local, domain] = value.split('@');
     21   return (
     22     local.length <= 64 &&
     23     !local.startsWith('.') &&
     24     !local.endsWith('.') &&
     25     !local.includes('..') &&
     26     domain
     27       .split('.')
     28       .every(
     29         (label) =>
     30           label.length <= 63 &&
     31           /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/u.test(label)
     32       )
     33   );
     34 }
     35 export function publicContact(input: unknown): PublicContact | undefined {
     36   if (
     37     typeof input !== 'object' ||
     38     input === null ||
     39     Array.isArray(input) ||
     40     !('public' in input) ||
     41     !('type' in input) ||
     42     !('value' in input)
     43   )
     44     return undefined;
     45   // Access known scalar fields once before validating or composing a URI.
     46   const { public: disclosed, type, value } = input;
     47   if (
     48     disclosed !== true ||
     49     typeof value !== 'string' ||
     50     !boundedUtf8(value, 8192)
     51   )
     52     return undefined;
     53   try {
     54     if (
     55       /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(value) ||
     56       /[\p{Cc}\p{Cf}]/u.test(decodeURIComponent(value))
     57     )
     58       return undefined;
     59   } catch {
     60     return undefined;
     61   }
     62   let href: string;
     63   if (type === 'email') {
     64     if (!email(value)) return undefined;
     65     href = `mailto:${value}`;
     66   } else if (type === 'phone') {
     67     if (!/^\+[1-9][0-9]{1,14}$/u.test(value)) return undefined;
     68     href = `tel:${value}`;
     69   } else if (type === 'https') {
     70     if (!/^https:\/\//u.test(value)) return undefined;
     71     href = value;
     72   } else return undefined;
     73   const safe = navigationHref(href);
     74   if (safe === undefined) return undefined;
     75   return { type, href: safe };
     76 }