ita_protocol.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. """Pure Prenot@Mi protocol parsing and precommit validation.
  2. This module is the functional core of the Italy plugin. It deliberately owns
  3. no browser, network, session, OTP, or form-submission behavior. Callers pass
  4. already-captured, sanitized data in and receive immutable value objects back.
  5. """
  6. from __future__ import annotations
  7. import json
  8. import html
  9. import re
  10. from dataclasses import dataclass, field
  11. from datetime import date, datetime, time
  12. from enum import Enum
  13. from typing import Any, Mapping, Sequence
  14. MAX_PROTOCOL_ITEMS = 512
  15. MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
  16. MAX_LOOKAHEAD_MONTHS = 120
  17. _SITE_DATE_PATTERN = re.compile(r"^\d{2}/\d{2}/\d{4} 00:00:00$")
  18. PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
  19. _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  20. _OTP_CONTEXT_PATTERN = re.compile(
  21. r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)",
  22. re.IGNORECASE,
  23. )
  24. class ItaProtocolError(ValueError):
  25. """Fail-closed protocol error with a stable, non-sensitive category."""
  26. def __init__(self, code: str, message: str, *, path: str = "") -> None:
  27. self.code = code
  28. self.path = path
  29. location = f" at {path}" if path else ""
  30. super().__init__(f"Italy protocol error [{code}]{location}: {message}")
  31. class ItaCapability(str, Enum):
  32. SERVICES_PROBE_ONLY = "services_probe_only"
  33. SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
  34. class InventoryState(str, Enum):
  35. AVAILABLE = "available"
  36. UNAVAILABLE = "unavailable"
  37. @dataclass(frozen=True, slots=True)
  38. class CalendarScanConfig:
  39. lookahead_months: int
  40. @dataclass(frozen=True, slots=True)
  41. class FormControlConfig:
  42. control_id: str
  43. value: str
  44. labels: tuple[str, ...]
  45. @dataclass(frozen=True, slots=True)
  46. class OtpMailConfig:
  47. """Allowlisted cloud-mail query settings for one Italy route.
  48. The authorization mailbox is configured explicitly or derived per call
  49. from the current account, never cached on a shared route or included in
  50. diagnostic objects or log messages. The sender is
  51. fixed to Prenot@Mi's observed official address; a route may not widen the
  52. allowlist through configuration.
  53. """
  54. authorization_email: str | None = field(default=None, repr=False)
  55. subject_keywords: str = "OTP Code"
  56. body_keywords: str = "OTP Code:"
  57. expiry_seconds: int = 300
  58. authorization_source: str = "configured"
  59. def __post_init__(self) -> None:
  60. if self.authorization_source not in ("configured", "account"):
  61. raise ItaProtocolError(
  62. "otp_authorization_source_invalid",
  63. "authorization source must be configured or account",
  64. path="mail.authorization_source",
  65. )
  66. if self.authorization_source == "account":
  67. if self.authorization_email is not None:
  68. raise ItaProtocolError(
  69. "otp_authorization_source_conflict",
  70. "account source cannot also specify a fixed authorization mailbox",
  71. path="mail.authorization_email",
  72. )
  73. else:
  74. object.__setattr__(self, "authorization_email", self._require_mailbox(self.authorization_email))
  75. for field_name, expected in (("subject_keywords", "OTP Code"), ("body_keywords", "OTP Code:")):
  76. value = getattr(self, field_name)
  77. if not isinstance(value, str) or value.strip() != expected:
  78. raise ItaProtocolError(
  79. "otp_filter_invalid",
  80. "mail filters must match the observed Prenot@Mi OTP template",
  81. path=f"mail.{field_name}",
  82. )
  83. object.__setattr__(self, field_name, value.strip())
  84. if (
  85. not isinstance(self.expiry_seconds, int)
  86. or isinstance(self.expiry_seconds, bool)
  87. or not 1 <= self.expiry_seconds <= 300
  88. ):
  89. raise ItaProtocolError(
  90. "otp_expiry_invalid",
  91. "mail expiry must be an integer between 1 and 300 seconds",
  92. path="mail.expiry_seconds",
  93. )
  94. @staticmethod
  95. def _require_mailbox(value: Any) -> str:
  96. if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
  97. raise ItaProtocolError(
  98. "otp_authorization_email_invalid",
  99. "authorization mailbox must be a valid email address",
  100. path="mail.authorization_email",
  101. )
  102. return value.strip()
  103. def mailbox_for(self, account_email: str) -> str:
  104. """Bind per call; never mutate the route shared by pool instances.
  105. Account mode requires that each account's own inbox has an existing
  106. backend authorization. Configured mode preserves shared/forwarded
  107. inbox support; recipient filtering remains bound to the site account.
  108. """
  109. return self._require_mailbox(
  110. account_email if self.authorization_source == "account" else self.authorization_email
  111. )
  112. @dataclass(frozen=True, slots=True)
  113. class ItaRouteConfig:
  114. routing_key: str
  115. service_id: int
  116. capability: ItaCapability
  117. calendar_scan: CalendarScanConfig | None = None
  118. booking_type: FormControlConfig | None = None
  119. purpose: FormControlConfig | None = None
  120. mail: OtpMailConfig | None = None
  121. @dataclass(frozen=True, slots=True)
  122. class CalendarDay:
  123. day: date
  124. slots_free: int
  125. slots_remaining: int
  126. state: InventoryState
  127. def __post_init__(self) -> None:
  128. _require_date(self.day, "CalendarDay.day")
  129. slots_free = _require_int(self.slots_free, "CalendarDay.slots_free")
  130. slots_remaining = _require_int(
  131. self.slots_remaining,
  132. "CalendarDay.slots_remaining",
  133. )
  134. expected_state = _classify_inventory(
  135. slots_free,
  136. slots_remaining,
  137. path="CalendarDay",
  138. )
  139. if self.state is not expected_state:
  140. raise ItaProtocolError(
  141. "inventory_state_mismatch",
  142. "declared state differs from the slot counters",
  143. path="CalendarDay.state",
  144. )
  145. @property
  146. def is_available(self) -> bool:
  147. return self.state is InventoryState.AVAILABLE
  148. @dataclass(frozen=True, slots=True)
  149. class SlotCandidate:
  150. day: date
  151. start_time: time
  152. end_time: time
  153. slots_free: int
  154. slots_remaining: int
  155. state: InventoryState
  156. daily_calendar_id: str = field(repr=False)
  157. def __post_init__(self) -> None:
  158. _require_date(self.day, "SlotCandidate.day")
  159. start = _require_time(self.start_time, "SlotCandidate.start_time")
  160. end = _require_time(self.end_time, "SlotCandidate.end_time")
  161. if start >= end:
  162. raise ItaProtocolError(
  163. "time_range_invalid",
  164. "slot start time must be earlier than end time",
  165. path="SlotCandidate",
  166. )
  167. slots_free = _require_int(
  168. self.slots_free,
  169. "SlotCandidate.slots_free",
  170. )
  171. slots_remaining = _require_int(
  172. self.slots_remaining,
  173. "SlotCandidate.slots_remaining",
  174. )
  175. expected_state = _classify_inventory(
  176. slots_free,
  177. slots_remaining,
  178. path="SlotCandidate",
  179. )
  180. if self.state is not expected_state:
  181. raise ItaProtocolError(
  182. "inventory_state_mismatch",
  183. "declared state differs from the slot counters",
  184. path="SlotCandidate.state",
  185. )
  186. if (
  187. not isinstance(self.daily_calendar_id, str)
  188. or not self.daily_calendar_id.isdigit()
  189. or int(self.daily_calendar_id) <= 0
  190. ):
  191. raise ItaProtocolError(
  192. "daily_id_invalid",
  193. "runtime daily identifier must be a positive integer string",
  194. path="SlotCandidate.daily_calendar_id",
  195. )
  196. @property
  197. def is_available(self) -> bool:
  198. return self.state is InventoryState.AVAILABLE
  199. @property
  200. def time_label(self) -> str:
  201. return (
  202. f"{self.start_time.strftime('%H:%M')} - "
  203. f"{self.end_time.strftime('%H:%M')}"
  204. )
  205. @dataclass(frozen=True, slots=True)
  206. class DateSelectionState:
  207. planned_day: date
  208. matching_availability_count: int
  209. timeline_selected_days: tuple[date, ...]
  210. content_selected_days: tuple[date, ...]
  211. day_disabled: bool
  212. day_not_available: bool
  213. day_has_positive_state: bool
  214. def __post_init__(self) -> None:
  215. _require_date(self.planned_day, "DateSelectionState.planned_day")
  216. _require_nonnegative_int(
  217. self.matching_availability_count,
  218. "DateSelectionState.matching_availability_count",
  219. )
  220. _require_date_tuple(
  221. self.timeline_selected_days,
  222. "DateSelectionState.timeline_selected_days",
  223. )
  224. _require_date_tuple(
  225. self.content_selected_days,
  226. "DateSelectionState.content_selected_days",
  227. )
  228. for field_name in (
  229. "day_disabled",
  230. "day_not_available",
  231. "day_has_positive_state",
  232. ):
  233. _require_bool(
  234. getattr(self, field_name),
  235. f"DateSelectionState.{field_name}",
  236. )
  237. @dataclass(frozen=True, slots=True)
  238. class SlotSelectionState:
  239. active_slot_count: int
  240. active_is_candidate: bool
  241. active_has_unavailable_class: bool
  242. active_has_red_dot: bool
  243. active_hidden_input_count: int
  244. active_daily_id_matches_candidate: bool
  245. active_day_matches_candidate: bool
  246. active_time_matches_candidate: bool
  247. active_capacity_matches_candidate: bool
  248. def __post_init__(self) -> None:
  249. for field_name in (
  250. "active_slot_count",
  251. "active_hidden_input_count",
  252. ):
  253. _require_nonnegative_int(
  254. getattr(self, field_name),
  255. f"SlotSelectionState.{field_name}",
  256. )
  257. for field_name in (
  258. "active_is_candidate",
  259. "active_has_unavailable_class",
  260. "active_has_red_dot",
  261. "active_daily_id_matches_candidate",
  262. "active_day_matches_candidate",
  263. "active_time_matches_candidate",
  264. "active_capacity_matches_candidate",
  265. ):
  266. _require_bool(
  267. getattr(self, field_name),
  268. f"SlotSelectionState.{field_name}",
  269. )
  270. @dataclass(frozen=True, slots=True)
  271. class PrecommitApproval:
  272. """Immutable value returned by :func:`approve_precommit`."""
  273. calendar_day: CalendarDay
  274. candidate: SlotCandidate
  275. def resolve_route_config(
  276. apt_configs: Mapping[str, Any],
  277. routing_key: str,
  278. ) -> ItaRouteConfig:
  279. """Resolve one VFS/BLS-style ``apt_configs[routing_key]`` entry."""
  280. configs = _require_mapping(apt_configs, "apt_configs")
  281. key = _require_nonempty_string(routing_key, "routing_key")
  282. if key not in configs:
  283. raise ItaProtocolError(
  284. "route_missing",
  285. "no route is configured for the requested routing key",
  286. path="apt_configs",
  287. )
  288. raw_route = _require_mapping(configs[key], f"apt_configs.{key}")
  289. service_id = _require_positive_int(
  290. raw_route.get("service_id"),
  291. f"apt_configs.{key}.service_id",
  292. )
  293. raw_capability = _require_nonempty_string(
  294. raw_route.get("capability"),
  295. f"apt_configs.{key}.capability",
  296. )
  297. try:
  298. capability = ItaCapability(raw_capability)
  299. except ValueError as exc:
  300. raise ItaProtocolError(
  301. "capability_unsupported",
  302. "route capability is not supported",
  303. path=f"apt_configs.{key}.capability",
  304. ) from exc
  305. if capability is ItaCapability.SERVICES_PROBE_ONLY:
  306. return ItaRouteConfig(
  307. routing_key=key,
  308. service_id=service_id,
  309. capability=capability,
  310. )
  311. calendar_scan_raw = _require_mapping(
  312. raw_route.get("calendar_scan"),
  313. f"apt_configs.{key}.calendar_scan",
  314. )
  315. calendar_scan = CalendarScanConfig(
  316. lookahead_months=_require_lookahead_months(
  317. calendar_scan_raw.get("lookahead_months"),
  318. f"apt_configs.{key}.calendar_scan.lookahead_months",
  319. )
  320. )
  321. form_raw = _require_mapping(
  322. raw_route.get("form"),
  323. f"apt_configs.{key}.form",
  324. )
  325. booking_type = _parse_form_control(
  326. form_raw,
  327. prefix="booking_type",
  328. path=f"apt_configs.{key}.form",
  329. )
  330. purpose = _parse_form_control(
  331. form_raw,
  332. prefix="purpose",
  333. path=f"apt_configs.{key}.form",
  334. )
  335. mail = _parse_mail_config(
  336. raw_route.get("mail"),
  337. path=f"apt_configs.{key}.mail",
  338. )
  339. return ItaRouteConfig(
  340. routing_key=key,
  341. service_id=service_id,
  342. capability=capability,
  343. calendar_scan=calendar_scan,
  344. booking_type=booking_type,
  345. purpose=purpose,
  346. mail=mail,
  347. )
  348. def decode_double_json_array(
  349. payload: str,
  350. *,
  351. max_items: int = MAX_PROTOCOL_ITEMS,
  352. ) -> tuple[Mapping[str, Any], ...]:
  353. """Strictly decode the JSON-string-containing-a-JSON-array wire shape."""
  354. if not isinstance(payload, str) or not payload:
  355. raise ItaProtocolError(
  356. "payload_type",
  357. "payload must be a non-empty JSON string",
  358. )
  359. if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
  360. raise ItaProtocolError(
  361. "payload_too_large",
  362. "payload exceeds the local parsing limit",
  363. )
  364. if not _is_positive_int(max_items):
  365. raise ItaProtocolError(
  366. "max_items_invalid",
  367. "max_items must be a positive integer",
  368. )
  369. try:
  370. outer = json.loads(payload)
  371. except (TypeError, json.JSONDecodeError) as exc:
  372. raise ItaProtocolError(
  373. "outer_json_invalid",
  374. "outer JSON cannot be decoded",
  375. ) from exc
  376. if not isinstance(outer, str):
  377. raise ItaProtocolError(
  378. "payload_layer_count",
  379. "payload must contain exactly two JSON layers",
  380. )
  381. if len(outer) > MAX_PROTOCOL_PAYLOAD_CHARS:
  382. raise ItaProtocolError(
  383. "payload_too_large",
  384. "inner payload exceeds the local parsing limit",
  385. )
  386. try:
  387. items = json.loads(outer)
  388. except (TypeError, json.JSONDecodeError) as exc:
  389. raise ItaProtocolError(
  390. "inner_json_invalid",
  391. "inner JSON cannot be decoded",
  392. ) from exc
  393. if not isinstance(items, list):
  394. raise ItaProtocolError(
  395. "payload_layer_count",
  396. "inner JSON must be an array",
  397. )
  398. if len(items) > max_items:
  399. raise ItaProtocolError(
  400. "item_limit_exceeded",
  401. "response contains more items than the configured parsing limit",
  402. )
  403. result: list[Mapping[str, Any]] = []
  404. for index, item in enumerate(items):
  405. if not isinstance(item, Mapping):
  406. raise ItaProtocolError(
  407. "item_type",
  408. "every response item must be an object",
  409. path=f"items[{index}]",
  410. )
  411. result.append(item)
  412. return tuple(result)
  413. def parse_calendar_availability(
  414. payload: str,
  415. *,
  416. max_items: int = MAX_PROTOCOL_ITEMS,
  417. ) -> tuple[CalendarDay, ...]:
  418. """Parse and classify calendar-day capacity without guessing conflicts."""
  419. items = decode_double_json_array(payload, max_items=max_items)
  420. days: list[CalendarDay] = []
  421. seen_days: set[date] = set()
  422. for index, item in enumerate(items):
  423. path = f"availability[{index}]"
  424. parsed_day = _parse_site_date(
  425. _require_key(item, "DateLibere", path),
  426. f"{path}.DateLibere",
  427. )
  428. if parsed_day in seen_days:
  429. raise ItaProtocolError(
  430. "duplicate_calendar_day",
  431. "calendar response contains a duplicate date",
  432. path=path,
  433. )
  434. seen_days.add(parsed_day)
  435. slots_free = _require_int(
  436. _require_key(item, "SlotLiberi", path),
  437. f"{path}.SlotLiberi",
  438. )
  439. slots_remaining = _require_int(
  440. _require_key(item, "SlotRimanenti", path),
  441. f"{path}.SlotRimanenti",
  442. )
  443. state = _classify_inventory(
  444. slots_free,
  445. slots_remaining,
  446. path=path,
  447. )
  448. days.append(
  449. CalendarDay(
  450. day=parsed_day,
  451. slots_free=slots_free,
  452. slots_remaining=slots_remaining,
  453. state=state,
  454. )
  455. )
  456. return tuple(sorted(days, key=lambda item: item.day))
  457. def parse_time_slots(
  458. payload: str,
  459. *,
  460. max_items: int = MAX_PROTOCOL_ITEMS,
  461. ) -> tuple[SlotCandidate, ...]:
  462. """Parse TimeSlots items while keeping the runtime ID memory-only."""
  463. items = decode_double_json_array(payload, max_items=max_items)
  464. candidates: list[SlotCandidate] = []
  465. seen_ranges: set[tuple[date, time, time]] = set()
  466. seen_daily_ids: set[str] = set()
  467. for index, item in enumerate(items):
  468. path = f"time_slots[{index}]"
  469. parsed_day = _parse_site_date(
  470. _require_key(item, "Data", path),
  471. f"{path}.Data",
  472. )
  473. start_time = _parse_site_time(
  474. _require_key(item, "OrarioInizioFascia", path),
  475. f"{path}.OrarioInizioFascia",
  476. )
  477. end_time = _parse_site_time(
  478. _require_key(item, "OrarioFineFascia", path),
  479. f"{path}.OrarioFineFascia",
  480. )
  481. if start_time >= end_time:
  482. raise ItaProtocolError(
  483. "time_range_invalid",
  484. "slot start time must be earlier than end time",
  485. path=path,
  486. )
  487. slots_free = _require_int(
  488. _require_key(item, "SlotLiberi", path),
  489. f"{path}.SlotLiberi",
  490. )
  491. slots_remaining = _require_int(
  492. _require_key(item, "SlotRimanenti", path),
  493. f"{path}.SlotRimanenti",
  494. )
  495. state = _classify_inventory(
  496. slots_free,
  497. slots_remaining,
  498. path=path,
  499. )
  500. daily_id = str(
  501. _require_positive_int(
  502. _require_key(item, "IDCalendarioServizioGiornaliero", path),
  503. f"{path}.IDCalendarioServizioGiornaliero",
  504. )
  505. )
  506. time_range = (parsed_day, start_time, end_time)
  507. if time_range in seen_ranges:
  508. raise ItaProtocolError(
  509. "duplicate_time_range",
  510. "time-slot response contains a duplicate time range",
  511. path=path,
  512. )
  513. if daily_id in seen_daily_ids:
  514. raise ItaProtocolError(
  515. "duplicate_daily_id",
  516. "time-slot response reuses a runtime daily identifier",
  517. path=path,
  518. )
  519. seen_ranges.add(time_range)
  520. seen_daily_ids.add(daily_id)
  521. candidates.append(
  522. SlotCandidate(
  523. day=parsed_day,
  524. start_time=start_time,
  525. end_time=end_time,
  526. slots_free=slots_free,
  527. slots_remaining=slots_remaining,
  528. state=state,
  529. daily_calendar_id=daily_id,
  530. )
  531. )
  532. return tuple(
  533. sorted(
  534. candidates,
  535. key=lambda item: (item.day, item.start_time, item.end_time),
  536. )
  537. )
  538. def available_calendar_days(
  539. days: Sequence[CalendarDay],
  540. *,
  541. start_day: date | None = None,
  542. end_day: date | None = None,
  543. ) -> tuple[CalendarDay, ...]:
  544. """Return positive days in an inclusive date range, sorted ascending."""
  545. start, end = _validate_date_range(start_day, end_day)
  546. seen: set[date] = set()
  547. selected: list[CalendarDay] = []
  548. for index, item in enumerate(days):
  549. if not isinstance(item, CalendarDay):
  550. raise ItaProtocolError(
  551. "calendar_day_type",
  552. "days must contain CalendarDay values",
  553. path=f"days[{index}]",
  554. )
  555. if item.day in seen:
  556. raise ItaProtocolError(
  557. "duplicate_calendar_day",
  558. "days contain a duplicate date",
  559. path=f"days[{index}]",
  560. )
  561. seen.add(item.day)
  562. if item.is_available and _date_in_range(item.day, start, end):
  563. selected.append(item)
  564. return tuple(sorted(selected, key=lambda item: item.day))
  565. def available_slot_candidates(
  566. candidates: Sequence[SlotCandidate],
  567. *,
  568. start_day: date | None = None,
  569. end_day: date | None = None,
  570. ) -> tuple[SlotCandidate, ...]:
  571. """Filter and deterministically order positive Book-side candidates."""
  572. start, end = _validate_date_range(start_day, end_day)
  573. seen_ranges: set[tuple[date, time, time]] = set()
  574. selected: list[SlotCandidate] = []
  575. for index, item in enumerate(candidates):
  576. if not isinstance(item, SlotCandidate):
  577. raise ItaProtocolError(
  578. "slot_candidate_type",
  579. "candidates must contain SlotCandidate values",
  580. path=f"candidates[{index}]",
  581. )
  582. identity = (item.day, item.start_time, item.end_time)
  583. if identity in seen_ranges:
  584. raise ItaProtocolError(
  585. "duplicate_time_range",
  586. "candidates contain a duplicate time range",
  587. path=f"candidates[{index}]",
  588. )
  589. seen_ranges.add(identity)
  590. if item.is_available and _date_in_range(item.day, start, end):
  591. selected.append(item)
  592. return tuple(
  593. sorted(
  594. selected,
  595. key=lambda item: (
  596. item.day,
  597. -item.slots_free,
  598. item.start_time,
  599. item.end_time,
  600. ),
  601. )
  602. )
  603. def parse_otp_body(
  604. body: str,
  605. *,
  606. max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS,
  607. ) -> str:
  608. """Extract exactly one Prenot@Mi OTP from a cloud-mail body.
  609. The cloud endpoint returns a body-only string and may include both the
  610. plain-text and HTML MIME alternatives. HTML tags are replaced with
  611. spaces, then only the observed ``OTP Code:`` marker followed by six ASCII
  612. digits is accepted. Repeated identical matches (plain + HTML) are fine;
  613. different candidates fail closed. No caller should log ``body`` or the
  614. returned code.
  615. """
  616. if not isinstance(body, str) or not body.strip():
  617. raise ItaProtocolError(
  618. "otp_body_invalid",
  619. "OTP mail body must be a non-empty string",
  620. path="mail.body",
  621. )
  622. if not isinstance(max_chars, int) or isinstance(max_chars, bool) or max_chars <= 0:
  623. raise ItaProtocolError(
  624. "otp_body_limit_invalid",
  625. "OTP body limit must be a positive integer",
  626. path="mail.max_chars",
  627. )
  628. if len(body) > max_chars:
  629. raise ItaProtocolError(
  630. "otp_body_too_large",
  631. "OTP mail body exceeds the local parsing limit",
  632. path="mail.body",
  633. )
  634. # The existing cloud service can concatenate text/plain and text/html.
  635. # Projecting HTML to text avoids depending on a browser or executing any
  636. # markup while preserving the marker when tags surround the code.
  637. projected = html.unescape(re.sub(r"<[^>]{0,4096}>", " ", body))
  638. projected = re.sub(r"\s+", " ", projected).strip()
  639. matches = _OTP_CONTEXT_PATTERN.findall(projected)
  640. unique = tuple(dict.fromkeys(matches))
  641. if not unique:
  642. raise ItaProtocolError(
  643. "otp_not_found",
  644. "mail body did not contain the expected OTP marker",
  645. path="mail.body",
  646. )
  647. if len(unique) != 1:
  648. raise ItaProtocolError(
  649. "otp_ambiguous",
  650. "mail body contained multiple different OTP candidates",
  651. path="mail.body",
  652. )
  653. return unique[0]
  654. def month_starts(anchor_day: date, lookahead_months: int) -> tuple[date, ...]:
  655. """Return deterministic month starts for the configured scan window."""
  656. anchor = _require_date(anchor_day, "anchor_day")
  657. months = _require_lookahead_months(lookahead_months, "lookahead_months")
  658. result: list[date] = []
  659. year = anchor.year
  660. month = anchor.month
  661. for _ in range(months):
  662. result.append(date(year, month, 1))
  663. month += 1
  664. if month == 13:
  665. year += 1
  666. month = 1
  667. return tuple(result)
  668. def approve_precommit(
  669. calendar_day: CalendarDay,
  670. candidate: SlotCandidate,
  671. date_state: DateSelectionState,
  672. slot_state: SlotSelectionState,
  673. ) -> PrecommitApproval:
  674. """Approve final-button readiness only when every observed invariant holds."""
  675. if not isinstance(calendar_day, CalendarDay):
  676. raise ItaProtocolError(
  677. "precommit_type",
  678. "calendar_day must be a CalendarDay",
  679. )
  680. if not isinstance(candidate, SlotCandidate):
  681. raise ItaProtocolError(
  682. "precommit_type",
  683. "candidate must be a SlotCandidate",
  684. )
  685. if not isinstance(date_state, DateSelectionState):
  686. raise ItaProtocolError(
  687. "precommit_type",
  688. "date_state must be a DateSelectionState",
  689. )
  690. if not isinstance(slot_state, SlotSelectionState):
  691. raise ItaProtocolError(
  692. "precommit_type",
  693. "slot_state must be a SlotSelectionState",
  694. )
  695. checks = (
  696. (calendar_day.is_available, "calendar day is not positively available"),
  697. (candidate.is_available, "slot candidate is not positively available"),
  698. (calendar_day.day == candidate.day, "calendar and slot dates differ"),
  699. (
  700. date_state.planned_day == candidate.day,
  701. "selected date differs from the planned date",
  702. ),
  703. (
  704. date_state.matching_availability_count == 1,
  705. "planned date must map to exactly one availability item",
  706. ),
  707. (
  708. date_state.timeline_selected_days == (candidate.day,),
  709. "timeline must have exactly one matching selected date",
  710. ),
  711. (
  712. date_state.content_selected_days == (candidate.day,),
  713. "content must have exactly one matching selected date",
  714. ),
  715. (not date_state.day_disabled, "selected date is disabled"),
  716. (
  717. not date_state.day_not_available,
  718. "selected date has a negative availability marker",
  719. ),
  720. (
  721. date_state.day_has_positive_state,
  722. "selected date lacks the verified positive state",
  723. ),
  724. (
  725. slot_state.active_slot_count == 1,
  726. "there must be exactly one active slot",
  727. ),
  728. (
  729. slot_state.active_is_candidate,
  730. "active slot is not the approved candidate",
  731. ),
  732. (
  733. not slot_state.active_has_unavailable_class,
  734. "active slot has an unavailable class",
  735. ),
  736. (
  737. not slot_state.active_has_red_dot,
  738. "active slot has a negative red marker",
  739. ),
  740. (
  741. slot_state.active_hidden_input_count == 1,
  742. "active slot must contain exactly one runtime identifier input",
  743. ),
  744. (
  745. slot_state.active_daily_id_matches_candidate,
  746. "active slot runtime identifier differs from the candidate",
  747. ),
  748. (
  749. slot_state.active_day_matches_candidate,
  750. "active slot date differs from the candidate",
  751. ),
  752. (
  753. slot_state.active_time_matches_candidate,
  754. "active slot time differs from the candidate",
  755. ),
  756. (
  757. slot_state.active_capacity_matches_candidate,
  758. "active slot capacity differs from the candidate",
  759. ),
  760. )
  761. for passed, message in checks:
  762. if not passed:
  763. raise ItaProtocolError("precommit_rejected", message)
  764. return PrecommitApproval(calendar_day=calendar_day, candidate=candidate)
  765. def _parse_form_control(
  766. form: Mapping[str, Any],
  767. *,
  768. prefix: str,
  769. path: str,
  770. ) -> FormControlConfig:
  771. return FormControlConfig(
  772. control_id=_require_nonempty_string(
  773. form.get(f"{prefix}_control_id"),
  774. f"{path}.{prefix}_control_id",
  775. ),
  776. value=_require_nonempty_string(
  777. form.get(f"{prefix}_value"),
  778. f"{path}.{prefix}_value",
  779. ),
  780. labels=_require_string_tuple(
  781. form.get(f"{prefix}_labels"),
  782. f"{path}.{prefix}_labels",
  783. ),
  784. )
  785. def _parse_mail_config(
  786. raw_mail: Any,
  787. *,
  788. path: str,
  789. ) -> OtpMailConfig | None:
  790. if raw_mail is None:
  791. return None
  792. mail = _require_mapping(raw_mail, path)
  793. sender = mail.get("sender", PRENOTAMI_OTP_SENDER)
  794. if not isinstance(sender, str) or sender.strip().casefold() != PRENOTAMI_OTP_SENDER:
  795. raise ItaProtocolError(
  796. "otp_sender_not_allowlisted",
  797. "mail sender must match Prenot@Mi's official OTP address",
  798. path=f"{path}.sender",
  799. )
  800. return OtpMailConfig(
  801. authorization_email=mail.get("authorization_email"),
  802. subject_keywords=mail.get("subject_keywords", "OTP Code"),
  803. body_keywords=mail.get("body_keywords", "OTP Code:"),
  804. expiry_seconds=mail.get("expiry_seconds", 300),
  805. authorization_source=mail.get("authorization_source", "configured"),
  806. )
  807. def _classify_inventory(
  808. slots_free: int,
  809. slots_remaining: int,
  810. *,
  811. path: str,
  812. ) -> InventoryState:
  813. if slots_free > 0 and slots_remaining >= 0:
  814. return InventoryState.AVAILABLE
  815. if slots_free == 0 and slots_remaining < 0:
  816. return InventoryState.UNAVAILABLE
  817. raise ItaProtocolError(
  818. "inventory_conflict",
  819. "slot counters do not match an observed allowlisted state",
  820. path=path,
  821. )
  822. def _parse_site_date(value: Any, path: str) -> date:
  823. if not isinstance(value, str) or not _SITE_DATE_PATTERN.fullmatch(value):
  824. raise ItaProtocolError(
  825. "date_format",
  826. "date must match DD/MM/YYYY 00:00:00",
  827. path=path,
  828. )
  829. try:
  830. return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
  831. except ValueError as exc:
  832. raise ItaProtocolError(
  833. "date_invalid",
  834. "date is not a real calendar date",
  835. path=path,
  836. ) from exc
  837. def _parse_site_time(value: Any, path: str) -> time:
  838. mapping = _require_mapping(value, path)
  839. hours = _require_int(_require_key(mapping, "Hours", path), f"{path}.Hours")
  840. minutes = _require_int(
  841. _require_key(mapping, "Minutes", path),
  842. f"{path}.Minutes",
  843. )
  844. seconds = _require_int(mapping.get("Seconds", 0), f"{path}.Seconds")
  845. milliseconds = _require_int(
  846. mapping.get("Milliseconds", 0),
  847. f"{path}.Milliseconds",
  848. )
  849. if seconds != 0 or milliseconds != 0:
  850. raise ItaProtocolError(
  851. "time_precision",
  852. "sub-minute slot precision is not supported by the observed protocol",
  853. path=path,
  854. )
  855. try:
  856. return time(hour=hours, minute=minutes)
  857. except ValueError as exc:
  858. raise ItaProtocolError(
  859. "time_invalid",
  860. "slot time is outside the 24-hour clock",
  861. path=path,
  862. ) from exc
  863. def _validate_date_range(
  864. start_day: date | None,
  865. end_day: date | None,
  866. ) -> tuple[date | None, date | None]:
  867. start = _require_date(start_day, "start_day") if start_day is not None else None
  868. end = _require_date(end_day, "end_day") if end_day is not None else None
  869. if start is not None and end is not None and start > end:
  870. raise ItaProtocolError(
  871. "date_range_invalid",
  872. "start_day must not be later than end_day",
  873. )
  874. return start, end
  875. def _date_in_range(
  876. value: date,
  877. start_day: date | None,
  878. end_day: date | None,
  879. ) -> bool:
  880. return (
  881. (start_day is None or value >= start_day)
  882. and (end_day is None or value <= end_day)
  883. )
  884. def _require_mapping(value: Any, path: str) -> Mapping[str, Any]:
  885. if not isinstance(value, Mapping):
  886. raise ItaProtocolError(
  887. "mapping_required",
  888. "value must be an object",
  889. path=path,
  890. )
  891. return value
  892. def _require_key(mapping: Mapping[str, Any], key: str, path: str) -> Any:
  893. if key not in mapping:
  894. raise ItaProtocolError(
  895. "field_missing",
  896. "required field is missing",
  897. path=f"{path}.{key}",
  898. )
  899. return mapping[key]
  900. def _require_nonempty_string(value: Any, path: str) -> str:
  901. if not isinstance(value, str) or not value.strip():
  902. raise ItaProtocolError(
  903. "string_required",
  904. "value must be a non-empty string",
  905. path=path,
  906. )
  907. return value.strip()
  908. def _require_string_tuple(value: Any, path: str) -> tuple[str, ...]:
  909. if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
  910. raise ItaProtocolError(
  911. "labels_required",
  912. "labels must be a non-empty array of strings",
  913. path=path,
  914. )
  915. labels = tuple(
  916. _require_nonempty_string(item, f"{path}[{index}]")
  917. for index, item in enumerate(value)
  918. )
  919. if not labels:
  920. raise ItaProtocolError(
  921. "labels_required",
  922. "labels must be a non-empty array of strings",
  923. path=path,
  924. )
  925. if len(set(labels)) != len(labels):
  926. raise ItaProtocolError(
  927. "labels_duplicate",
  928. "labels must not contain duplicates",
  929. path=path,
  930. )
  931. return labels
  932. def _is_positive_int(value: Any) -> bool:
  933. return isinstance(value, int) and not isinstance(value, bool) and value > 0
  934. def _require_positive_int(value: Any, path: str) -> int:
  935. if not _is_positive_int(value):
  936. raise ItaProtocolError(
  937. "positive_integer_required",
  938. "value must be a positive integer",
  939. path=path,
  940. )
  941. return value
  942. def _require_int(value: Any, path: str) -> int:
  943. if not isinstance(value, int) or isinstance(value, bool):
  944. raise ItaProtocolError(
  945. "integer_required",
  946. "value must be an integer",
  947. path=path,
  948. )
  949. return value
  950. def _require_nonnegative_int(value: Any, path: str) -> int:
  951. number = _require_int(value, path)
  952. if number < 0:
  953. raise ItaProtocolError(
  954. "nonnegative_integer_required",
  955. "value must be a non-negative integer",
  956. path=path,
  957. )
  958. return number
  959. def _require_bool(value: Any, path: str) -> bool:
  960. if not isinstance(value, bool):
  961. raise ItaProtocolError(
  962. "boolean_required",
  963. "value must be a boolean",
  964. path=path,
  965. )
  966. return value
  967. def _require_lookahead_months(value: Any, path: str) -> int:
  968. months = _require_positive_int(value, path)
  969. if months > MAX_LOOKAHEAD_MONTHS:
  970. raise ItaProtocolError(
  971. "lookahead_too_large",
  972. "lookahead exceeds the local scan safety limit",
  973. path=path,
  974. )
  975. return months
  976. def _require_date(value: Any, path: str) -> date:
  977. if not isinstance(value, date) or isinstance(value, datetime):
  978. raise ItaProtocolError(
  979. "date_required",
  980. "value must be a date",
  981. path=path,
  982. )
  983. return value
  984. def _require_date_tuple(value: Any, path: str) -> tuple[date, ...]:
  985. if not isinstance(value, tuple):
  986. raise ItaProtocolError(
  987. "date_tuple_required",
  988. "value must be a tuple of dates",
  989. path=path,
  990. )
  991. for index, item in enumerate(value):
  992. _require_date(item, f"{path}[{index}]")
  993. return value
  994. def _require_time(value: Any, path: str) -> time:
  995. if not isinstance(value, time):
  996. raise ItaProtocolError(
  997. "time_required",
  998. "value must be a time",
  999. path=path,
  1000. )
  1001. if value.second != 0 or value.microsecond != 0:
  1002. raise ItaProtocolError(
  1003. "time_precision",
  1004. "slot time must use minute precision",
  1005. path=path,
  1006. )
  1007. return value
  1008. __all__ = [
  1009. "CalendarDay",
  1010. "CalendarScanConfig",
  1011. "DateSelectionState",
  1012. "FormControlConfig",
  1013. "InventoryState",
  1014. "ItaCapability",
  1015. "ItaProtocolError",
  1016. "ItaRouteConfig",
  1017. "MAX_LOOKAHEAD_MONTHS",
  1018. "MAX_PROTOCOL_ITEMS",
  1019. "OtpMailConfig",
  1020. "PrecommitApproval",
  1021. "PRENOTAMI_OTP_SENDER",
  1022. "SlotCandidate",
  1023. "SlotSelectionState",
  1024. "approve_precommit",
  1025. "available_calendar_days",
  1026. "available_slot_candidates",
  1027. "decode_double_json_array",
  1028. "month_starts",
  1029. "parse_calendar_availability",
  1030. "parse_otp_body",
  1031. "parse_time_slots",
  1032. "resolve_route_config",
  1033. ]