3. Token-Based Onboarding & Member Declaration Forms — Token Mode
Repository:
Microservices (planovi-microservices)• Rule Prefix:BR-DEC• Documented Rules: 10 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
- Problem Solved: Delivers secure, time-limited, multi-step declaration and onboarding forms to cooperative members (for joining an energy cooperative or correcting rejected declarations), new SaaS company admins (post-Stripe legal data collection: NIP/KRS/address), and board members (previewing templates or filling/editing paper declarations on a member’s behalf with full change history).
- Actors:
- Supabase Edge Functions (
planovi-backend):send-onboarding-invitation,send-correction-request-notice,create-form-preview(via_shared/form_link.ts) write token JSON payloads viadealflow/api/form-writer.php. - Cooperative Member / Prospective Company Admin: Opens
dealflow/offer.php?token={64-hex}, completes multi-step fields (including handwritten signature canvas), consents to RODO, and submits. - Cooperative Board Admin: Opens preview (
preview: true) or board-edit (mode: 'admin_edit') links generated from the Planovi panel.
- Supabase Edge Functions (
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Feature A: Write Token Form Snapshot (
POST dealflow/api/form-writer.php)- Trigger: Edge Functions in
planovi-backendcallPOST /dealflow/api/form-writer.phpwithX-Api-Secretheader. - Validation: Constant-time
hash_equals($expectedSecret, $providedSecret)againstDEALFLOW_API_SECRET(401) →POSTonly (405) → JSON body must containtokenanddata(400) →tokenstripped to lowercase hex[a-f0-9]must be>= 32chars (400) →../datamust exist (500). - State Change: Writes
dealflow/data/{token}.jsonusingLOCK_EXandJSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE. - Response: HTTP
200{"success": true, "file": "{token}.json", "bytes": N}.
- Trigger: Edge Functions in
- Feature B: Token Validation & Mode Resolution (
GET dealflow/offer.php?token={hex})- Trigger: Visitor opens link with
>= 32lowercase hex chars in?token=. - Validation Pipeline (ordered, short-circuiting):
- File
dealflow/data/{cleanToken}.jsonmust exist → else"Link wygasł lub jest nieprawidłowy. Poproś o nowe zaproszenie." - JSON must decode to array → else
"Błąd odczytu danych formularza. Skontaktuj się z administratorem." !empty($tokenFormData['revoked'])→"Ten link został zastąpiony nowym. Użyj linku z najnowszego e-maila."isset($tokenFormData['expires_at']) && strtotime($tokenFormData['expires_at']) < time()→ preview:"Podgląd wygasł. Otwórz podgląd ponownie z panelu."; standard:"Ten link wygasł (ważny 72h). Poproś o nowe zaproszenie."- Live DB usage check (skipped for
IS_PREVIEWandIS_ADMIN_EDIT):POST {SUPABASE_URL}/rest/v1/rpc/onboarding_token_statuswith{"p_token": $cleanToken}(timeout5s,SUPABASE_ANON_KEY). If$dbRes[0]['used_at']is non-empty →"Ta deklaracja została już wysłana. Dziękujemy!"
- File
- Mode & Target Function Resolution (
offer.php:98, 138-150):- Default:
submit-member-declaration - If
mode === 'admin_edit':IS_ADMIN_EDIT = true→update-member-declaration - If
!empty($tokenFormData['deal_id']): overrides tosubmit-company-details - If
!empty($tokenFormData['preview']):IS_PREVIEW = true(submission disabled)
- Default:
- Trigger: Visitor opens link with
- Feature C: Multi-Step Form Rendering, Rich Labels, Prefill & Signature Pad
- Step Grouping: Groups visible fields by
step_idaccording tosteps[]order; fields with unknown/missingstep_idappend to a final fallback step. Empty steps are dropped. If> 1step, renders clickable step chips (compactnumeric chips when> 4steps),"Krok X z N","← Wstecz","Dalej →". Consent/board options and submit button appear only on the last step. - Field Types:
info(read-only notice box, nodata-fid, never validated/submitted),text,email,phone(tel),number(type="text" inputmode="decimal"accepting Polish decimal comma),date,boolean(Tak/Nieradio pair),address(3-row textarea),signature(HTML5<canvas>600×150 CSS scaled bydevicePixelRatio || 2, with preview/change/clear controls and legacy text-signature compatibility). - Prefill & Correction Banner: Pre-populates answers from
values[field_id]. Ifcorrection_reasonis non-empty, renders amber"Uwagi zarządu"callout banner.
- Step Grouping: Groups visible fields by
- Feature D: Client Validation, Signature Upload & Submission
- Validation: Advancing via
"Dalej"or clicking a forward step chip validates every prior step (goToStep()stops at first failing step unlessIS_PREVIEW). Final submit validates ALL fields across ALL steps at once (skippingrequiredchecks inIS_ADMIN_EDITso board can save partial paper declarations) plus#tok-rodocheckbox (non-admin modes only). Pressing Enter before the last step triggersgoNext()instead of submitting. - Signature Upload: Before calling the Edge Function, iterates
values[]; any string starting withdata:image/png;base64,is decoded to binaryBlob(image/png) and uploaded viaPOST {SUPABASE_URL}/storage/v1/object/company-media/{COMPANY_ID}/signatures/{SESSION_ID}_{field_id}_{timestamp}.png(x-upsert: true,SUPABASE_ANON_KEY). On HTTP 2xx, replaces base64 with public Storage URL; on failure/exception, silently falls back to inline base64 data URL (offer.php:1388-1424). - Submission:
POST {submitFnUrl}withapikey+Authorization: Bearer {ANON_KEY}:- Member / Company mode:
{ token, values } - Admin edit mode:
{ admin_edit_token, values, notify, submit_on_behalf, note }
- Member / Company mode:
- Response & Error Handling:
data.success: Hides form, shows#tok-success(in admin mode displays changed field count,submitted_on_behalfbadge,email_sentbadge, and anydata.warnings).data.already_submittedOR (!IS_ADMIN_EDIT && res.status === 409): Hides form, shows"Deklaracja już wysłana ✓".422/ other server error: Keeps form open with all typed data intact, mapsdata.errors[]({field_id, message}) to per-field inline errors, jumps to the step containing the first error, and shows summary banner.- Network error: Keeps form and typed values intact, shows
"Brak połączenia z serwerem."banner.
- Validation: Advancing via
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-DEC-01(Token Format & Security): Tokens must be>= 32lowercase hex chars ([a-f0-9]).form-writer.php:37uses constant-timehash_equalsonX-Api-SecretvsDEALFLOW_API_SECRETand writes withLOCK_EX(form-writer.php:81).BR-DEC-02(Field Visibility & Calculated Field Filtering):offer.php:176-181always strips fields withfield_type === 'calculated'. Fields withfield_visibility === 'admin'are stripped unless$IS_ADMIN_EDIT === true(in which case they display an orange"zarząd"badge,offer.php:738-740).BR-DEC-03(Dual-Pass HTML Allowlist Sanitizer):planovi_clean_label_html()(offer.php:39-86) truncates input to20,000bytes, strips<script>/<style>blocks, allows ONLY tagsp,br,b(strong→b),i(em→i),u,a,ul,ol,li, enforceshrefmatching^(https://|mailto:)(injectingtarget="_blank" rel="noopener noreferrer nofollow"), balances unclosed tags via a stack, and returns''if stripped text is empty.BR-DEC-04(Preview URL Allowlist):planovi_clean_preview_url()(offer.php:89-93) accepts onlyhttps://URLs<= 2048chars with a real domain TLD (\.[A-Za-z]{2,}), rejecting HTTP, IPs, localhost, and credentialed URLs.BR-DEC-05(Field Type Validation Parity with_shared/declaration_values.ts):fieldProblem()(offer.php:1176-1203):- Empty value: error
'To pole jest wymagane.'only if!IS_ADMIN_EDIT && data-req === '1'. number: strips spaces & NBSP (\u00A0), converts,to., checksNumber.isFinite(n)→ else'Wpisz liczbę (np. 12 lub 12,5).'.date: matches/^(\d{4})-(\d{2})-(\d{2})/and verifies exact UTC calendar validity (rejects e.g.2026-02-30) → else'Wpisz poprawną datę (RRRR-MM-DD).'.email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/→ else'Nieprawidłowy adres e-mail.'.phone:>= 7digits AND matches/^[+\d][\d\s\-()]*$/→ else'Nieprawidłowy numer telefonu.'.boolean,address,signature,text: any non-empty value accepted.
- Empty value: error
BR-DEC-06(Emptied Optional Fields Clear Prior Values): During corrections or board edits, empty optional fields explicitly emit{ field_id, value: null }(offer.php:1376-1379) so backend clears previously stored values instead of ignoring them.BR-DEC-07(Board Paper-Declaration Checkbox Gate): The"Deklaracja złożona na papierze – przekaż do recenzji"checkbox (#adm-paper, default checked) is rendered ONLY inIS_ADMIN_EDITwhensession_statusis in['started', 'declaration_uploaded', 'form_ready'](offer.php:863).BR-DEC-08(Compact Step Chips Threshold): Whencount($tokenSteps) > 4,.tok-stepsreceives class.compact, displaying step numbers only with full titles intitle/aria-labeltooltips (offer.php:679,536-537).BR-DEC-09(Signature Preview Classification): Existing signature value renders as<img>if it starts withhttp://,https://,data:image, or contains/storage/; otherwise renders as italicized legacy text with"(tekst z poprzedniej wersji formularza)"(offer.php:767-786).BR-DEC-10(Live Error Recheck Without Blur Layout Shift): Field errors re-validate oninput(orchangefor radios) ONLY while the error element is currently visible (offer.php:1309-1319), explicitly avoidingblurso layout shift does not swallow clicks on the next input.
4. State Machines & Data Lifecycle
Token Link Lifecycle:
stateDiagram-v2
[*] --> Written: POST form-writer.php -> data/{token}.json
Written --> Active: Valid, not revoked, not expired, used_at IS NULL
Written --> Revoked: Re-written with revoked=true (resend/correction)
Written --> Expired: now() > expires_at (72h member / preview TTL)
Active --> Submitted: Edge Function returns success=true (sets used_at in DB)
Active --> AlreadyUsed: RPC onboarding_token_status returns used_at != null OR 409
Active --> PreviewOnly: preview=true (no DB check, submit disabled)
Active --> BoardSaved: mode=admin_edit -> update-member-declaration
Revoked --> [*]
Expired --> [*]
Submitted --> [*]
AlreadyUsed --> [*]
BoardSaved --> [*]
5. Technical Contract (Inputs → Processing → Side Effects)
- Endpoints:
POST /dealflow/api/form-writer.php→ HeaderX-Api-Secret, Body{token, data}→ Writesdealflow/data/{token}.json(200/400/401/405/500).GET /dealflow/offer.php?token={64-hex}→ Server-side reads JSON, calls RPConboarding_token_status, renders HTML form.
- RPCs / Edge Functions / Storage Called:
POST {SUPABASE_URL}/rest/v1/rpc/onboarding_token_status(p_token) — server-side PHP cURL (5stimeout,SUPABASE_ANON_KEY).POST {SUPABASE_URL}/storage/v1/object/company-media/{company_id}/signatures/{session_id}_{field_id}_{timestamp}.png— client-sidefetch(SUPABASE_ANON_KEY,x-upsert: true).POST {SUPABASE_URL}/functions/v1/submit-member-declaration— client-sidefetch({token, values}).POST {SUPABASE_URL}/functions/v1/update-member-declaration— client-sidefetch({admin_edit_token, values, notify, submit_on_behalf, note}).POST {SUPABASE_URL}/functions/v1/submit-company-details— client-sidefetch({token, values}).
6. Cross-Repository Dependencies
| Caller | Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|---|
planovi-backend (_shared/form_link.ts via send-onboarding-invitation, send-correction-request-notice, create-form-preview) | planovi-microservices (dealflow) | HTTPS POST + X-Api-Secret (DEALFLOW_API_SECRET) | POST /dealflow/api/form-writer.php |
dealflow/offer.php (PHP server) | planovi-backend (Supabase RPC) | HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY) | POST /rest/v1/rpc/onboarding_token_status |
dealflow/offer.php (browser JS) | planovi-backend (Supabase Storage) | HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY) | POST /storage/v1/object/company-media/{company_id}/signatures/... |
dealflow/offer.php (browser JS) | planovi-backend (Supabase Edge Functions) | HTTPS POST + apikey/Bearer (SUPABASE_ANON_KEY) | POST /functions/v1/{submit-member-declaration|update-member-declaration|submit-company-details} |
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- RPC
onboarding_token_statusInstead of Direct Table Read (9467cfe4): Token JSON files on disk cannot know if a member already submitted the form; an RPC is used instead of opening direct anonSELECTon onboarding token tables. - Text Input with
inputmode="decimal"for Numbers (1cc09803): Native<input type="number">silently dropped non-numeric/comma input in browsers; switching totype="text" inputmode="decimal"allows Polish commas ("12,5") and surfaces explicit inline validation errors. - Quoted
.envFix (25fcdc97):offer.phpandform-writer.phpstrip surrounding"/'from.envvalues after quoted secrets caused 401 failures. - Step Hiding Without Tailwind CDN Dependency (
offer.php:555-556):.tok-step.hidden, #tok-final.hidden, .tok-nav .hidden { display: none !important; }is defined in inline CSS so multi-step visibility never breaks ifcdn.tailwindcss.comloads slowly or fails. - Signature Base64 Fallback (
00b9b20a): If direct browser upload tocompany-mediaStorage fails, the inlinedata:image/png;base64,...string is submitted directly to the Edge Function instead of blocking form submission. [TEAM_WHY_NEEDED: Does Supabase Storage bucket company-media allow unauthenticated anon uploads via SUPABASE_ANON_KEY with x-upsert: true for any {company_id}/signatures/* path? Is there an RLS policy scoping uploads to valid active onboarding sessions, or can an attacker overwrite signatures?][TEAM_WHY_NEEDED: In offer.php:141-150, if a token ever contained both mode='admin_edit' and deal_id, deal_id would overwrite submitFnUrl to submit-company-details while sending the admin_edit_token payload — confirm those two flags are mutually exclusive in planovi-backend.]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Log or Query | Fix |
|---|---|---|---|
form-writer.php returns HTTP 401 | X-Api-Secret header does not match DEALFLOW_API_SECRET in root .env (form-writer.php:33-41). Note header name is X-Api-Secret, NOT X-Secret-Key. | Check Edge Function logs in planovi-backend and verify .env DEALFLOW_API_SECRET. | Sync DEALFLOW_API_SECRET between VPS .env and Supabase Edge Function secrets. |
"Ta deklaracja została już wysłana. Dziękujemy!" unexpectedly | onboarding_token_status RPC returned non-null used_at (offer.php:169-171). | Run SELECT * FROM onboarding_token_status('<token>'); in Supabase SQL editor. | Issue a new resend/correction token from the panel. |
Signature canvas appears blank or distorted after clicking "Dalej" | Canvas was hidden (display:none) during initial initSignaturePads(), giving rect.width === 0; showStep() calls resizeVisibleCanvases() (offer.php:1252, 1515-1523). | Verify canvas width/height attributes in DOM inspector when step becomes active. | Only resizes if !canvas._hasStrokes; window resize after drawing is not re-scaled. |
"Nie zapisano." on submit with field errors | Edge Function returned HTTP 422 with errors: [{field_id, message}] (offer.php:1487-1497). | Inspect Network tab response JSON from submit-member-declaration / update-member-declaration. | Fix highlighted fields; form preserves all entered data. |