From db1211166f9a7388a40d6197f50f5b52f8d57c36 Mon Sep 17 00:00:00 2001 From: Dave Liu <7david12liu@gmail.com> Date: Thu, 13 Aug 2026 16:44:37 -0700 Subject: [PATCH] Validate saved WebP responses (#639) --- IMPLEMENTATION_PLAN.md | 2 + SECURITY.md | 1 + SYSTEM_DESIGN.md | 2 + docs/officers/EVENTS_SHOP_MEMBERS.md | 102 ++++++++- .../account/memberDirectoryService.test.ts | 204 +++++++++++++++++- .../account/memberDirectoryService.ts | 16 +- 6 files changed, 322 insertions(+), 5 deletions(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 8a7e1090..4127210b 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -183,6 +183,8 @@ Exit gate: **MEMBERS-DIRECTORY-001J current source boundary:** [#637](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/637) changes only keyboard-focus recovery in the preserved connected Account branch. A user-initiated visibility, upload, or removal failure that becomes uncertain, a completed mutation followed by failed authoritative readback, or a definitive rejection followed by failed confirming read records one recovery-focus intent for the current mounted application-and-account lifetime and focuses the rendered **Reload settings** action. Choosing Reload records a replacement same-lifetime intent that is bound by the next load effect to its exact load identity; a guarded failure of that load focuses the replacement recovery action, including across repeated failures. Initial and background load failures have no intent and do not steal focus. A successful authoritative reload clears the intent and does not focus a removed recovery action or an unrelated ready control. Application change, account change, unmount, and stale load completion fail the explicit lifetime-and-load checks and remain focus-inert. The focus handoff creates no request ID, additional service call, mutation, automatic retry, draft restoration, or data URL. Existing uncertainty truth, generic failure truth, profile-read count, mutation/read/render/context fences, photo-draft handling, and ready-state focus rules remain unchanged. Availability stays `false`, so the default source branch and live #623 preview remain inert. #637 changes no data movement, page structure, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in, production data, deployment, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. +**MEMBERS-DIRECTORY-001K current source boundary:** [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) changes only inbound returned saved-photo admission in the preserved connected Account service. A photo's exact canonical base64 must decode to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, in addition to the existing exact object, MIME, dimensions, and version contract. A malformed response becomes only **Invalid member directory response.** without raw-byte, provider-value, or caught-detail output. The actual Account component-to-actual-service path, with only Firebase Functions mocked, proves mislabeled bytes stop before a saved-thumbnail image or data URL. Structurally admitted but browser-undecodable bytes retain the version-scoped, byte-free **Photo unavailable** fallback and **Remove current saved photo** action. Outbound JPG, PNG, and WebP upload admission and exact bytes remain unchanged. Availability stays `false`, so the default branch and live #623 preview remain inert. #639 changes no Account component, People finder, Function, Rule, index, schema, package, workflow, backend, provider, account, sign-in, production data, deployment, biometric processing, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. + ### Phase 5 — End-to-end qualification **Issue:** TEST-001 plus final closure evidence from all prior phases diff --git a/SECURITY.md b/SECURITY.md index 6ad3b91b..287627bc 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -106,6 +106,7 @@ These entries are implementation evidence, not a production risk-acceptance deci | Source-only reviewed-replacement containment for RISK-042 | MEMBERS-DIRECTORY-001H [#633](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/633) renames the destructive control **Remove current saved photo** and makes a confirmed remove plus authoritative readback preserve the exact current reading or ready component-memory draft identity while updating only the current saved-photo state and revision. The replacement creates no upload request or service call until a later explicit Save creates a new request ID, sends the same content type and bytes once, and uses the refreshed revision. Definitive rejection plus successful readback preserves the draft and associates the fixed error with Remove. Unknown outcome or failed post-mutation readback clears the draft identity, bytes, and data URL, hides photo and finder mutation controls, retains only the existing **Reload settings** recovery, and exposes no Save or duplicate-mutation retry. Confirmed readback moves focus to a still-current Remove action, otherwise an eligible Save action, otherwise the persistent Add/Replace input. Generated-only tests cover exact-byte/revision reuse, reading and ready drafts, no-draft and concurrent-photo focus, rejection, unknown/readback failure, unchanged visibility, stale contexts, reselection, unmount, and the unchanged unavailable default. | Intentionally preserving an unsaved replacement keeps private image bytes in component memory after the current saved photo is removed; it is not an upload, durable draft, server state, cancellation, or deletion proof outside the authoritative saved-photo readback. Context and generation fences limit stale restoration, while unknown state fails closed by discarding the draft. The source-controlled availability value stays `false`, and live #623 remains inert. No service/server contract, photo query, face recognition, matching, embedding, similarity, biometric processing, roster authority, membership proof, Firebase, provider, account, sign-in, production data, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use only generated non-face test images; do not inspect or upload a real photo. | | Source-only uncertain-change recovery containment for RISK-042 | MEMBERS-DIRECTORY-001I [#635](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/635) gives the preserved connected Account branch a component-lifetime uncertainty marker for an ordinary mutation failure or failed authoritative post-mutation readback. Failed and repeated **Reload settings** reads retain the fixed **We could not confirm that change** warning, keep photo and finder mutation controls hidden, and cannot restore discarded draft bytes or data URLs. A successful guarded authoritative profile read clears uncertainty and displays the returned state. Initial load failures and failed confirming reads after definitive mutation rejection remain generic unavailable; that generic message no longer globally promises **No setting was changed**. Reload creates no request ID or visibility, upload, or removal mutation. Generated-only tests cover repeated failures, eventual authoritative success, generic failures, zero mutation retries, discarded bytes, and stale application/account reload fences. | The marker preserves truthful uncertainty only within one mounted application-and-account component lifetime; it is not provider acknowledgement, durable mutation evidence, reconciliation, deletion proof, or authorization. Generic unavailable state deliberately does not infer whether a prior change occurred. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, service/server contract, Firebase, provider, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | | Source-only recovery-focus containment for RISK-042 | MEMBERS-DIRECTORY-001J [#637](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/637) gives the preserved connected Account branch one explicit recovery-focus intent for a user-initiated uncertain mutation, failed authoritative post-mutation readback, or failed confirming read after definitive rejection. The intent is tied to the current mounted application-and-account lifetime. A Reload-created intent is additionally bound by the next load effect to that exact load identity. Only the matching current unavailable or unknown transition focuses the rendered **Reload settings** action. Repeated failed reloads focus each replacement action. Initial or background load failure has no intent and does not steal focus; successful authoritative reload clears the intent without redirecting focus to an unrelated ready control. Application change, account change, unmount, and stale completion remain focus-inert. Generated-only tests cover all three mutations, both readback-failure classes, repeated uncertain and generic reload failures, successful reload, outside focus, application/account changes, unmount, zero retry or request-ID creation, and the unchanged unavailable default. | Programmatic focus is accessibility state, not provider acknowledgement, authorization, durable reconciliation, deletion proof, or evidence that a stale load became current. It creates no service call, mutation, automatic retry, draft restoration, data URL, or new data flow. The source-controlled availability value stays `false`, and live #623 remains inert. No page structure, service/server contract, Function, Rule, index, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | +| Source-only saved-photo response containment for RISK-042 | MEMBERS-DIRECTORY-001K [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) makes the preserved connected Account service admit an inbound returned saved photo only when the existing exact object, `image/webp`, 256×256 dimensions, and UUID version contract contains canonical base64 that decodes to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11. Any failure returns only **Invalid member directory response.** without rendering or logging raw bytes, a provider value, or caught detail. A real Account component-to-real-service test with only `firebase/functions` mocked proves mislabeled bytes stop before a saved-thumbnail image or data URL. Structurally admitted but browser-undecodable bytes retain the version-scoped, byte-free **Photo unavailable** fallback and enabled **Remove current saved photo** action without another callable. Outbound JPG, PNG, and WebP admission and exact bytes remain unchanged. | RIFF/WEBP markers are structural admission, not full decoding, safe image proof, authenticity, server-state proof, authorization, or provider acknowledgement; header-shaped hostile bytes can still reach the browser decoder, so the byte-free render fallback remains required. The source-controlled availability value stays `false`, and live #623 remains inert. No Function, Rule, index, schema, package, workflow, photo query, facial recognition, matching, embedding, similarity, biometric processing, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use only generated non-face test bytes; do not inspect or upload a real photo. | | Immediate Product-binding containment part of RISK-031 | PAY-PRODUCT-001A is tracked in live [#353](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/353). One dependency-free projection is used by the paid race and Shop checkout paths. A present stored Product link must be an own primitive non-empty string from 1 through 255 JavaScript code units and is copied without trimming, conversion, character restrictions, or `prod_` inference. Only a genuinely missing own field retains the compatibility Product-create path. Before any mapping write, a resolved Product must provide a bounded custom ID, exact Product kind, expected declared mode, and an installed-SDK 2xx response marker. Malformed stored links stop before token, registration/order identifier, Product-link or business-record write, or Stripe work; earlier access and request-count checks and their safety-counter writes may already have run. Malformed created results stop after at most one Product attempt but before mapping, Checkout Session, or business-record writes. | This structural containment does not prove provider origin, Stripe account ownership, intended catalog identity, metadata binding, Product status, price, dispatch, delivery, or reconciliation. A rejected create result may leave an orphaned Product; do not retry automatically. Anonymous clean-missing creation remains concurrency-prone and reachable from public traffic. Complete #113 inventory/disposition, authenticated idempotent catalog synchronization, Product-specific plan/pre-send/result/lost-acknowledgement/reconciliation controls, isolated staging, protected Firebase deployment, and provider proof before live commerce. | | Immediate current-handler containment part of RISK-003 | PAY-SESSION-001A is tracked in live [#357](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/357). The current paid race and Shop handlers build one immutable expectation before the Session call, catch rejection without opening it, and immediately project only a closed installed-SDK result. A result must match declared test/live mode, payment/open/unpaid state, exact cents, USD, buyer email, exact closed metadata, exact callbacks, a mode-compatible bounded Session ID, one canonical HTTPS capability at the hard-coded default `checkout.stripe.com` origin, and an installed-SDK 200 marker. Only copied ID/URL values continue; records store the ID but never the URL. Invalid results create no registration/order record and return one fixed unknown-result message. The website makes rejection or a missing paid URL terminal for that page visit, retains the form, and blocks a second direct handler call. | This is a narrow legacy compatibility stop, not trusted provider/account origin, deterministic business idempotency, dispatch/delivery proof, durable result evidence, payment proof, or adoption of the unused C4 chain. The Session call occurs first, so a rejected result may leave a payable orphan; earlier rate-counter, token/identifier, and lazy Product-mapping effects may remain. Reload, another tab/device, or a scripted caller bypasses the page lock. A configured Stripe custom checkout domain is blocked until #113 and a protected configuration boundary approve it. Complete PAY-002C/D persistence-first sagas, trusted C4 controller/result persistence, reconciliation, protected staging/deployment, provider readback, and exact website/Firebase/live proof. | | Immediate pre-render browser containment part of RISK-003 | PAY-SESSION-001B is tracked in live [#503](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/503). Each current public race and Shop page now keeps one component-local in-memory marker. After existing local checks admit a request, the handler sets that marker synchronously before analytics or its first Checkout promise can settle. A same-action or later submission on that mounted page is inert, including the gap before React renders the existing pending disabled button. Focused actual-route tests prove one service/analytics attempt across same-action and post-render repeats; preserve free-participant, volunteer-without-price-tier, and both paid-link navigation branches; and prove local waiver/native-disabled paths do not consume an attempt. | This browser marker is not a server boundary, durable idempotency key, provider dispatch/result record, business-state lock, payment proof, or reconciliation. It never releases during the mounted page visit because the admitted result must navigate or enter #357's terminal unknown-result state. Existing form controls other than the submit button remain editable. Reload, a remount, another tab/device, a script, or a direct service caller can bypass it. A same-mounted route change instead stays locked, and this slice does not fence an older pending result from that changed route. Complete PAY-002C/D persistence-first deterministic commands, durable replay/reconciliation, protected deployment, and exact website/Firebase/Stripe/live proof. | diff --git a/SYSTEM_DESIGN.md b/SYSTEM_DESIGN.md index e987f7b8..5b7de43c 100644 --- a/SYSTEM_DESIGN.md +++ b/SYSTEM_DESIGN.md @@ -699,6 +699,8 @@ WEB-002C [#623](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/623) publi **MEMBERS-DIRECTORY-001J profile-recovery focus — SOURCE ONLY:** [#637](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/637) changes only the preserved connected Account recovery focus. When a user-initiated visibility, upload, or removal mutation has an unknown outcome, when a completed mutation's authoritative readback fails, or when a definitive rejection cannot be confirmed by a profile read, the component records one recovery-focus intent tied to the current mounted application-and-account lifetime before rendering **Reload settings**. The rendered recovery button receives focus after either the uncertain-change or generic unavailable transition. Choosing Reload replaces that intent with a same-lifetime reload intent, and the next load effect binds it to that exact load identity; only a guarded failure of that current load focuses the replacement Reload button. Repeated failed reloads repeat that exact-load handoff. An initial or background load has no recovery intent and does not steal focus. A successful authoritative reload clears the intent, removes the recovery action, and does not redirect focus to an unrelated ready control. Application change, account change, unmount, or an obsolete load clears or fails the lifetime-and-load checks, so an older completion cannot move focus in a new context. Focus creates no request ID, service call, mutation, automatic retry, draft restoration, or data URL beyond the existing profile read. Existing uncertainty copy, mutation/read/render fences, draft rules, and ready-state focus behavior otherwise remain unchanged. This accessibility-only source change adds no data movement, page structure, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in state, production data, deployment, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. +**MEMBERS-DIRECTORY-001K saved-photo response admission — SOURCE ONLY:** [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) changes only the preserved connected Account service boundary for an inbound returned saved photo. After the existing exact-object and `image/webp` checks, canonical base64 must decode to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11 before it can become `MemberDirectoryProfile.photo`. Every failure still becomes only **Invalid member directory response.**; the client does not render or log raw bytes, a provider value, or caught detail. Tests import the actual Account profile component and actual service while mocking only `firebase/functions`: mislabeled canonical bytes stop at the service and produce the existing generic unavailable state without a saved-thumbnail image or data URL. This structural admission is not browser decoding. Header-valid bytes may reach the existing fixed `data:image/webp;base64,` image; if the browser cannot display them, the version-scoped, byte-free **Photo unavailable** fallback removes the data URL and keeps **Remove current saved photo** available without another callable. The returned-photo change does not alter outbound JPG, PNG, or WebP admission or bytes. It adds no Function, Rule, index, schema, package, workflow, photo query, facial recognition, matching, embedding, similarity, biometric processing, provider, account, sign-in state, production-data action, deployment, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. + ### 8.0a Provider-neutral membership authority and entitlement — SOURCE ONLY, UNUSED MEMBERS-IDENTITY-001A [#208](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/208), with its command-order correction in MEMBERS-IDENTITY-001H [#451](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/451), defines one unused pure contract that keeps a stable MPRC membership separate from the Firebase account used to sign in. A membership record can exist and receive monotonic term decisions without a UID. Such a record grants no website entitlement. Google, WhatsApp, Strava, email equality, a profile role, and any browser field remain projections or inputs to future reviewed workflows; none is membership authority. diff --git a/docs/officers/EVENTS_SHOP_MEMBERS.md b/docs/officers/EVENTS_SHOP_MEMBERS.md index 8d4452fd..535131dd 100644 --- a/docs/officers/EVENTS_SHOP_MEMBERS.md +++ b/docs/officers/EVENTS_SHOP_MEMBERS.md @@ -2472,7 +2472,7 @@ flowchart TD Connected -. "never photo search or proof" .-> Official["Membership, role, payment, or official records"] ``` -Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. +Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; source-only #639 admits a returned saved photo only when its canonical decoded bytes total 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, maps every other returned byte shape to one fixed byte-free failure before the Account image path, preserves the version-scoped **Photo unavailable** fallback and Remove action for structurally admitted bytes the browser cannot display, and leaves outbound uploads unchanged; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. Officer review steps for the #621 frontend preview: @@ -3041,6 +3041,106 @@ Officer source-review procedure for MEMBERS-DIRECTORY-001J [#637] profile-recove **Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, recovery focus moved across applications or accounts, Reload sent a mutation, an initial failure stole unrelated focus, or connected behavior became available. +Officer source-review procedure for MEMBERS-DIRECTORY-001K [#639] saved-photo response admission — connected source only, **NOT LIVE**: + +**Purpose:** let a backup officer verify from specialist-prepared evidence that the preserved connected Account interface rejects clearly mislabeled returned saved-photo bytes before they reach the page while retaining the existing safe display fallback for structurally admitted bytes the browser cannot decode, without connecting the feature, changing outbound uploads, using a real account or photo, or changing production. + +**Approvers:** membership lead, privacy owner, and platform/security owner. + +**Prerequisites:** #637 is reviewed and merged. Ask the platform owner or testing specialist for the exact #639 source candidate, the named generated-only test output, the trustworthy old-source failure, and a redacted written synthetic-behavior report. The specialist runs the tests and records the evidence. The backup officer reviews that written evidence without a terminal or test harness. Keep the source-controlled availability value `false`. Do not sign in to production, use a real name or photo, call production Firebase, or change production data. + +1. Keep the complete profile-photo and People-finder feature marked **NOT AVAILABLE YET**. +2. Ask the platform owner for the exact #639 issue. +3. Ask the platform owner for the reviewed pull request. +4. Ask the platform owner for the candidate or merge commit. +5. Ask the testing specialist for the named MEMBERS-DIRECTORY-001K test output. +6. Ask the testing specialist for the trustworthy old-source failure. +7. Ask the testing specialist for the redacted written synthetic-behavior report. +8. Confirm the report names the specialist who ran the tests. +9. Confirm the evidence uses only a made-up account. +10. Confirm the evidence uses only generated non-face image bytes. +11. Confirm the source-controlled availability value remains byte-for-byte `false`. +12. Confirm the last verified production deployment remains inert #623 deploy `6a7e072f8f346b0008510d29`. +13. Confirm the named bridge imports the actual Account profile component. +14. Confirm the named bridge imports the actual member-directory service. +15. Confirm the named bridge mocks only Firebase Functions transport. +16. Confirm the named bridge makes no real Firebase request. +17. Confirm the old source admits canonical non-WebP bytes into the saved-thumbnail image path. +18. Confirm the new source rejects those mislabeled returned bytes before creating a saved-thumbnail image. +19. Confirm the new source rejects those mislabeled returned bytes before creating an image data URL. +20. Confirm that rejection renders only the existing generic unavailable Account state. +21. Confirm the service rejection is exactly **Invalid member directory response.** +22. Confirm the fixed rejection contains no raw image bytes. +23. Confirm the fixed rejection contains no provider value. +24. Confirm the fixed rejection contains no caught detail. +25. Confirm the source adds no logging path for the rejected value. +26. Confirm canonical bytes with an exact 12-byte `RIFF`/`WEBP` envelope are admitted. +27. Confirm canonical bytes with an exact 65,536-byte `RIFF`/`WEBP` envelope are admitted. +28. Confirm empty returned bytes are rejected. +29. Confirm a returned envelope shorter than 12 bytes is rejected. +30. Confirm a returned envelope with the wrong bytes 0–3 is rejected. +31. Confirm a returned envelope with the wrong bytes 8–11 is rejected. +32. Confirm noncanonical returned base64 is rejected. +33. Confirm a 65,537-byte returned envelope is rejected. +34. Confirm the exact returned `image/webp` requirement remains. +35. Confirm the exact returned 256×256 dimensions remain. +36. Confirm the exact returned version requirement remains. +37. Confirm the exact returned-photo object requirement remains. +38. Confirm a returned-photo accessor is rejected generically. +39. Confirm a hostile returned-photo object is rejected generically. +40. Confirm a structurally admitted saved photo first uses the fixed WebP image type. +41. Confirm a synthetic browser decode failure removes that saved image. +42. Confirm a synthetic browser decode failure removes its data URL. +43. Confirm the replacement says **Photo unavailable**. +44. Confirm the replacement contains no image bytes. +45. Confirm **Remove current saved photo** remains enabled. +46. Confirm the display failure creates no additional callable. +47. Confirm the existing fallback remains scoped to the failed photo version. +48. Confirm a different later photo version retains its existing fresh render attempt. +49. Confirm canonical non-RIFF outbound WebP upload bytes still reach the callable unchanged. +50. Confirm outbound JPEG admission remains unchanged. +51. Confirm outbound PNG admission remains unchanged. +52. Confirm outbound WebP admission remains unchanged. +53. Confirm the source diff changes no Account component. +54. Confirm the source diff changes no People-finder page. +55. Confirm the source diff changes no Function. +56. Confirm the source diff changes no Rule. +57. Confirm the source diff changes no index. +58. Confirm the source diff changes no schema. +59. Confirm the source diff changes no package. +60. Confirm the source diff changes no workflow. +61. Confirm the source diff changes no release control. +62. Confirm the source diff adds no photo query. +63. Confirm the source diff adds no face recognition. +64. Confirm the source diff adds no image matching. +65. Confirm the source diff adds no image embedding. +66. Confirm the source diff adds no similarity scoring. +67. Confirm the source diff adds no biometric processing. +68. Confirm the default Account branch obtains no directory-service context. +69. Confirm the default Account branch creates no directory request number. +70. Confirm the default Account branch calls no directory service. +71. Record the source change as its own state. +72. Record the named test results as their own state. +73. Record whether the change merged as its own state. +74. Record whether any website artifact was published as its own state. +75. Record the exact `runmprc.com` revision as its own state. +76. Record whether Firebase was deployed as its own state. +77. Record whether an outside provider was configured as its own state. +78. Record whether an account or sign-in state changed as its own state. +79. Record whether production data changed as its own state. +80. Record whether connected behavior became available as its own state. +81. Stop before changing availability, Firebase, a provider, an account, production data, or the live website. + +**Expected result:** the reviewed connected source admits an inbound returned saved photo only when its existing exact object, WebP MIME, dimensions, and version contract contains canonical decoded bytes from 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11. Other returned bytes become only **Invalid member directory response.** and the generic unavailable Account state without a saved-thumbnail image, data URL, raw bytes, provider value, caught detail, or log. Structural admission is not full decoding. If the browser cannot display admitted bytes, the image and data URL leave the page, the version-scoped byte-free **Photo unavailable** fallback appears, and **Remove current saved photo** remains enabled without another callable. Outbound JPG, PNG, and WebP admission and exact upload bytes remain unchanged. Availability remains `false`; the default branch obtains no directory-service context, creates no request number, and calls no directory service; and live #623 remains inert. The backend and connected behavior remain **NOT AVAILABLE YET**. + +**Stop conditions:** a real account, name, or photo; production sign-in; direct production Firebase access; malformed returned bytes that create a saved-thumbnail image or data URL; a rejection that renders or logs raw bytes, a provider value, or caught detail; admitted bytes outside 12 through 65,536; missing `RIFF` or `WEBP` checks; a browser decode failure that leaves the data URL rendered, omits **Photo unavailable**, or removes the Remove action; an extra callable caused by image failure; changed outbound JPG, PNG, or WebP admission or bytes; a photo query; face recognition, matching, embedding, similarity scoring, or biometric processing; a Function, Rule, index, schema, package, workflow, release-control, provider, account, sign-in, production-data, or website change; an availability flip; use of a terminal or test harness by the backup officer; or a claim that source, tests, or merge means the feature is live. + +**Success proof:** record the exact #639 issue, reviewed pull request and commit; trustworthy old-source failure; green separately named MEMBERS-DIRECTORY-001K focused tests; green full frontend tests; type-checking; scoped lint; diagnostic production build; unchanged lint baseline; workflow checks; diff-check; independent privacy/security, frontend, response-contract, and backup-officer reviews; and exact-main CI if merged. Record source, tests, merge, website publication, exact `runmprc.com` revision, Firebase deployment, provider configuration, account/sign-in change, production-data action, and connected/live behavior separately. Record the unchanged `false` availability value and unchanged #623 deploy separately. Source and tests do not prove merge; merge does not prove publication; publication does not prove Firebase, provider, account, data, or connected-live behavior. Final connection and live proof remain #507 work. + +**Undo:** use one reviewed service-and-documentation revert or safe roll-forward. Confirm the default disabled branch still makes zero directory calls. No Firebase, provider, account, or production-data undo is needed because #639 changes source only. Undo must not turn clearly mislabeled returned bytes into a saved-thumbnail image or change outbound upload bytes. + +**Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, raw returned bytes or provider detail reached the page or a log, malformed bytes entered the saved-thumbnail image path, outbound uploads changed, or connected behavior became available. + ## Admin screens — NOT AVAILABLE YET Admin event and product editors exist in source, but their live permissions, backup, preview, and rollback behavior have not been approved. Saving can write directly to production Firestore. Officers must not use these screens as a continuity procedure yet. diff --git a/src/services/account/memberDirectoryService.test.ts b/src/services/account/memberDirectoryService.test.ts index e52a685c..f27e40ef 100644 --- a/src/services/account/memberDirectoryService.test.ts +++ b/src/services/account/memberDirectoryService.test.ts @@ -1,6 +1,11 @@ /* eslint-env jest */ +import React from 'react'; +import { + fireEvent, render, screen, waitFor, +} from '@testing-library/react'; import { getFunctions, httpsCallable } from 'firebase/functions'; +import MemberDirectoryProfile from '../../pages/account/MemberDirectoryProfile'; import { createMemberDirectoryRequestId, getMyMemberDirectoryProfile, @@ -18,7 +23,12 @@ jest.mock('firebase/functions', () => ({ const app = { name: 'synthetic-app' } as any; const REQUEST_ID = '123e4567-e89b-42d3-a456-426614174000'; const SECOND_REQUEST_ID = '123e4567-e89b-42d3-b456-426614174001'; -const PHOTO_BYTES = btoa('synthetic processed webp bytes'); + +function webPEnvelope(byteLength: number): string { + return btoa(`RIFF${'\0'.repeat(4)}WEBP${'\0'.repeat(byteLength - 12)}`); +} + +const PHOTO_BYTES = webPEnvelope(32); const PHOTO = { contentType: 'image/webp', base64Data: PHOTO_BYTES, @@ -40,6 +50,13 @@ const MUTATION_STATE = { hasPhoto: true, }; +function profileWithPhoto(base64Data: string) { + return { + ...PROFILE, + photo: { ...PHOTO, base64Data }, + }; +} + describe('member directory callable service', () => { beforeEach(() => { jest.clearAllMocks(); @@ -269,3 +286,188 @@ describe('member directory callable service', () => { expect(isDefinitiveMemberDirectoryRejection(hostile)).toBe(false); }); }); + +describe('MEMBERS-DIRECTORY-001K saved WebP response boundary', () => { + beforeEach(() => { + jest.clearAllMocks(); + (getFunctions as jest.Mock).mockReturnValue({ name: 'synthetic-functions' }); + }); + + test.each([ + ['the exact 12-byte structural envelope', webPEnvelope(12)], + ['the exact 65,536-byte response limit', webPEnvelope(64 * 1024)], + ])('accepts %s', async (_label, base64Data) => { + const response = profileWithPhoto(base64Data); + const callable = jest.fn().mockResolvedValue({ data: response }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + await expect(getMyMemberDirectoryProfile(app)).resolves.toEqual(response); + expect(callable).toHaveBeenCalledTimes(1); + }); + + test.each([ + ['empty bytes', ''], + ['a truncated 11-byte envelope', btoa(`RIFF${'\0'.repeat(4)}WEB`)], + ['the wrong RIFF marker', btoa(`NOPE${'\0'.repeat(4)}WEBP`)], + ['the wrong WEBP marker', btoa(`RIFF${'\0'.repeat(4)}NOPE`)], + ['non-canonical base64', 'Zh=='], + ['a 65,537-byte response', webPEnvelope((64 * 1024) + 1)], + ])('rejects %s with the fixed response error', async (_label, base64Data) => { + const callable = jest.fn().mockResolvedValue({ + data: profileWithPhoto(base64Data), + }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + await expect(getMyMemberDirectoryProfile(app)) + .rejects.toThrow('Invalid member directory response.'); + }); + + test.each([ + ['the wrong returned MIME type', { ...PHOTO, contentType: 'image/png' }], + ['the wrong width', { ...PHOTO, width: 255 }], + ['the wrong height', { ...PHOTO, height: 255 }], + ['an uppercase version', { ...PHOTO, version: REQUEST_ID.toUpperCase() }], + ['an extra field', { ...PHOTO, providerDetail: 'not allowed' }], + ])('preserves exact photo validation for %s', async (_label, photo) => { + const callable = jest.fn().mockResolvedValue({ + data: { ...PROFILE, photo }, + }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + await expect(getMyMemberDirectoryProfile(app)) + .rejects.toThrow('Invalid member directory response.'); + }); + + test('rejects returned photo prototypes, accessors, and hostile objects generically', async () => { + const prototypePhoto = Object.assign(Object.create(null), PHOTO); + const accessorPhoto = { ...PHOTO } as Record; + Object.defineProperty(accessorPhoto, 'base64Data', { + enumerable: true, + get: () => PHOTO_BYTES, + }); + const hostilePhoto = new Proxy({}, { + ownKeys() { + throw new Error('synthetic-provider-canary'); + }, + }); + const callable = jest.fn() + .mockResolvedValueOnce({ data: { ...PROFILE, photo: prototypePhoto } }) + .mockResolvedValueOnce({ data: { ...PROFILE, photo: accessorPhoto } }) + .mockResolvedValueOnce({ data: { ...PROFILE, photo: hostilePhoto } }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + await expect(getMyMemberDirectoryProfile(app)) + .rejects.toThrow('Invalid member directory response.'); + await expect(getMyMemberDirectoryProfile(app)) + .rejects.toThrow('Invalid member directory response.'); + await expect(getMyMemberDirectoryProfile(app)) + .rejects.toThrow('Invalid member directory response.'); + }); + + test('preserves canonical non-RIFF outbound WebP upload bytes unchanged', async () => { + const base64Data = btoa('canonical outbound WebP bytes without a RIFF marker'); + const request = { + requestId: REQUEST_ID, + expectedRevision: 2, + contentType: 'image/webp' as const, + base64Data, + }; + const callable = jest.fn().mockResolvedValue({ data: MUTATION_STATE }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + await expect(setMyMemberDirectoryPhoto(app, request)) + .resolves.toEqual(MUTATION_STATE); + expect(callable).toHaveBeenCalledWith(request); + }); + + test('keeps mislabeled saved bytes out of the actual Account photo DOM', async () => { + const callable = jest.fn().mockResolvedValue({ + data: profileWithPhoto(btoa(`NOPE${'\0'.repeat(4)}WEBP`)), + }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + render(React.createElement(MemberDirectoryProfile, { + app, + uid: 'synthetic-member', + displayName: 'Synthetic Member', + backendAvailable: true, + })); + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'We could not load your profile photo and officer finder settings.', + ); + expect(screen.queryByRole('img', { + name: 'Your current profile thumbnail', + })).not.toBeInTheDocument(); + expect(document.querySelector('img[src^="data:image/webp;base64,"]')) + .not.toBeInTheDocument(); + expect(httpsCallable).toHaveBeenCalledTimes(1); + expect(callable).toHaveBeenCalledTimes(1); + }); + + test('keeps the byte-free fallback and Remove after browser decode failure', async () => { + const base64Data = webPEnvelope(12); + const callable = jest.fn().mockResolvedValue({ + data: profileWithPhoto(base64Data), + }); + (httpsCallable as jest.Mock).mockReturnValue(callable); + + render(React.createElement(MemberDirectoryProfile, { + app, + uid: 'synthetic-member', + displayName: 'Synthetic Member', + backendAvailable: true, + })); + + const image = await screen.findByRole('img', { + name: 'Your current profile thumbnail', + }); + expect(image).toHaveAttribute( + 'src', + `data:image/webp;base64,${base64Data}`, + ); + + fireEvent.error(image); + + await waitFor(() => expect(screen.getByRole('img', { + name: 'Saved profile photo could not be displayed', + })).toHaveTextContent('Photo unavailable')); + expect(document.querySelector('img[src^="data:image/webp;base64,"]')) + .not.toBeInTheDocument(); + expect(screen.getByRole('button', { + name: 'Remove current saved photo', + })).toBeEnabled(); + expect(httpsCallable).toHaveBeenCalledTimes(1); + expect(callable).toHaveBeenCalledTimes(1); + }); + + test('keeps the default unavailable preview free of context, IDs, and calls', () => { + const originalCrypto = Object.getOwnPropertyDescriptor(globalThis, 'crypto'); + const randomUUID = jest.fn(() => REQUEST_ID); + const getRandomValues = jest.fn((bytes: Uint8Array) => bytes); + Object.defineProperty(globalThis, 'crypto', { + configurable: true, + value: { getRandomValues, randomUUID }, + }); + try { + render(React.createElement(MemberDirectoryProfile, { + app: null as any, + uid: '', + displayName: null, + })); + + expect(screen.getByText('Interface preview — not connected yet.')) + .toBeInTheDocument(); + expect(randomUUID).not.toHaveBeenCalled(); + expect(getRandomValues).not.toHaveBeenCalled(); + expect(getFunctions).not.toHaveBeenCalled(); + expect(httpsCallable).not.toHaveBeenCalled(); + } finally { + if (originalCrypto) { + Object.defineProperty(globalThis, 'crypto', originalCrypto); + } else { + delete (globalThis as { crypto?: Crypto }).crypto; + } + } + }); +}); diff --git a/src/services/account/memberDirectoryService.ts b/src/services/account/memberDirectoryService.ts index b2da313d..88ff73f3 100644 --- a/src/services/account/memberDirectoryService.ts +++ b/src/services/account/memberDirectoryService.ts @@ -121,7 +121,7 @@ function isValidRevision(value: unknown): value is number { && !Object.is(value, -0); } -function canonicalBase64DecodedBytes(value: unknown, maximum: number): number | null { +function canonicalBase64DecodedBytes(value: unknown, maximum: number): string | null { if ( typeof value !== 'string' || value.length === 0 @@ -137,12 +137,18 @@ function canonicalBase64DecodedBytes(value: unknown, maximum: number): number | || decoded.length > maximum || btoa(decoded) !== value ) return null; - return decoded.length; + return decoded; } catch { return null; } } +function hasWebPEnvelope(decodedBytes: string): boolean { + return decodedBytes.length >= 12 + && decodedBytes.slice(0, 4) === 'RIFF' + && decodedBytes.slice(8, 12) === 'WEBP'; +} + function readMutationState(value: unknown): MemberDirectoryMutationState { const data = readExactPlainObject(value, [ 'schemaVersion', @@ -173,9 +179,13 @@ function readPhoto(value: unknown): MemberDirectoryPhoto { 'height', 'version', ]); + const decodedBytes = data.contentType === 'image/webp' + ? canonicalBase64DecodedBytes(data.base64Data, MAX_RETURNED_PHOTO_BYTES) + : null; if ( data.contentType !== 'image/webp' - || canonicalBase64DecodedBytes(data.base64Data, MAX_RETURNED_PHOTO_BYTES) === null + || decodedBytes === null + || !hasWebPEnvelope(decodedBytes) || data.width !== 256 || data.height !== 256 || typeof data.version !== 'string'