← Back to Pull requests

feat(sign): add in-person host signing ceremony and public template hub (Slice 4d) #4278

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 21, 2026 11:17 UTC
Author

Closes #3820

Release note (vi): Hỗ trợ ký trực tiếp tại quầy trên màn hình cách ly một lần có lưu vết nhân viên phụ trách và cổng biểu mẫu tự phục vụ công khai (/-/sign/p/<orgSlug>) không dùng CAPTCHA.

What

Implements Ludy eSign Slice 4d (docs/plan/esign.md, docs/research/esign-competitors-and-ai-2026.md), Step 2 of 2 following pending-route pre-registration in #4267:

1. In-person host signing ceremony (Ký trực tiếp tại quầy, 2a):
- Adds in_person_host_user_id on crove_sign.signing_token, host_user_id on crove_sign.signing_event, and 'in_person_session_started' + 'in_person_signed' event types across SQL CHECK constraints, @crove/db (schema.ts), @crove/kernel-contract, and @crove/mod-sign.
- Adds sign.signer.start_in_person (noIdempotency: true, SIGN_WRITERS access, enforcing confidential hr_contract visibility in both TypeScript and crove_sign.mint_in_person_signing_token), minting a single-use short-lived (<= 2h, default 30m) ceremony token (/-/sign?in_person=1#<token>), revoking prior unused tokens/OTPs for that signer, and appending in_person_session_started with hostUserId onto the hash-chained crove_sign.signing_event ledger.
- Updates crove_sign.public_token_resolve, public_record_view, public_submit, and runSignPdfSealJob so in_person_signed records host_user_id and commits hostUserId in both the canonical event hash chain and the sealed certificate.json Audit Certificate.
- Adds "Ký trực tiếp tại quầy" action and handoff dialog on /o/$slug/sign/envelopes/$id (opening an isolated noopener,noreferrer tab with empty back-history plus 1-click copy for an incognito/private window on shared counter devices), and locks /-/sign onto a terminal SignInPersonHandoffCard upon completion or decline with zero links back to / or /o/$slug/.

2. Self-service public template hub (/-/sign/p/$orgSlug + /api/sign/public-hub/:orgSlug, 2b):
- Adds listed_on_public_hub boolean NOT NULL DEFAULT false (CHECK (NOT (listed_on_public_hub AND (NOT enabled OR revoked_at IS NOT NULL)))) on crove_sign.template_direct_link, automatically cleared on link disable, archive, or template/role sync, with an opt-in checkbox ("Hiển thị trên cổng biểu mẫu công khai") and copyable hub URL on /o/$slug/sign/templates.
- Adds six narrow orgless SECURITY DEFINER procedures (crove_app only, each enforcing crove_kernel.org_app_on(v_tenant.org_id, 'sign')): public_hub_list, public_hub_resolve, public_hub_pdf_source, public_hub_request_otp, public_hub_verify_otp, and public_hub_start, resolving token_sha256 strictly inside PostgreSQL so zero plaintext or hashed direct-link capability tokens ever leave the database.
- Mounts GET and POST /api/sign/public-hub/:orgSlug in apps/kernel/src/http.ts (signEdgeGuard, ?token= rejection, Referrer-Policy: no-referrer, Cache-Control: no-store, X-Content-Type-Options: nosniff, per-IP + per-template + per-email rate limiters, bounded PDF read concurrency, zero CAPTCHA per #203), returning an identical opaque 404 across unknown/inactive/disabled/unentitled orgs and orgs with zero opted-in forms, and promotes /api/sign/public-hub/:orgSlug from PENDING/'pending' (#4267) to PUBLIC/'sql'.
- Adds mobile-first chrome-free /-/sign/p/$orgSlug (apps/app/src/routes/sign-public-hub.tsx) reusing SignDirectOtpCard, SignDirectReadyView, and handoffDirectSigningToken.

Tests

  • Scoped typechecks: @crove/db, @crove/kernel-contract, @crove/mod-sign, @crove/kernel-server, @crove/app

  • PostgreSQL 17 integration tests:

  • - apps/kernel/test/sign-in-person-public-hub.db.test.ts (3/3 passed)
    - apps/kernel/test/invariant/org-app-public-definers.db.test.ts (1/1 passed)
    - packages/db/test/check-unions.db.test.ts (3/3 passed)
    - apps/kernel/test/invariant/personal-data.db.test.ts (3/3 passed)
    - modules/sign/test/templates.db.test.ts (6/6 passed)
    - apps/kernel/test/invariant/sign-public-link-http.db.test.ts (3/3 passed)
  • Unit, SSR, and repo gates:

  • - apps/app/test/sign-in-person-public-hub.test.tsx, module-screens.test.ts, kernel-errors.test.ts, i18n.test.ts, sign-components.test.tsx, sign-templates.test.tsx, sign-direct.test.tsx (69/69 passed)
    - apps/kernel/test/invariant/route-coverage.test.ts, app-gate-routes.test.ts, command-writes.test.ts, tools/test/pii-scan.test.ts, apps/kernel/test/audit-facts.test.ts, apps/kernel/test/personal-data.test.ts (79/79 passed)
    - pnpm lint, pnpm knip, pnpm depcruise, migration-order.mjs, migration-lint.mjs, spdx-header.mjs, readme-assets.mjs, pnpm docs:check

    Acceptance

  • User-visible change: Workspace members (owner, admin, member) can start an isolated short-lived single-use in-person signing session (/-/sign?in_person=1#<token>) for any due signer/approver on an active envelope (locking onto a workspace-free handoff card on completion and sealing hostUserId into certificate.json), and can opt individual active 1-signer template direct links into a zero-CAPTCHA self-service public form hub at /-/sign/p/$orgSlug.

  • Evidence per acceptance item:

  • - In-person host signing (<= 2h single-use TTL, viewer 403, waiting sequential signer 409, confidential hr_contract visibility, in_person_session_started / in_person_signed hash chain, certificate.json hostUserId provenance, isolated post-sign lock card): verified in apps/kernel/test/sign-in-person-public-hub.db.test.ts and apps/app/test/sign-in-person-public-hub.test.tsx.
    - Self-service public template hub (listedOnPublicHub opt-in, opaque 404 parity with zero org-existence oracle, pre-envelope OTP gate, maxUses enforcement, instant unlisting while keeping private /-/sign/d#<token> links live, per-IP/email rate limiting without CAPTCHA): verified in apps/kernel/test/sign-in-person-public-hub.db.test.ts, apps/kernel/test/invariant/org-app-public-definers.db.test.ts, and apps/app/test/sign-in-person-public-hub.test.tsx.
  • Reviews: Fresh-context flagship reviewer (TypeName: "research") returned PASS with 0 blocking findings (1 non-blocking mobile button height polish applied in 281bc3c05); codex review --base HEAD~1 -c model_reasoning_effort=high was unavailable due to OpenAI Codex quota limit. Protected-path review (line:esign PO) and shared-core review (Platform PO on apps/kernel/src/http.ts, packages/db/src/schema.ts, apps/kernel/test/invariant/) requested on this PR.

  • Residual risk: Low. On a shared counter device, opening in the same browser profile still shares browser-level storage if a customer manually types another URL; the handoff dialog opens a noopener,noreferrer tab with empty back-history and provides 1-click copy with explicit guidance to use an incognito/private window on shared devices. Invariant suite (from base) turns green once Step 1 PR #4267 merges onto main and this branch rebases.

  • Six-item review checklist:

  • - correctness: Verified sequential turn promotion, canonical event hash chain backward compatibility (hostUserId included when non-null, omitted when null), signing_token_immutable trigger freeze on in_person_host_user_id, and listed_on_public_hub constraint + automatic reset across disable/rotate/archive/sync triggers.
    - security and authorization: Verified SIGN_WRITERS + human-actor checks and confidential hr_contract visibility in both TypeScript and mint_in_person_signing_token, SET search_path = pg_catalog, pg_temp and least-privilege REVOKE/GRANT on every SQL function, zero raw/hashed direct-link token exposure outside PostgreSQL, (orgSlug, templateId) lookup prior to payload validation for opaque 404 parity, ?token= rejection, no-referrer/no-store headers, and zero CAPTCHA (#203).
    - tenancy: Every query, lock, and index is scoped by org_id, manifest privacy classifications are updated, and crove_kernel.org_app_on(org_id, 'sign') + entitledTo(entitlements, 'sign') gate every command and orgless public_hub_* definer.
    - money: not applicable.
    - performance: Canonical lock order (envelope -> signer -> signing_token and template -> template_direct_link -> signing_otp), partial indexes signing_event_host_user_idx and template_direct_link_public_hub_idx, LIMIT 100 on public_hub_list, 4 KB body cap, per-IP/template/email RateLimiter budgets, and bounded signPdfReads concurrency.
    - accessibility: Paired <Label htmlFor> on all new inputs and checkboxes (assertPairedLabels), >= 44px (min-h-11 / max-sm:min-h-11) touch targets on public hub, ceremony, SignerPanel, and dialog buttons, and full Vietnamese diacritics (vi.ts) + English (en.ts) parity.

    ---

    <!-- dos-pr-summary -->

    📌 TL;DR


    This PR introduces a "Sign in Person" feature allowing hosts to initiate short-lived, isolated face-to-face signing sessions, and adds a public self-service form hub (/-/sign/p/$orgSlug) for organizations to list and manage public signing templates without requiring user accounts.

    🎯 Type of Change


  • 🚀 New feature

  • 🐛 Bugfix

  • 🧹 Refactor

  • ⚡ Performance

  • 📚 Documentation

  • ⚙️ CI / Configuration
  • 🔍 Changes Walkthrough


    | File | Summary of Changes |
    | :--- | :--- |
    | apps/app/src/components/sign/signer-panel.tsx | Added onStartInPerson prop and UI button to trigger in-person signing for eligible signers. |
    | apps/app/src/i18n/messages/en.ts | Added English translations for in-person signing dialogs, public hub labels, and audit badges. |
    | apps/app/src/i18n/messages/vi.ts | Added Vietnamese translations for in-person signing dialogs, public hub labels, and audit badges. |
    | apps/app/src/lib/sign-api.ts | Extended API types with inPerson flags; added startInPersonSigning method; implemented publicHubSignApi for public template hub interactions (list, view, pdf, otp, start). |
    | apps/app/src/lib/sign-hash.ts | Added SIGN_PUBLIC_HUB_PAGE_PREFIX, hasInPersonQueryFlag utility, and URL builders for in-person and public hub routes. |
    | apps/app/src/router.tsx | Registered the new signPublicHubRoute at /-/sign/p/$orgSlug with public access guards. |
    | apps/app/src/routes/sign-ceremony.tsx | Enhanced the signing ceremony to detect in-person mode via query params or API response; added SignInPersonHandoffCard for post-signing handoff instructions and updated security notices. |
    | apps/app/src/routes/sign-envelope-detail.tsx | Integrated the in-person signing workflow: added state management, mutation for starting sessions, a dialog for managing the session (open tab/copy link), and audit badge display for in-person events. |
    | apps/app/src/routes/sign-public-hub.tsx | New File: Implemented the public self-service hub UI, including template directory listing, OTP verification flow, PDF preview, and form submission logic for public signing. |

    📊 Architectural Flow


    sequenceDiagram
        participant Host as Host (Admin)
        participant Envelope as Envelope Detail Page
        participant API as Sign API
        participant Ceremony as Sign Ceremony Page
        participant Hub as Public Hub Page
    
        Note over Host, Ceremony: In-Person Signing Flow
        Host->>Envelope: Click "Sign in Person"
        Envelope->>API: startInPersonSigning(envelopeId, signerId)
        API-->>Envelope: Return token & expiry
        Envelope->>Host: Display Dialog (Open Tab / Copy Link)
        Host->>Ceremony: Open Isolated Tab (with ?in_person=1)
        Ceremony->>API: View/Submit (with inPerson flag)
        API-->>Ceremony: Confirm Completion
        Ceremony->>Host: Show Handoff Card (Lock Session)
    
        Note over Hub, API: Public Hub Flow
        Hub->>API: List Templates (orgSlug)
        API-->>Hub: Return Public Templates
        Hub->>Hub: User Selects Template
        Hub->>API: View/PDF/OTP (as needed)
        Hub->>API: Start Signing (name/email)
        API-->>Hub: Return Signing Token
        Hub->>Ceremony: Navigate to Direct Sign (Token)
    

    <!-- /dos-pr-summary -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: claude[bot] Review duration: 6m
    All Vouch review confidence checks passed
    Residual risk 0.38 = Change Risk (0.52) × (1 − Review Confidence (0.27)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 40% · Reviewer familiarity: 35%
    27%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #4278"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 27.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 27.2% · Lower = rushed or shallow review
    27.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 37.9% · Moderate risk
    37.9%
    Repository