Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Retire self-hosted trial signup control plane

rcourtman7cc980ad1d6e
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 9451c5f5fa..3c29b96c08 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -219,7 +219,7 @@ Environment variables take precedence over `system.json`.
| Variable | Description | Default |
| ---------- | ------------- | --------- |
| `PULSE_PUBLIC_URL` | URL for UI links, notifications, and OIDC. For reverse proxies, keep this as the public URL and use `PULSE_AGENT_CONNECT_URL` for agent installs if you need a direct/internal address. | Auto-detected |
-| `PULSE_PRO_TRIAL_SIGNUP_URL` | Support-only hosted trial signup URL used by explicit commercial handoff flows. Normal self-hosted v6 UI does not surface this path. Must be absolute `http(s)` URL. | `https://cloud.pulserelay.pro/start-pro-trial?...` |
+| `PULSE_PRO_TRIAL_SIGNUP_URL` | Legacy hosted commercial base URL retained for hosted entitlement refresh compatibility. The path is ignored for refresh and normal self-hosted v6 UI must not surface trial signup. Must be absolute `http(s)` URL. | `https://cloud.pulserelay.pro` |
| `PULSE_AGENT_CONNECT_URL` | Dedicated direct URL for agents (overrides `PULSE_PUBLIC_URL` for agent install commands). Alias: `PULSE_AGENT_URL`. | *(unset)* |
| `PULSE_AGENT_CONFIG_SIGNING_KEY` | Base64 Ed25519 private key used to sign remote agent config payloads. | *(unset)* |
| `PULSE_AGENT_CONFIG_PUBLIC_KEYS` | Comma-separated base64 Ed25519 public keys (raw 32-byte or PKIX-encoded) trusted by agents. | *(unset)* |
diff --git a/docs/operations/TRIAL_E2E_LXC_SNAPSHOT_RUNBOOK.md b/docs/operations/TRIAL_E2E_LXC_SNAPSHOT_RUNBOOK.md
index 2f4a16aa68..6313b764a8 100644
--- a/docs/operations/TRIAL_E2E_LXC_SNAPSHOT_RUNBOOK.md
+++ b/docs/operations/TRIAL_E2E_LXC_SNAPSHOT_RUNBOOK.md
@@ -1,17 +1,16 @@
-# Trial + Cloud E2E on Proxmox LXC (Snapshot-Clean)
+# Trial-Retirement + Cloud E2E on Proxmox LXC (Snapshot-Clean)
-This runbook defines a clean, repeatable end-to-end trial validation loop for a Pulse binary running in Proxmox LXC.
+This runbook defines a clean, repeatable validation loop for retired self-hosted trial acquisition and Pulse Cloud signup behavior on a Pulse binary running in Proxmox LXC.
Goal: every eval run starts from the exact same filesystem and runtime state, so previous runs cannot pollute new results.
## Scope
-- Validates hosted trial initiation from a self-hosted Pulse instance
-- Validates initiation does not mint local entitlements before activation
-- Validates initiation rate limiting and idempotent redirect behavior
+- Validates ordinary self-hosted v6 does not expose in-app trial acquisition
+- Validates probing retired trial acquisition routes does not mutate local entitlements
+- Validates default self-hosted UI does not show trial CTAs or paid-only navigation
- Validates real Stripe sandbox checkout completion for Pulse Cloud signup
- Validates cloud post-checkout lifecycle transition to canceled state
-- Validates post-checkout trial activation state in Pulse (`/settings?trial=activated`)
## Prerequisites
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index a4ef5e1ad3..87c9036fd1 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -4782,21 +4782,7 @@
],
"coverage_gaps": [],
"candidate_lanes": [],
- "work_claims": [
- {
- "id": "codex-lane-l6",
- "agent_id": "codex",
- "summary": "Remove remaining hosted-AI quickstart provider/runtime plumbing so v6 self-hosted AI is BYOK/local-only and quickstart survives only as inert historical compatibility.",
- "target_id": "v6-product-lane-expansion",
- "claimed_at": "2026-04-28T14:53:29Z",
- "heartbeat_at": "2026-04-28T14:53:29Z",
- "expires_at": "2026-04-28T16:53:29Z",
- "work_item": {
- "kind": "lane",
- "id": "L6"
- }
- }
- ],
+ "work_claims": [],
"open_decisions": [],
"source_of_truth_file": "docs/release-control/v6/internal/SOURCE_OF_TRUTH.md",
"resolved_decisions": [
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 320a131eab..8cb42ec4ee 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -978,8 +978,8 @@ commercial checkout-session result before redeeming the activation key, so
browser form/query state and Stripe metadata alone never become the source of
truth for a completed self-hosted upgrade. That same owned callback path must
resolve only to HTTPS instance origins or a direct loopback HTTP origin, and
-the hosted trial/entitlement follow-up fetches behind that path must stay on
-the restricted outbound client instead of raw commercial HTTP calls. Once that
+the hosted entitlement follow-up fetches behind that path must stay on the
+restricted outbound client instead of raw commercial HTTP calls. Once that
commercial binding
verifies, Pulse's owned callback must persist a dedicated local
purchase-return redemption record keyed by `portal_handoff_id` plus
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 477fdb3526..1e2a62cd9a 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -102,7 +102,7 @@ cloud-specific enforcement rules.
79. `pulse-pro:license-server/self_hosted_feature_catalog.generated.go`
80. `internal/cloudcp/server.go`, `internal/cloudcp/authz.go`, `internal/cloudcp/commercial_identity.go`, `internal/cloudcp/security.go`
81. `internal/cloudcp/health_monitor.go`, `internal/cloudcp/health_stuck_provisioning.go`, `internal/cloudcp/tenant_state_metrics.go`, `internal/cloudcp/ratelimit.go`
-82. `internal/cloudcp/trial_signup_handlers.go`, `internal/cloudcp/trial_signup_store.go`, `internal/cloudcp/hosted_entitlement_handlers.go`
+82. `internal/cloudcp/hosted_entitlement_handlers.go`, `internal/cloudcp/url_helpers.go`
83. `internal/cloudcp/admin/handlers.go`, `internal/cloudcp/admin/status.go`, `internal/cloudcp/auditlog/auditlog.go`
84. `internal/cloudcp/cpmetrics/metrics.go`, `internal/cloudcp/cpsec/nonce.go`, `internal/cloudcp/static_assets.go`, `internal/cloudcp/favicon.svg`
85. `internal/cloudcp/email/sender.go`, `internal/cloudcp/email/templates.go`
@@ -818,30 +818,32 @@ and `frontend-modern/src/utils/upgradePresentation.ts`. Commercial tier labels,
feature minimum-tier messaging, migration/trial notices, billing-admin status
labels, and upgrade CTA styling must extend those helpers instead of being
forked into per-surface status-code branches that drift from backend error
-truth. Trial initiation surfaces must preserve backend denial messages when the
-request is blocked for migration, active commercial state, or other operational
-reasons, and only map the explicit canonical cases (`trial_already_used`,
-rate-limit retry) to fixed copy.
+truth. The old self-hosted trial-start acquisition path is not a current v6
+commercial surface; denial and retry copy for ordinary self-hosted runtimes
+must be limited to owned purchase, recovery, portal, Cloud signup, or support
+handoff paths.
That same helper boundary also owns generic settings-paywall CTA labels. Under
the v6 free-first self-hosted policy, non-billing feature gates must stay
factual and route deliberate commercial intent to Plans with neutral "View
plans" copy; they must not start a Pro trial directly or embed local
`Upgrade to Pro` / `Start free trial` strings. Direct trial-start actions stay
-owned by explicit billing, hosted, activation, recovery, and support handoff
-surfaces where the operator has already chosen the commercial path.
+retired for ordinary self-hosted v6; explicit commercial intent routes through
+plan comparison, purchase activation, recovery, Cloud, or support handoff
+surfaces where the operator has already chosen that path.
The same shared self-hosted commercial presentation boundary also owns the
recovery-surface copy for `SelfHostedCommercialRecoverySection.tsx`,
including the existing-key field label/help text and legacy-key exchange
notice, while `selfHostedBillingPresentation.ts` owns the first-class plan and
-trial copy that belongs on the primary billing surface. That split prevents
-manual key redemption from drifting back into the main purchase or trial path.
+license-state copy that belongs on the primary billing surface. That split
+prevents manual key redemption from drifting back into the main purchase path.
That same recovery boundary also owns the linked legal surface:
`SelfHostedCommercialRecoverySection.tsx` must route its Terms-of-Service link
through the shipped `TERMS.md` docs asset instead of sending operators to
GitHub `main`, so the recovery trust surface stays version-matched and
available on restricted installs.
-Hosted self-serve trial leases are also part of that same contract. A redeemed
-hosted trial must carry the canonical Pro capability set and the authoritative
+Already-issued legacy hosted trial leases are also part of that same
+compatibility contract. If such a lease is refreshed, it must carry the
+canonical Pro capability set and the authoritative
`limits.max_monitored_systems` cap inside the signed lease rather than relying
on downstream runtime fallback to infer a limit from trial state alone.
The top-level authenticated shell is part of that same customer-facing
@@ -989,6 +991,10 @@ The retired `/auth/trial-activate` return path must also stay out of the
ordinary self-hosted router and Pro settings UI. Hosted/cloud entitlement lease
refresh may still validate signed leases for already-approved hosted state, but
ordinary self-hosted Pulse must not create a local trial acquisition callback.
+The matching control-plane acquisition routes are retired too:
+`/start-pro-trial`, `/trial-signup/*`, and `/api/trial-signup/*` must remain
+unregistered. `/api/entitlements/refresh` remains the only hosted entitlement
+refresh endpoint for already-issued hosted leases.
Browser and shell coverage now guard that retired boundary:
`tests/integration/tests/07-trial-signup-return.spec.ts` and
`tests/integration/scripts/trial-signup-contract.sh` must expect `404` from the
@@ -1006,46 +1012,15 @@ when older workspaces need membership continuity repaired at open time. Cloud,
MSP, and commercial account roles therefore have one canonical translation into
tenant org permissions instead of drifting between provisioning-time seeds and
handoff-time access repair.
-For the hosted self-serve flow, that also means the public trial pages and form
-posts must render the owned Pulse trial experience with preserved instance/form
-state when rate limited, rather than dropping users onto a generic control-plane
-`Too Many Requests` response.
-The same owned hosted-trial failure experience applies to invalid or expired
-verification links. The customer must stay inside the Pulse-owned retry path
-with the originating-instance context preserved, rather than landing on a
-generic hosted error page that reads like a detached SaaS funnel.
-The hosted trial handoff page is part of that same boundary as well. It may
-still use a secure hosted Stripe-backed session internally, but the customer
-copy must present the flow as starting a trial for the originating Pulse
-instance, not as a generic purchase funnel. Recovery-contact fields such as
-work email and optional company name must remain clearly secondary to the
-instance-bound entitlement handoff. Hosted form-stage issuance conflicts must
-also preserve the canonical reason shape: duplicate recovery-email usage must
-not be flattened into an organization-level message, and terminal conflicts
-must render as owned hosted outcome UX rather than editable inline form state.
-Expired or invalid hosted backup-link states must follow that same rule rather
-than falling back to a form with missing Pulse initiation context.
-Hosted service/configuration failures during verification, hosted checkout
-preparation, or checkout-session creation must also render as owned
-"temporarily unavailable" outcome UX rather than inline form errors.
The old self-hosted trial activation return notice on `/settings/system-pro` is
retired with that callback: the `trial` query result must not produce owned
activation UI, a success banner, or retry copy in v6 GA. Purchase activation
continues through the Pulse Account return contract instead.
-That same hosted owner also applies after Stripe returns to
-`/trial-signup/complete`: customer-facing completion failures must stay inside
-owned trial UX rather than dropping raw control-plane error strings, and they
-may only offer a direct "Start Trial Again" restart path when the original
-Pulse return target and initiation binding are still known. Terminal conflicts
-such as "trial already used" must not present restart as the recommended next
-step.
-That same rule applies to the self-hosted Pro settings panel. Trial start
-errors in `frontend-modern/src/components/Settings/useProLicensePanelState.ts`
-must route through the shared cloud-paid presentation helper so backend denial
-reasons, explicit already-used conflicts, and retry-later states stay aligned
-with the rest of the commercial surfaces.
-redefined inline in settings feature gates, Pro license panels, or trial
-upgrade nudges.
+That same retirement applies to the old hosted control-plane completion and
+redeem routes: `/trial-signup/complete` and `/api/trial-signup/redeem` must
+not return customer-facing trial UX or raw acquisition errors in v6 GA.
+Commercial plan disclosure copy must not be redefined inline in settings
+feature gates, Pro license panels, or upgrade nudges.
That same disclosure copy must stay professional and customer-facing. The
settings ledger may expose counting details and included collection paths, but
it must avoid informal debug-style labels or ad hoc wording that makes the
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index f6e8abf5ff..1212a5501a 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -92,7 +92,12 @@ visibility, and privacy controls to operators.
5. Change security/privacy settings presentation through the shared `frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx`, `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx`, `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx`, `frontend-modern/src/components/Settings/QuickSecuritySetup.tsx`, `frontend-modern/src/components/Settings/SecurityPostureSummary.tsx`, `frontend-modern/src/components/Settings/SSOProviderTypeIcon.tsx`, `frontend-modern/src/utils/securityAuthPresentation.ts`, `frontend-modern/src/utils/securityScorePresentation.ts`, `frontend-modern/src/utils/auditLogPresentation.ts`, and `frontend-modern/src/utils/auditWebhookPresentation.ts` boundary.
6. Change operator-facing telemetry/adoption reporting through `scripts/telemetry_adoption_report.py` together with the privacy disclosure whenever release-identity interpretation changes.
7. Change data-at-rest encryption-key or control-plane magic-link HMAC key and storage-root hardening semantics through `internal/crypto/crypto.go`, `internal/cloudcp/auth/magiclink.go`, `internal/cloudcp/auth/magiclink_store.go`, and `internal/securityutil/secure_storage_dir.go` together so writable-but-not-owned runtime storage mounts stay supported without weakening file-level secrecy.
-8. Change auth-env password normalization or shared TLS fingerprint verification defaults through `internal/config/config.go`, `internal/config/watcher.go`, and `pkg/tlsutil/fingerprint.go` together so startup auth ingestion, live auth-env reloads, and pinned-fingerprint TLS clients keep one fail-closed security floor.
+8. Change auth-env password normalization, hosted commercial base URL
+ normalization, or shared TLS fingerprint verification defaults through
+ `internal/config/config.go`, `internal/config/watcher.go`, and
+ `pkg/tlsutil/fingerprint.go` together so startup auth ingestion, live
+ auth-env reloads, hosted entitlement refresh origins, and
+ pinned-fingerprint TLS clients keep one fail-closed security floor.
9. Change operator-facing data-handling posture through `frontend-modern/src/components/Settings/DataHandlingPanel.tsx` and `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts` together so resource classification, handling-boundary, and redaction copy stays governed as a trust surface.
## Forbidden Paths
@@ -109,7 +114,11 @@ visibility, and privacy controls to operators.
4. Keep the checked-in telemetry adoption report aligned with the same release-identity rules used by the runtime telemetry payload.
5. Update this contract whenever a new canonical security, token, auth, or privacy surface becomes part of the governed trust boundary.
6. Keep the shared storage-directory and secure storage-file hardening helper aligned with the crypto manager plus control-plane magic-link key and store handling whenever runtime data-root ownership assumptions change.
-7. Keep auth-env ingestion and shared fingerprint-verifier TLS defaults aligned whenever runtime auth loading or pinned-certificate transport behavior changes.
+7. Keep auth-env ingestion, hosted commercial base URL validation, and shared
+ fingerprint-verifier TLS defaults aligned whenever runtime auth loading,
+ hosted entitlement refresh origin handling, or pinned-certificate transport
+ behavior changes. Hosted commercial URL overrides must remain absolute
+ HTTP(S) URLs, with plain HTTP limited to loopback development origins.
8. Keep the Data Handling settings surface neutral and non-commercial: it may show resource policy posture, local-only counts, and redaction coverage, but it must not advertise trials, upgrades, paid plans, or monitoring limits.
9. Keep operator-facing Data Handling posture aligned with runtime AI/context enforcement: `local-only` resource details must not be sent to external model prompts, and sensitive free-form alert, tool-result, investigation, and any retained legacy managed-model compatibility text must use the shared resource-policy redaction helper before leaving the local trust boundary. All provider-bound AI requests to non-local models must use the shared resource-policy sanitizer immediately before transport so later agentic turns cannot bypass the advertised handling posture.
10. Keep the canonical and frontend-served privacy disclosures aligned with
diff --git a/frontend-modern/public/docs/CONFIGURATION.md b/frontend-modern/public/docs/CONFIGURATION.md
index 9451c5f5fa..3c29b96c08 100644
--- a/frontend-modern/public/docs/CONFIGURATION.md
+++ b/frontend-modern/public/docs/CONFIGURATION.md
@@ -219,7 +219,7 @@ Environment variables take precedence over `system.json`.
| Variable | Description | Default |
| ---------- | ------------- | --------- |
| `PULSE_PUBLIC_URL` | URL for UI links, notifications, and OIDC. For reverse proxies, keep this as the public URL and use `PULSE_AGENT_CONNECT_URL` for agent installs if you need a direct/internal address. | Auto-detected |
-| `PULSE_PRO_TRIAL_SIGNUP_URL` | Support-only hosted trial signup URL used by explicit commercial handoff flows. Normal self-hosted v6 UI does not surface this path. Must be absolute `http(s)` URL. | `https://cloud.pulserelay.pro/start-pro-trial?...` |
+| `PULSE_PRO_TRIAL_SIGNUP_URL` | Legacy hosted commercial base URL retained for hosted entitlement refresh compatibility. The path is ignored for refresh and normal self-hosted v6 UI must not surface trial signup. Must be absolute `http(s)` URL. | `https://cloud.pulserelay.pro` |
| `PULSE_AGENT_CONNECT_URL` | Dedicated direct URL for agents (overrides `PULSE_PUBLIC_URL` for agent install commands). Alias: `PULSE_AGENT_URL`. | *(unset)* |
| `PULSE_AGENT_CONFIG_SIGNING_KEY` | Base64 Ed25519 private key used to sign remote agent config payloads. | *(unset)* |
| `PULSE_AGENT_CONFIG_PUBLIC_KEYS` | Comma-separated base64 Ed25519 public keys (raw 32-byte or PKIX-encoded) trusted by agents. | *(unset)* |
diff --git a/internal/cloudcp/email/templates.go b/internal/cloudcp/email/templates.go
index 8d1a60c06a..3420b7dae3 100644
--- a/internal/cloudcp/email/templates.go
+++ b/internal/cloudcp/email/templates.go
@@ -51,52 +51,3 @@ func RenderMagicLinkEmail(data MagicLinkData) (html, text string, err error) {
return buf.String(), textBody, nil
}
-
-var trialVerificationTemplate = template.Must(template.New("trial_verification").Parse(`<!DOCTYPE html>
-<html>
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Verify your Pulse Pro trial request</title>
-</head>
-<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background-color: #f5f7f2;">
-<table role="presentation" style="width: 100%; border: 0; cellpadding: 0; cellspacing: 0;">
-<tr><td style="padding: 40px 0; text-align: center;">
-<table role="presentation" style="max-width: 520px; margin: 0 auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 10px 30px rgba(20,38,31,0.08);">
-<tr><td style="padding: 34px 40px; text-align: center;">
-<h1 style="margin: 0 0 16px; font-size: 24px; color: #14261f;">Verify your Pulse Pro trial request</h1>
-<p style="margin: 0 0 24px; color: #4d5f57; font-size: 15px; line-height: 1.6;">
-Confirm this email address to continue setting up your 14-day Pulse Pro trial. This link expires in 20 minutes.
-</p>
-<a href="{{.VerifyURL}}" style="display: inline-block; padding: 12px 30px; background: #0f766e; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 15px; font-weight: 600;">
-Verify Email
-</a>
-<p style="margin: 24px 0 0; color: #7a8a83; font-size: 13px; line-height: 1.5;">
-If you did not request a Pulse Pro trial, you can safely ignore this email.
-</p>
-</td></tr>
-</table>
-</td></tr>
-</table>
-</body>
-</html>`))
-
-// TrialVerificationData holds template data for the trial verification email.
-type TrialVerificationData struct {
- VerifyURL string
-}
-
-// RenderTrialVerificationEmail renders the trial verification HTML email.
-func RenderTrialVerificationEmail(data TrialVerificationData) (html, text string, err error) {
- var buf bytes.Buffer
- if err := trialVerificationTemplate.Execute(&buf, data); err != nil {
- return "", "", fmt.Errorf("render trial verification template: %w", err)
- }
-
- textBody := fmt.Sprintf(
- "Verify your Pulse Pro trial request\n\nConfirm your email to continue setting up your 14-day Pulse Pro trial: %s\n\nThis link expires in 20 minutes. If you didn't request this, ignore this email.",
- data.VerifyURL,
- )
-
- return buf.String(), textBody, nil
-}
diff --git a/internal/cloudcp/entitlements/service.go b/internal/cloudcp/entitlements/service.go
index ca2a0386f1..aba3f32451 100644
--- a/internal/cloudcp/entitlements/service.go
+++ b/internal/cloudcp/entitlements/service.go
@@ -35,36 +35,6 @@ type RefreshResult struct {
EntitlementJWT string
}
-type TrialEntitlementInput struct {
- RequestID string
- OrgID string
- Email string
- ReturnURL string
- InstanceToken string
- InstanceHost string
- TrialStartedAt time.Time
- IssuedAt time.Time
- RedeemedAt time.Time
-}
-
-type TrialRedemptionResult struct {
- EntitlementJWT string
- EntitlementRefreshToken string
-}
-
-type TrialActivationInput struct {
- RequestID string
- OrgID string
- Email string
- ReturnURL string
- InstanceToken string
- InstanceHost string
- CheckoutSessionID string
- TrialStartedAt time.Time
- IssuedAt time.Time
- TTL time.Duration
-}
-
func NewService(reg *registry.TenantRegistry, baseURL, trialActivationPrivateKey string) *Service {
return &Service{
registry: reg,
@@ -127,139 +97,6 @@ func (s *Service) IssueTenantBillingState(tenant *registry.Tenant, requestedSubS
}, nil
}
-func (s *Service) RedeemTrialEntitlement(input TrialEntitlementInput) (*TrialRedemptionResult, error) {
- if s == nil || s.registry == nil {
- return nil, fmt.Errorf("hosted entitlement service is unavailable")
- }
- requestID := strings.TrimSpace(input.RequestID)
- orgID := strings.TrimSpace(input.OrgID)
- email := strings.TrimSpace(input.Email)
- returnURL := strings.TrimSpace(input.ReturnURL)
- instanceToken := strings.TrimSpace(input.InstanceToken)
- instanceHost := strings.ToLower(strings.TrimSpace(input.InstanceHost))
- if requestID == "" || orgID == "" || email == "" || returnURL == "" || instanceHost == "" {
- return nil, fmt.Errorf("trial entitlement input is incomplete")
- }
-
- issuedAt := input.IssuedAt.UTC()
- if issuedAt.IsZero() {
- issuedAt = s.now().UTC()
- }
- redeemedAt := input.RedeemedAt.UTC()
- if redeemedAt.IsZero() {
- redeemedAt = issuedAt
- }
- trialStartedAt := input.TrialStartedAt.UTC()
- if trialStartedAt.IsZero() {
- trialStartedAt = issuedAt
- }
-
- rawToken, err := randomRefreshToken()
- if err != nil {
- return nil, err
- }
- refreshToken, _, err := s.registry.StoreOrIssueTrialHostedEntitlement(registry.TrialHostedEntitlementInput{
- RequestID: requestID,
- OrgID: orgID,
- Email: email,
- ReturnURL: returnURL,
- InstanceToken: instanceToken,
- InstanceHost: instanceHost,
- TrialStartedAt: trialStartedAt,
- IssuedAt: issuedAt,
- RedeemedAt: redeemedAt,
- RefreshToken: rawToken,
- })
- if err != nil {
- return nil, err
- }
-
- entitlementJWT, err := s.signTrialLease(trialEntitlementContext{
- requestID: requestID,
- orgID: orgID,
- email: email,
- instanceHost: instanceHost,
- trialStartedAt: trialStartedAt,
- }, issuedAt)
- if err != nil {
- return nil, err
- }
- return &TrialRedemptionResult{
- EntitlementJWT: entitlementJWT,
- EntitlementRefreshToken: refreshToken,
- }, nil
-}
-
-func (s *Service) IssueTrialActivation(input TrialActivationInput) (string, error) {
- if s == nil || s.registry == nil {
- return "", fmt.Errorf("hosted entitlement service is unavailable")
- }
- requestID := strings.TrimSpace(input.RequestID)
- orgID := strings.TrimSpace(input.OrgID)
- email := strings.TrimSpace(input.Email)
- returnURL := strings.TrimSpace(input.ReturnURL)
- instanceToken := strings.TrimSpace(input.InstanceToken)
- instanceHost := strings.ToLower(strings.TrimSpace(input.InstanceHost))
- checkoutSessionID := strings.TrimSpace(input.CheckoutSessionID)
- if requestID == "" || orgID == "" || email == "" || returnURL == "" || instanceToken == "" || instanceHost == "" || checkoutSessionID == "" {
- return "", fmt.Errorf("trial activation input is incomplete")
- }
-
- issuedAt := input.IssuedAt.UTC()
- if issuedAt.IsZero() {
- issuedAt = s.now().UTC()
- }
- trialStartedAt := input.TrialStartedAt.UTC()
- if trialStartedAt.IsZero() {
- trialStartedAt = issuedAt
- }
- ttl := input.TTL
- if ttl <= 0 {
- return "", fmt.Errorf("trial activation ttl is required")
- }
-
- privateKey, err := s.entitlementPrivateKey()
- if err != nil {
- return "", err
- }
- activationToken, err := pkglicensing.SignTrialActivationToken(privateKey, pkglicensing.TrialActivationClaims{
- OrgID: orgID,
- Email: email,
- InstanceHost: instanceHost,
- InstanceToken: instanceToken,
- ReturnURL: returnURL,
- RegisteredClaims: jwt.RegisteredClaims{
- IssuedAt: jwt.NewNumericDate(issuedAt),
- ExpiresAt: jwt.NewNumericDate(issuedAt.Add(ttl)),
- Subject: checkoutSessionID,
- },
- })
- if err != nil {
- return "", fmt.Errorf("sign trial activation token: %w", err)
- }
-
- refreshToken, err := randomRefreshToken()
- if err != nil {
- return "", err
- }
- storedToken, _, err := s.registry.StoreOrRotateTrialActivation(registry.TrialHostedActivationInput{
- RequestID: requestID,
- OrgID: orgID,
- Email: email,
- ReturnURL: returnURL,
- InstanceToken: instanceToken,
- InstanceHost: instanceHost,
- TrialStartedAt: trialStartedAt,
- IssuedAt: issuedAt,
- ActivationToken: activationToken,
- RefreshToken: refreshToken,
- }, ttl)
- if err != nil {
- return "", err
- }
- return storedToken, nil
-}
-
func (s *Service) RefreshEntitlement(refreshToken, instanceHost string) (*RefreshResult, error) {
if s == nil || s.registry == nil {
return nil, fmt.Errorf("hosted entitlement service is unavailable")
@@ -294,41 +131,6 @@ func (s *Service) RefreshEntitlement(refreshToken, instanceHost string) (*Refres
}
}
-func (s *Service) ResolveTrialActivation(token, instanceHost string) (*registry.HostedEntitlement, error) {
- if s == nil || s.registry == nil {
- return nil, fmt.Errorf("hosted entitlement service is unavailable")
- }
- token = strings.TrimSpace(token)
- instanceHost = strings.ToLower(strings.TrimSpace(instanceHost))
- if token == "" {
- return nil, ErrHostedEntitlementNotFound
- }
- if instanceHost == "" {
- return nil, ErrHostedEntitlementTargetMismatch
- }
-
- entitlement, err := s.registry.GetHostedEntitlementByActivationToken(token)
- if err != nil {
- return nil, err
- }
- if entitlement == nil || entitlement.Kind != registry.HostedEntitlementKindTrial {
- return nil, ErrHostedEntitlementNotFound
- }
- if strings.TrimSpace(entitlement.TrialRequestID) == "" {
- return nil, ErrHostedEntitlementInvalid
- }
- if strings.ToLower(strings.TrimSpace(entitlement.InstanceHost)) != instanceHost {
- return nil, ErrHostedEntitlementTargetMismatch
- }
- if strings.TrimSpace(entitlement.ReturnURL) == "" || strings.TrimSpace(entitlement.InstanceToken) == "" {
- return nil, ErrHostedEntitlementInvalid
- }
- if entitlement.ActivationIssuedAt == nil {
- return nil, ErrHostedEntitlementInactive
- }
- return entitlement, nil
-}
-
func (s *Service) RevokeTenantEntitlement(tenantID string, revokedAt time.Time) error {
if s == nil || s.registry == nil {
return fmt.Errorf("hosted entitlement service is unavailable")
diff --git a/internal/cloudcp/entitlements/service_test.go b/internal/cloudcp/entitlements/service_test.go
index 9c9ef6d328..7a38405a8d 100644
--- a/internal/cloudcp/entitlements/service_test.go
+++ b/internal/cloudcp/entitlements/service_test.go
@@ -2,7 +2,9 @@ package entitlements
import (
"crypto/ed25519"
+ "database/sql"
"encoding/base64"
+ "path/filepath"
"testing"
"time"
@@ -15,20 +17,26 @@ func newTestService(t *testing.T) (*Service, ed25519.PublicKey, *registry.Tenant
}
func newTestServiceWithBaseURL(t *testing.T, baseURL string) (*Service, ed25519.PublicKey, *registry.TenantRegistry) {
+ svc, pub, reg, _ := newTestServiceWithBaseURLAndDir(t, baseURL)
+ return svc, pub, reg
+}
+
+func newTestServiceWithBaseURLAndDir(t *testing.T, baseURL string) (*Service, ed25519.PublicKey, *registry.TenantRegistry, string) {
t.Helper()
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("GenerateKey: %v", err)
}
- reg, err := registry.NewTenantRegistry(t.TempDir())
+ dir := t.TempDir()
+ reg, err := registry.NewTenantRegistry(dir)
if err != nil {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
svc := NewService(reg, baseURL, base64.StdEncoding.EncodeToString(priv))
- return svc, pub, reg
+ return svc, pub, reg, dir
}
func TestIssueTenantBillingStateReturnsLeaseOnlyState(t *testing.T) {
@@ -241,31 +249,15 @@ func TestRefreshPaidEntitlementCanonicalizesBaseURLForExpectedHost(t *testing.T)
}
}
-func TestRedeemTrialEntitlementAndRefresh(t *testing.T) {
- svc, pub, reg := newTestServiceWithBaseURL(t, "https://cloud.example.com")
+func TestRefreshLegacyTrialEntitlementReturnsLease(t *testing.T) {
+ svc, pub, reg, dir := newTestServiceWithBaseURLAndDir(t, "https://cloud.example.com")
now := time.Unix(1710000000, 0).UTC()
svc.SetNow(func() time.Time { return now })
- redemption, err := svc.RedeemTrialEntitlement(TrialEntitlementInput{
- RequestID: "trial_request_1",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now,
- RedeemedAt: now,
- })
- if err != nil {
- t.Fatalf("RedeemTrialEntitlement: %v", err)
- }
- if redemption.EntitlementJWT == "" || redemption.EntitlementRefreshToken == "" {
- t.Fatalf("expected lease and refresh token, got %#v", redemption)
- }
+ seedLegacyTrialHostedEntitlement(t, dir, now, "etr_legacy_trial")
- loaded, err := reg.GetHostedEntitlementByRefreshToken(redemption.EntitlementRefreshToken)
+ loaded, err := reg.GetHostedEntitlementByRefreshToken("etr_legacy_trial")
if err != nil {
t.Fatalf("GetHostedEntitlementByRefreshToken: %v", err)
}
@@ -273,7 +265,7 @@ func TestRedeemTrialEntitlementAndRefresh(t *testing.T) {
t.Fatalf("expected trial entitlement record, got %#v", loaded)
}
- refreshResult, err := svc.RefreshEntitlement(redemption.EntitlementRefreshToken, "pulse.example.com")
+ refreshResult, err := svc.RefreshEntitlement("etr_legacy_trial", "pulse.example.com")
if err != nil {
t.Fatalf("RefreshEntitlement: %v", err)
}
@@ -293,3 +285,35 @@ func TestRedeemTrialEntitlementAndRefresh(t *testing.T) {
)
}
}
+
+func seedLegacyTrialHostedEntitlement(t *testing.T, registryDir string, now time.Time, refreshToken string) {
+ t.Helper()
+
+ db, err := sql.Open("sqlite", filepath.Join(registryDir, "tenants.db"))
+ if err != nil {
+ t.Fatalf("open registry db: %v", err)
+ }
+ defer db.Close()
+
+ _, err = db.Exec(`
+ INSERT INTO hosted_entitlements (
+ id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
+ trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
+ ) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, NULL, NULL, ?, NULL)`,
+ "trial:trial_request_1",
+ string(registry.HostedEntitlementKindTrial),
+ "trial_request_1",
+ "default",
+ "https://pulse.example.com/auth/trial-activate",
+ "tsi_test",
+ "pulse.example.com",
+ now.Unix(),
+ refreshToken,
+ now.Unix(),
+ now.Unix(),
+ )
+ if err != nil {
+ t.Fatalf("seed legacy trial hosted entitlement: %v", err)
+ }
+}
diff --git a/internal/cloudcp/hosted_entitlement_handlers.go b/internal/cloudcp/hosted_entitlement_handlers.go
index 8f075d9a9d..58c153cd1e 100644
--- a/internal/cloudcp/hosted_entitlement_handlers.go
+++ b/internal/cloudcp/hosted_entitlement_handlers.go
@@ -20,6 +20,8 @@ type hostedEntitlementRefreshResponse struct {
EntitlementJWT string `json:"entitlement_jwt"`
}
+const hostedEntitlementDefaultOrgID = "default"
+
type HostedEntitlementHandlers struct {
entitlements *entitlements.Service
}
@@ -43,14 +45,14 @@ func (h *HostedEntitlementHandlers) HandleRefresh(w http.ResponseWriter, r *http
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
- orgID := normalizeTrialOrgID(reqBody.OrgID)
+ orgID := normalizeHostedEntitlementOrgID(reqBody.OrgID)
instanceHost := strings.ToLower(strings.TrimSpace(reqBody.InstanceHost))
refreshToken := strings.TrimSpace(reqBody.EntitlementRefreshToken)
if instanceHost == "" || refreshToken == "" {
http.Error(w, "instance_host and entitlement_refresh_token are required", http.StatusBadRequest)
return
}
- if orgID != trialSignupDefaultOrgID {
+ if orgID != hostedEntitlementDefaultOrgID {
http.Error(w, "invalid entitlement refresh token", http.StatusUnauthorized)
return
}
@@ -77,3 +79,11 @@ func (h *HostedEntitlementHandlers) HandleRefresh(w http.ResponseWriter, r *http
log.Error().Err(err).Str("org_id", orgID).Msg("failed to encode hosted entitlement refresh response")
}
}
+
+func normalizeHostedEntitlementOrgID(raw string) string {
+ orgID := strings.TrimSpace(raw)
+ if orgID == "" {
+ return hostedEntitlementDefaultOrgID
+ }
+ return orgID
+}
diff --git a/internal/cloudcp/public_cloud_signup_handlers.go b/internal/cloudcp/public_cloud_signup_handlers.go
index ce4a6fd8ed..6260ea85c3 100644
--- a/internal/cloudcp/public_cloud_signup_handlers.go
+++ b/internal/cloudcp/public_cloud_signup_handlers.go
@@ -21,7 +21,10 @@ import (
stripesession "github.com/stripe/stripe-go/v82/checkout/session"
)
-const publicCloudSignupRequestBodyLimit = 64 * 1024
+const (
+ publicCloudSignupRequestBodyLimit = 64 * 1024
+ publicCloudTrialDays = 14
+)
// cloudTier represents a Cloud plan tier for public signup.
type cloudTier string
@@ -271,7 +274,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
Cancelled: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("cancelled")), "1"),
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
}
h.renderSignupPage(w, r, http.StatusOK, data)
case http.MethodPost:
@@ -293,7 +296,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
ErrorMessage: "Invalid plan tier selected.",
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
})
return
}
@@ -307,7 +310,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
ErrorMessage: "A valid email address is required.",
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
})
return
}
@@ -320,7 +323,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
ErrorMessage: "Organization name must be 3-64 characters and cannot contain slashes.",
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
})
return
}
@@ -333,7 +336,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
ErrorMessage: "The selected plan tier is not currently available.",
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
})
return
}
@@ -349,7 +352,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupPage(w http.ResponseWriter, r *h
ErrorMessage: "Unable to create checkout session. Please try again.",
HasPower: h.cfg != nil && strings.TrimSpace(h.cfg.CloudPowerPriceID) != "",
HasMax: h.cfg != nil && strings.TrimSpace(h.cfg.CloudMaxPriceID) != "",
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
})
return
}
@@ -367,7 +370,7 @@ func (h *PublicCloudSignupHandlers) HandleSignupComplete(w http.ResponseWriter,
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := publicCloudSignupCompleteTemplate.Execute(w, publicCloudSignupCompleteData{
Nonce: cpsec.NonceFromContext(r.Context()),
- TrialDays: trialSignupTrialDays,
+ TrialDays: publicCloudTrialDays,
}); err != nil {
log.Error().Err(err).Msg("public cloud signup complete page render failed")
}
@@ -416,7 +419,7 @@ func (h *PublicCloudSignupHandlers) HandlePublicSignup(w http.ResponseWriter, r
writePublicSignupJSON(w, http.StatusCreated, map[string]any{
"checkout_url": checkoutURL,
- "message": fmt.Sprintf("Checkout session created. Continue in Stripe to start your %d-day Pulse Cloud trial and provision your workspace.", trialSignupTrialDays),
+ "message": fmt.Sprintf("Checkout session created. Continue in Stripe to start your %d-day Pulse Cloud trial and provision your workspace.", publicCloudTrialDays),
})
}
@@ -530,7 +533,7 @@ func (h *PublicCloudSignupHandlers) createCheckout(email, orgName string, tier c
},
},
SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
- TrialPeriodDays: stripe.Int64(trialSignupTrialDays),
+ TrialPeriodDays: stripe.Int64(publicCloudTrialDays),
},
Metadata: h.buildCheckoutMetadata(priceID, orgName),
}
@@ -563,7 +566,7 @@ func (h *PublicCloudSignupHandlers) buildCheckoutMetadata(priceID, orgName strin
func (h *PublicCloudSignupHandlers) renderSignupPage(w http.ResponseWriter, r *http.Request, status int, data publicCloudSignupPageData) {
data.Nonce = cpsec.NonceFromContext(r.Context())
if data.TrialDays <= 0 {
- data.TrialDays = trialSignupTrialDays
+ data.TrialDays = publicCloudTrialDays
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
diff --git a/internal/cloudcp/public_cloud_signup_handlers_test.go b/internal/cloudcp/public_cloud_signup_handlers_test.go
index 911df5123a..7dbe754916 100644
--- a/internal/cloudcp/public_cloud_signup_handlers_test.go
+++ b/internal/cloudcp/public_cloud_signup_handlers_test.go
@@ -3,6 +3,7 @@ package cloudcp
import (
"context"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"net/url"
@@ -75,7 +76,7 @@ func TestPublicCloudSignupHandleSignupPageRendersForm(t *testing.T) {
t.Fatalf("status=%d, want %d", rec.Code, http.StatusOK)
}
body := rec.Body.String()
- if !strings.Contains(body, "<form") || !strings.Contains(body, "Start your 14-day Pulse Cloud trial") {
+ if !strings.Contains(body, "<form") || !strings.Contains(body, fmt.Sprintf("Start your %d-day Pulse Cloud trial", publicCloudTrialDays)) {
t.Fatalf("expected signup form markup in response body")
}
if !strings.Contains(body, "no upfront charge") {
@@ -100,7 +101,7 @@ func TestPublicCloudSignupHandleSignupCompleteRendersPulseAccountHandoff(t *test
if !strings.Contains(body, "Trial checkout complete") {
t.Fatalf("expected trial checkout completion heading")
}
- if !strings.Contains(body, "14-day Pulse Cloud trial") {
+ if !strings.Contains(body, fmt.Sprintf("%d-day Pulse Cloud trial", publicCloudTrialDays)) {
t.Fatalf("expected trial duration in completion copy")
}
if !strings.Contains(body, "Pulse Account sign-in link") {
@@ -210,7 +211,7 @@ func TestPublicCloudSignupHandlePublicSignupCreatesCheckout(t *testing.T) {
if got := strings.TrimSpace(asString(payload["checkout_url"])); got != "https://checkout.stripe.com/c/pay/cs_live" {
t.Fatalf("checkout_url=%q, want stripe URL", got)
}
- if got := strings.TrimSpace(asString(payload["message"])); !strings.Contains(got, "14-day Pulse Cloud trial") {
+ if got := strings.TrimSpace(asString(payload["message"])); !strings.Contains(got, fmt.Sprintf("%d-day Pulse Cloud trial", publicCloudTrialDays)) {
t.Fatalf("message=%q, want trial copy", got)
}
}
diff --git a/internal/cloudcp/registry/models.go b/internal/cloudcp/registry/models.go
index 44ab5381fb..a36053200d 100644
--- a/internal/cloudcp/registry/models.go
+++ b/internal/cloudcp/registry/models.go
@@ -139,32 +139,6 @@ type HostedEntitlement struct {
RevokedAt *time.Time `json:"revoked_at,omitempty"`
}
-type TrialHostedEntitlementInput struct {
- RequestID string
- OrgID string
- Email string
- ReturnURL string
- InstanceToken string
- InstanceHost string
- TrialStartedAt time.Time
- IssuedAt time.Time
- RedeemedAt time.Time
- RefreshToken string
-}
-
-type TrialHostedActivationInput struct {
- RequestID string
- OrgID string
- Email string
- ReturnURL string
- InstanceToken string
- InstanceHost string
- TrialStartedAt time.Time
- IssuedAt time.Time
- ActivationToken string
- RefreshToken string
-}
-
// StripeAccount maps a control-plane account to a single Stripe customer +
// subscription for consolidated (MSP-style) billing.
type StripeAccount struct {
diff --git a/internal/cloudcp/registry/registry.go b/internal/cloudcp/registry/registry.go
index 980e5a25f7..80905dd297 100644
--- a/internal/cloudcp/registry/registry.go
+++ b/internal/cloudcp/registry/registry.go
@@ -869,10 +869,6 @@ func paidHostedEntitlementID(tenantID string) string {
return "paid:" + strings.TrimSpace(tenantID)
}
-func trialHostedEntitlementID(requestID string) string {
- return "trial:" + strings.TrimSpace(requestID)
-}
-
// StoreOrIssueHostedEntitlement stores a new hosted entitlement refresh token for a paid tenant,
// or returns the existing active token if one has already been issued.
func (r *TenantRegistry) StoreOrIssueHostedEntitlement(tenantID, token string, issuedAt time.Time) (string, bool, error) {
@@ -960,251 +956,6 @@ func (r *TenantRegistry) StoreOrIssueHostedEntitlement(tenantID, token string, i
return token, true, nil
}
-func (r *TenantRegistry) StoreOrIssueTrialHostedEntitlement(input TrialHostedEntitlementInput) (string, bool, error) {
- requestID := strings.TrimSpace(input.RequestID)
- token := strings.TrimSpace(input.RefreshToken)
- if requestID == "" {
- return "", false, fmt.Errorf("missing trial request id")
- }
- if token == "" {
- return "", false, fmt.Errorf("missing entitlement refresh token")
- }
- if strings.TrimSpace(input.OrgID) == "" || strings.TrimSpace(input.Email) == "" || strings.TrimSpace(input.ReturnURL) == "" || strings.TrimSpace(input.InstanceHost) == "" {
- return "", false, fmt.Errorf("trial entitlement input is incomplete")
- }
-
- issuedAt := input.IssuedAt.UTC()
- redeemedAt := input.RedeemedAt.UTC()
- trialStartedAt := input.TrialStartedAt.UTC()
-
- tx, err := r.db.Begin()
- if err != nil {
- return "", false, fmt.Errorf("begin trial hosted entitlement tx: %w", err)
- }
- defer func() {
- if tx != nil {
- _ = tx.Rollback()
- }
- }()
-
- rec, err := loadHostedEntitlement(tx.QueryRow(`
- SELECT id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- FROM hosted_entitlements WHERE trial_request_id = ?`,
- requestID,
- ))
- if err != nil {
- return "", false, fmt.Errorf("load trial hosted entitlement: %w", err)
- }
- if rec != nil && strings.TrimSpace(rec.RefreshToken) != "" && rec.RevokedAt == nil {
- if _, err := tx.Exec(`
- UPDATE hosted_entitlements
- SET org_id = ?, email = ?, return_url = ?, instance_token = ?, instance_host = ?, trial_started_at = ?,
- redeemed_at = COALESCE(redeemed_at, ?)
- WHERE id = ?`,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- redeemedAt.Unix(),
- rec.ID,
- ); err != nil {
- return "", false, fmt.Errorf("update trial hosted entitlement metadata: %w", err)
- }
- if err := tx.Commit(); err != nil {
- return "", false, fmt.Errorf("commit trial hosted entitlement tx: %w", err)
- }
- tx = nil
- return rec.RefreshToken, false, nil
- }
-
- if rec == nil {
- if _, err := tx.Exec(`
- INSERT INTO hosted_entitlements (
- id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- ) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, NULL, NULL, ?, NULL)`,
- trialHostedEntitlementID(requestID),
- string(HostedEntitlementKindTrial),
- requestID,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- token,
- issuedAt.Unix(),
- redeemedAt.Unix(),
- ); err != nil {
- return "", false, fmt.Errorf("insert trial hosted entitlement: %w", err)
- }
- } else {
- if _, err := tx.Exec(`
- UPDATE hosted_entitlements
- SET id = ?, kind = ?, tenant_id = NULL, trial_request_id = ?, org_id = ?, email = ?, return_url = ?,
- instance_token = ?, instance_host = ?, trial_started_at = ?, refresh_token = ?, issued_at = ?,
- last_refreshed_at = NULL, redeemed_at = ?, revoked_at = NULL
- WHERE trial_request_id = ?`,
- trialHostedEntitlementID(requestID),
- string(HostedEntitlementKindTrial),
- requestID,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- token,
- issuedAt.Unix(),
- redeemedAt.Unix(),
- requestID,
- ); err != nil {
- return "", false, fmt.Errorf("rotate trial hosted entitlement: %w", err)
- }
- }
-
- if err := tx.Commit(); err != nil {
- return "", false, fmt.Errorf("commit trial hosted entitlement tx: %w", err)
- }
- tx = nil
- return token, true, nil
-}
-
-func (r *TenantRegistry) StoreOrRotateTrialActivation(input TrialHostedActivationInput, ttl time.Duration) (string, bool, error) {
- requestID := strings.TrimSpace(input.RequestID)
- activationToken := strings.TrimSpace(input.ActivationToken)
- refreshToken := strings.TrimSpace(input.RefreshToken)
- if requestID == "" {
- return "", false, fmt.Errorf("missing trial request id")
- }
- if activationToken == "" {
- return "", false, fmt.Errorf("missing activation token")
- }
- if refreshToken == "" {
- return "", false, fmt.Errorf("missing entitlement refresh token")
- }
- if strings.TrimSpace(input.OrgID) == "" || strings.TrimSpace(input.Email) == "" || strings.TrimSpace(input.ReturnURL) == "" || strings.TrimSpace(input.InstanceHost) == "" {
- return "", false, fmt.Errorf("trial activation input is incomplete")
- }
- if ttl <= 0 {
- return "", false, fmt.Errorf("activation ttl is required")
- }
-
- issuedAt := input.IssuedAt.UTC()
- if issuedAt.IsZero() {
- return "", false, fmt.Errorf("activation issued_at is required")
- }
- trialStartedAt := input.TrialStartedAt.UTC()
- if trialStartedAt.IsZero() {
- trialStartedAt = issuedAt
- }
- rotateBefore := issuedAt.Add(-ttl)
-
- tx, err := r.db.Begin()
- if err != nil {
- return "", false, fmt.Errorf("begin trial activation tx: %w", err)
- }
- defer func() {
- if tx != nil {
- _ = tx.Rollback()
- }
- }()
-
- rec, err := loadHostedEntitlement(tx.QueryRow(`
- SELECT id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- FROM hosted_entitlements WHERE trial_request_id = ?`,
- requestID,
- ))
- if err != nil {
- return "", false, fmt.Errorf("load trial activation entitlement: %w", err)
- }
-
- if rec != nil && strings.TrimSpace(rec.ActivationToken) != "" && rec.ActivationIssuedAt != nil && rec.ActivationIssuedAt.After(rotateBefore) && rec.RevokedAt == nil {
- if _, err := tx.Exec(`
- UPDATE hosted_entitlements
- SET org_id = ?, email = ?, return_url = ?, instance_token = ?, instance_host = ?, trial_started_at = ?
- WHERE id = ?`,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- rec.ID,
- ); err != nil {
- return "", false, fmt.Errorf("update trial activation metadata: %w", err)
- }
- if err := tx.Commit(); err != nil {
- return "", false, fmt.Errorf("commit trial activation tx: %w", err)
- }
- tx = nil
- return rec.ActivationToken, false, nil
- }
-
- if rec == nil {
- if _, err := tx.Exec(`
- INSERT INTO hosted_entitlements (
- id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- ) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL)`,
- trialHostedEntitlementID(requestID),
- string(HostedEntitlementKindTrial),
- requestID,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- refreshToken,
- activationToken,
- issuedAt.Unix(),
- issuedAt.Unix(),
- ); err != nil {
- return "", false, fmt.Errorf("insert trial activation entitlement: %w", err)
- }
- } else {
- effectiveRefreshToken := strings.TrimSpace(rec.RefreshToken)
- if effectiveRefreshToken == "" {
- effectiveRefreshToken = refreshToken
- }
- if _, err := tx.Exec(`
- UPDATE hosted_entitlements
- SET id = ?, kind = ?, tenant_id = NULL, trial_request_id = ?, org_id = ?, email = ?, return_url = ?,
- instance_token = ?, instance_host = ?, trial_started_at = ?, refresh_token = ?, activation_token = ?,
- issued_at = CASE WHEN issued_at > 0 THEN issued_at ELSE ? END, activation_issued_at = ?,
- last_refreshed_at = NULL, revoked_at = NULL
- WHERE trial_request_id = ?`,
- trialHostedEntitlementID(requestID),
- string(HostedEntitlementKindTrial),
- requestID,
- strings.TrimSpace(input.OrgID),
- strings.TrimSpace(input.Email),
- strings.TrimSpace(input.ReturnURL),
- strings.TrimSpace(input.InstanceToken),
- strings.TrimSpace(input.InstanceHost),
- trialStartedAt.Unix(),
- effectiveRefreshToken,
- activationToken,
- issuedAt.Unix(),
- issuedAt.Unix(),
- requestID,
- ); err != nil {
- return "", false, fmt.Errorf("rotate trial activation entitlement: %w", err)
- }
- }
-
- if err := tx.Commit(); err != nil {
- return "", false, fmt.Errorf("commit trial activation tx: %w", err)
- }
- tx = nil
- return activationToken, true, nil
-}
-
func scanTenants(rows *sql.Rows) ([]*Tenant, error) {
var tenants []*Tenant
for rows.Next() {
@@ -1229,28 +980,6 @@ func (r *TenantRegistry) GetHostedEntitlementByRefreshToken(token string) (*Host
return loadHostedEntitlement(row)
}
-func (r *TenantRegistry) GetHostedEntitlementByActivationToken(token string) (*HostedEntitlement, error) {
- row := r.db.QueryRow(`
- SELECT id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- FROM hosted_entitlements
- WHERE activation_token = ?`,
- strings.TrimSpace(token),
- )
- return loadHostedEntitlement(row)
-}
-
-func (r *TenantRegistry) GetHostedEntitlementByTrialRequestID(requestID string) (*HostedEntitlement, error) {
- row := r.db.QueryRow(`
- SELECT id, kind, tenant_id, trial_request_id, org_id, email, return_url, instance_token, instance_host,
- trial_started_at, refresh_token, activation_token, issued_at, activation_issued_at, last_refreshed_at, redeemed_at, revoked_at
- FROM hosted_entitlements
- WHERE trial_request_id = ?`,
- strings.TrimSpace(requestID),
- )
- return loadHostedEntitlement(row)
-}
-
// ListHostedEntitlements returns all hosted entitlement authority rows.
func (r *TenantRegistry) ListHostedEntitlements() ([]*HostedEntitlement, error) {
rows, err := r.db.Query(`
diff --git a/internal/cloudcp/registry/registry_test.go b/internal/cloudcp/registry/registry_test.go
index a3c5bcc7bd..6ede578685 100644
--- a/internal/cloudcp/registry/registry_test.go
+++ b/internal/cloudcp/registry/registry_test.go
@@ -1312,165 +1312,6 @@ func TestTenantRegistryCanonicalizesStripeAccountPlanVersion(t *testing.T) {
}
}
-func TestStoreOrIssueTrialHostedEntitlement(t *testing.T) {
- reg := newTestRegistry(t)
-
- now := time.Now().UTC()
- stored, firstIssue, err := reg.StoreOrIssueTrialHostedEntitlement(TrialHostedEntitlementInput{
- RequestID: "trial_request_1",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now,
- RedeemedAt: now,
- RefreshToken: "etr_trial_one",
- })
- if err != nil {
- t.Fatalf("StoreOrIssueTrialHostedEntitlement(first): %v", err)
- }
- if !firstIssue {
- t.Fatal("first trial issue should report firstIssue=true")
- }
- if stored != "etr_trial_one" {
- t.Fatalf("stored token=%q, want %q", stored, "etr_trial_one")
- }
-
- loaded, err := reg.GetHostedEntitlementByRefreshToken("etr_trial_one")
- if err != nil {
- t.Fatalf("GetHostedEntitlementByRefreshToken: %v", err)
- }
- if loaded == nil || loaded.Kind != HostedEntitlementKindTrial {
- t.Fatalf("expected trial entitlement, got %#v", loaded)
- }
- if loaded.TrialRequestID != "trial_request_1" {
- t.Fatalf("TrialRequestID=%q, want %q", loaded.TrialRequestID, "trial_request_1")
- }
- if loaded.RedeemedAt == nil || loaded.TrialStartedAt == nil {
- t.Fatalf("expected redeemed/trial_started timestamps, got %#v", loaded)
- }
-
- stored, firstIssue, err = reg.StoreOrIssueTrialHostedEntitlement(TrialHostedEntitlementInput{
- RequestID: "trial_request_1",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now.Add(time.Minute),
- RedeemedAt: now.Add(time.Minute),
- RefreshToken: "etr_trial_two",
- })
- if err != nil {
- t.Fatalf("StoreOrIssueTrialHostedEntitlement(second): %v", err)
- }
- if firstIssue {
- t.Fatal("second trial issue should report firstIssue=false")
- }
- if stored != "etr_trial_one" {
- t.Fatalf("stored token on second issue=%q, want %q", stored, "etr_trial_one")
- }
-}
-
-func TestStoreOrRotateTrialActivation(t *testing.T) {
- reg := newTestRegistry(t)
-
- now := time.Now().UTC()
- stored, firstIssue, err := reg.StoreOrRotateTrialActivation(TrialHostedActivationInput{
- RequestID: "trial_request_activation",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now,
- ActivationToken: "act_one",
- RefreshToken: "etr_hidden_one",
- }, 10*time.Minute)
- if err != nil {
- t.Fatalf("StoreOrRotateTrialActivation(first): %v", err)
- }
- if !firstIssue {
- t.Fatal("first activation issue should report firstIssue=true")
- }
- if stored != "act_one" {
- t.Fatalf("stored activation=%q, want %q", stored, "act_one")
- }
-
- loaded, err := reg.GetHostedEntitlementByTrialRequestID("trial_request_activation")
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID: %v", err)
- }
- if loaded == nil || loaded.Kind != HostedEntitlementKindTrial {
- t.Fatalf("expected trial hosted entitlement, got %#v", loaded)
- }
- if loaded.RefreshToken != "etr_hidden_one" {
- t.Fatalf("RefreshToken=%q, want %q", loaded.RefreshToken, "etr_hidden_one")
- }
- if loaded.ActivationToken != "act_one" {
- t.Fatalf("ActivationToken=%q, want %q", loaded.ActivationToken, "act_one")
- }
-
- stored, firstIssue, err = reg.StoreOrRotateTrialActivation(TrialHostedActivationInput{
- RequestID: "trial_request_activation",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now.Add(time.Minute),
- ActivationToken: "act_two",
- RefreshToken: "etr_hidden_two",
- }, 10*time.Minute)
- if err != nil {
- t.Fatalf("StoreOrRotateTrialActivation(second): %v", err)
- }
- if firstIssue {
- t.Fatal("second activation issue should report firstIssue=false")
- }
- if stored != "act_one" {
- t.Fatalf("stored activation=%q, want %q", stored, "act_one")
- }
-
- stored, firstIssue, err = reg.StoreOrRotateTrialActivation(TrialHostedActivationInput{
- RequestID: "trial_request_activation",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now.Add(11 * time.Minute),
- ActivationToken: "act_three",
- RefreshToken: "etr_hidden_three",
- }, 10*time.Minute)
- if err != nil {
- t.Fatalf("StoreOrRotateTrialActivation(third): %v", err)
- }
- if !firstIssue {
- t.Fatal("expired activation should rotate")
- }
- if stored != "act_three" {
- t.Fatalf("stored activation=%q, want %q", stored, "act_three")
- }
-
- loaded, err = reg.GetHostedEntitlementByActivationToken("act_three")
- if err != nil {
- t.Fatalf("GetHostedEntitlementByActivationToken: %v", err)
- }
- if loaded == nil || loaded.TrialRequestID != "trial_request_activation" {
- t.Fatalf("expected activation lookup to return hosted entitlement, got %#v", loaded)
- }
- if loaded.RefreshToken != "etr_hidden_one" {
- t.Fatalf("RefreshToken=%q, want original %q", loaded.RefreshToken, "etr_hidden_one")
- }
-}
-
func TestCreateStripeAccount_RequiresExistingAccount(t *testing.T) {
reg := newTestRegistry(t)
diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.go
index ea9940e75a..b630d41b06 100644
--- a/internal/cloudcp/routes.go
+++ b/internal/cloudcp/routes.go
@@ -25,7 +25,6 @@ type Deps struct {
Registry *registry.TenantRegistry
Docker *docker.Manager // nil if Docker is unavailable
MagicLinks *cpauth.Service // control plane magic link service
- TrialSignupStore *TrialSignupStore
Provisioner *cpstripe.Provisioner
HostedEntitlements *entitlements.Service
Version string
@@ -47,12 +46,6 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {
adminLimiter := NewCPRateLimiter(deps.Config.AdminRateLimitPerMinute, time.Minute)
accountAPILimiter := NewCPRateLimiter(deps.Config.AccountAPIRateLimitPerMinute, time.Minute)
portalAPILimiter := NewCPRateLimiter(deps.Config.PortalAPIRateLimitPerMinute, time.Minute)
- trialSignupPageLimiter := NewCPRateLimiter(30, time.Minute)
- trialSignupVerificationLimiter := NewCPRateLimiter(6, time.Hour)
- trialSignupVerifyLimiter := NewCPRateLimiter(30, time.Minute)
- trialSignupCheckoutLimiter := NewCPRateLimiter(12, time.Hour)
- trialSignupCompleteLimiter := NewCPRateLimiter(30, time.Minute)
- trialSignupRedeemLimiter := NewCPRateLimiter(30, time.Minute)
hostedEntitlementRefreshLimiter := NewCPRateLimiter(60, time.Hour)
publicSignupLimiter := NewCPRateLimiter(30, time.Minute)
publicMagicLinkLimiter := NewCPRateLimiter(20, time.Minute)
@@ -142,17 +135,9 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {
mux.Handle(portal.PortalLogoutPath, sessionAuthLimiter.Middleware(sessionAuth(cpauth.HandleLogout(deps.Registry))))
}
- // Hosted Pulse Pro trial signup: public form + checkout + return completion.
- trialSignupHandlers := NewTrialSignupHandlers(deps.Config, deps.EmailSender, deps.TrialSignupStore, hostedEntitlements)
+ // Hosted entitlement refresh stays available for already-issued hosted leases.
hostedEntitlementHandlers := NewHostedEntitlementHandlers(hostedEntitlements)
- mux.Handle("/start-pro-trial", trialSignupPageLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleStartProTrial)))
- mux.Handle("/api/trial-signup/request-verification", trialSignupVerificationLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleRequestVerification)))
- mux.Handle("/trial-signup/verify", trialSignupVerifyLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleVerifyEmail)))
- mux.Handle("/api/trial-signup/checkout", trialSignupCheckoutLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleCheckout)))
- mux.Handle("/trial-signup/complete", trialSignupCompleteLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupComplete)))
- mux.Handle("/api/trial-signup/redeem", trialSignupRedeemLimiter.Middleware(http.HandlerFunc(trialSignupHandlers.HandleTrialSignupRedeem)))
mux.Handle("/api/entitlements/refresh", hostedEntitlementRefreshLimiter.Middleware(http.HandlerFunc(hostedEntitlementHandlers.HandleRefresh)))
- mux.Handle("/api/trial-signup/refresh", hostedEntitlementRefreshLimiter.Middleware(http.HandlerFunc(hostedEntitlementHandlers.HandleRefresh)))
// Public commercial magic-link requests stay available for existing hosted
// accounts even while public v6 Cloud signup remains prelaunch-disabled.
diff --git a/internal/cloudcp/routes_favicon_test.go b/internal/cloudcp/routes_favicon_test.go
index f3442e25dc..8df002e53f 100644
--- a/internal/cloudcp/routes_favicon_test.go
+++ b/internal/cloudcp/routes_favicon_test.go
@@ -16,11 +16,6 @@ func TestRegisterRoutes_ControlPlaneFavicons(t *testing.T) {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -30,9 +25,8 @@ func TestRegisterRoutes_ControlPlaneFavicons(t *testing.T) {
BaseURL: "https://cloud.example.com",
StripeWebhookSecret: "whsec_test",
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
svgReq := httptest.NewRequest(http.MethodGet, "/favicon.svg", nil)
diff --git a/internal/cloudcp/routes_test.go b/internal/cloudcp/routes_test.go
index 6df94115d6..6ff913006b 100644
--- a/internal/cloudcp/routes_test.go
+++ b/internal/cloudcp/routes_test.go
@@ -16,11 +16,6 @@ func TestRegisterRoutes_AccountAndTenantMethodDispatch(t *testing.T) {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -31,9 +26,8 @@ func TestRegisterRoutes_AccountAndTenantMethodDispatch(t *testing.T) {
StripeWebhookSecret: "whsec_test",
PublicCloudSignupEnabled: true,
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
tests := []struct {
@@ -100,11 +94,6 @@ func TestRegisterRoutes_FaviconRouteParity(t *testing.T) {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -115,9 +104,8 @@ func TestRegisterRoutes_FaviconRouteParity(t *testing.T) {
StripeWebhookSecret: "whsec_test",
PublicCloudSignupEnabled: true,
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
svgReq := httptest.NewRequest(http.MethodGet, "/favicon.svg", nil)
@@ -148,18 +136,13 @@ func TestRegisterRoutes_FaviconRouteParity(t *testing.T) {
}
}
-func TestRegisterRoutes_TrialSignupRoutes(t *testing.T) {
+func TestRegisterRoutes_RetiredTrialSignupRoutes(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
if err != nil {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -170,54 +153,28 @@ func TestRegisterRoutes_TrialSignupRoutes(t *testing.T) {
StripeWebhookSecret: "whsec_test",
PublicCloudSignupEnabled: true,
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
- pageReq := httptest.NewRequest(http.MethodGet, "/start-pro-trial?org_id=default&return_url=https://pulse.example.com/auth/trial-activate&instance_token=tsi_test", nil)
- pageRec := httptest.NewRecorder()
- mux.ServeHTTP(pageRec, pageReq)
- if pageRec.Code != http.StatusOK {
- t.Fatalf("GET /start-pro-trial status=%d, want %d", pageRec.Code, http.StatusOK)
- }
- if !strings.Contains(pageRec.Body.String(), "Continue To Secure Trial Setup") {
- t.Fatalf("expected trial signup page body")
- }
-
- verifyReq := httptest.NewRequest(http.MethodGet, "/trial-signup/verify", nil)
- verifyRec := httptest.NewRecorder()
- mux.ServeHTTP(verifyRec, verifyReq)
- if verifyRec.Code != http.StatusBadRequest {
- t.Fatalf("GET /trial-signup/verify status=%d, want %d", verifyRec.Code, http.StatusBadRequest)
- }
-
- requestVerificationReq := httptest.NewRequest(http.MethodGet, "/api/trial-signup/request-verification", nil)
- requestVerificationRec := httptest.NewRecorder()
- mux.ServeHTTP(requestVerificationRec, requestVerificationReq)
- if requestVerificationRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("GET /api/trial-signup/request-verification status=%d, want %d", requestVerificationRec.Code, http.StatusMethodNotAllowed)
- }
-
- checkoutReq := httptest.NewRequest(http.MethodGet, "/api/trial-signup/checkout", nil)
- checkoutRec := httptest.NewRecorder()
- mux.ServeHTTP(checkoutRec, checkoutReq)
- if checkoutRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("GET /api/trial-signup/checkout status=%d, want %d", checkoutRec.Code, http.StatusMethodNotAllowed)
- }
-
- redeemReq := httptest.NewRequest(http.MethodGet, "/api/trial-signup/redeem", nil)
- redeemRec := httptest.NewRecorder()
- mux.ServeHTTP(redeemRec, redeemReq)
- if redeemRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("GET /api/trial-signup/redeem status=%d, want %d", redeemRec.Code, http.StatusMethodNotAllowed)
- }
-
- refreshReq := httptest.NewRequest(http.MethodGet, "/api/trial-signup/refresh", nil)
- refreshRec := httptest.NewRecorder()
- mux.ServeHTTP(refreshRec, refreshReq)
- if refreshRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("GET /api/trial-signup/refresh status=%d, want %d", refreshRec.Code, http.StatusMethodNotAllowed)
+ for _, tc := range []struct {
+ method string
+ path string
+ }{
+ {method: http.MethodGet, path: "/start-pro-trial?org_id=default&return_url=https://pulse.example.com/auth/trial-activate&instance_token=tsi_test"},
+ {method: http.MethodPost, path: "/api/trial-signup/request-verification"},
+ {method: http.MethodGet, path: "/trial-signup/verify"},
+ {method: http.MethodPost, path: "/api/trial-signup/checkout"},
+ {method: http.MethodGet, path: "/trial-signup/complete"},
+ {method: http.MethodPost, path: "/api/trial-signup/redeem"},
+ {method: http.MethodPost, path: "/api/trial-signup/refresh"},
+ } {
+ req := httptest.NewRequest(tc.method, tc.path, nil)
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("%s %s status=%d, want %d", tc.method, tc.path, rec.Code, http.StatusNotFound)
+ }
}
hostedRefreshReq := httptest.NewRequest(http.MethodGet, "/api/entitlements/refresh", nil)
@@ -228,51 +185,6 @@ func TestRegisterRoutes_TrialSignupRoutes(t *testing.T) {
}
}
-func TestRegisterRoutes_TrialSignupVerificationRateLimit(t *testing.T) {
- dir := t.TempDir()
- reg, err := registry.NewTenantRegistry(dir)
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
-
- mux := http.NewServeMux()
- RegisterRoutes(mux, &Deps{
- Config: &CPConfig{
- DataDir: dir,
- AdminKey: "test-admin-key",
- BaseURL: "https://cloud.example.com",
- StripeWebhookSecret: "whsec_test",
- },
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
- })
-
- for i := 0; i < 6; i++ {
- req := httptest.NewRequest(http.MethodGet, "/api/trial-signup/request-verification", nil)
- req.RemoteAddr = "198.51.100.25:7777"
- rec := httptest.NewRecorder()
- mux.ServeHTTP(rec, req)
- if rec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("attempt %d status=%d, want %d", i+1, rec.Code, http.StatusMethodNotAllowed)
- }
- }
-
- req := httptest.NewRequest(http.MethodGet, "/api/trial-signup/request-verification", nil)
- req.RemoteAddr = "198.51.100.25:7777"
- rec := httptest.NewRecorder()
- mux.ServeHTTP(rec, req)
- if rec.Code != http.StatusTooManyRequests {
- t.Fatalf("rate-limited status=%d, want %d body=%q", rec.Code, http.StatusTooManyRequests, rec.Body.String())
- }
-}
-
func TestRegisterRoutes_PublicCloudSignupRoutes(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
@@ -280,11 +192,6 @@ func TestRegisterRoutes_PublicCloudSignupRoutes(t *testing.T) {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -295,9 +202,8 @@ func TestRegisterRoutes_PublicCloudSignupRoutes(t *testing.T) {
StripeWebhookSecret: "whsec_test",
PublicCloudSignupEnabled: true,
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
signupPageReq := httptest.NewRequest(http.MethodGet, "/signup", nil)
@@ -340,11 +246,6 @@ func TestRegisterRoutes_PublicCloudSignupRoutesDisabledByDefault(t *testing.T) {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
- trialStore, err := NewTrialSignupStore(dir)
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { trialStore.Close() })
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
@@ -354,9 +255,8 @@ func TestRegisterRoutes_PublicCloudSignupRoutesDisabledByDefault(t *testing.T) {
BaseURL: "https://cloud.example.com",
StripeWebhookSecret: "whsec_test",
},
- Registry: reg,
- TrialSignupStore: trialStore,
- Version: "test",
+ Registry: reg,
+ Version: "test",
})
for _, tc := range []struct {
diff --git a/internal/cloudcp/server.go b/internal/cloudcp/server.go
index d731d94399..6c41c90672 100644
--- a/internal/cloudcp/server.go
+++ b/internal/cloudcp/server.go
@@ -77,12 +77,6 @@ func Run(ctx context.Context, version string) error {
}
defer magicLinkSvc.Close()
- trialSignupStore, err := NewTrialSignupStore(cfg.ControlPlaneDir())
- if err != nil {
- return fmt.Errorf("init trial signup store: %w", err)
- }
- defer trialSignupStore.Close()
-
// Initialize email sender
var emailSender email.Sender
if cfg.ResendAPIKey != "" {
@@ -129,7 +123,6 @@ func Run(ctx context.Context, version string) error {
Registry: reg,
Docker: dockerMgr,
MagicLinks: magicLinkSvc,
- TrialSignupStore: trialSignupStore,
Provisioner: provisioner,
HostedEntitlements: hostedEntitlements,
Version: version,
diff --git a/internal/cloudcp/stripe/webhook.go b/internal/cloudcp/stripe/webhook.go
index c80a0ad165..136000b08b 100644
--- a/internal/cloudcp/stripe/webhook.go
+++ b/internal/cloudcp/stripe/webhook.go
@@ -141,7 +141,7 @@ func (h *WebhookHandler) handleEvent(r *http.Request, event *stripelib.Event) er
if isSelfHostedProTrialCheckout(session) {
log.Info().
Str("session_id", strings.TrimSpace(session.ID)).
- Msg("Stripe webhook ignored self-hosted Pro trial checkout; activation is owned by trial signup completion")
+ Msg("Stripe webhook ignored retired self-hosted Pro trial checkout")
return nil
}
return h.provisioner.HandleCheckout(ctx, session)
diff --git a/internal/cloudcp/trial_signup_handlers.go b/internal/cloudcp/trial_signup_handlers.go
deleted file mode 100644
index 7e75e138f1..0000000000
--- a/internal/cloudcp/trial_signup_handlers.go
+++ /dev/null
@@ -1,1567 +0,0 @@
-package cloudcp
-
-import (
- "context"
- "crypto/ed25519"
- "encoding/json"
- "errors"
- "html/template"
- "net/http"
- "net/mail"
- "net/url"
- "strconv"
- "strings"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/cpsec"
- cpemail "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/email"
- "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/entitlements"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rs/zerolog/log"
- stripe "github.com/stripe/stripe-go/v82"
- stripesession "github.com/stripe/stripe-go/v82/checkout/session"
-)
-
-const (
- trialSignupDefaultOrgID = "default"
- trialSignupTrialDays = 14
- trialSignupVerificationTTL = 20 * time.Minute
- trialSignupActivationTokenTTL = 10 * time.Minute
- stripeCheckoutSessionIDPlaceholder = "{CHECKOUT_SESSION_ID}"
-)
-
-var trialSignupPageTemplate = template.Must(template.New("trial-signup-page").Parse(`<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Start Pulse Pro Trial</title>
- <style nonce="{{.Nonce}}">
- :root {
- color-scheme: light;
- --bg-top: #f7f3ea;
- --bg-bottom: #e9efe8;
- --card: #fffdf8;
- --line: #d8dccf;
- --text: #14261f;
- --muted: #4d5f57;
- --accent: #0f766e;
- --accent-deep: #115e59;
- --error-bg: #fef2f2;
- --error-line: #fecaca;
- --error-text: #991b1b;
- --note-bg: #eefbf4;
- --note-line: #bfe8ce;
- --note-text: #166534;
- }
- * { box-sizing: border-box; }
- body {
- margin: 0;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
- background:
- radial-gradient(circle at top left, rgba(15,118,110,.10), transparent 34%),
- linear-gradient(155deg, var(--bg-top), var(--bg-bottom));
- color: var(--text);
- }
- .wrap { max-width: 840px; margin: 40px auto; padding: 0 18px; }
- .card {
- background: var(--card);
- border-radius: 18px;
- border: 1px solid rgba(20,38,31,.10);
- box-shadow: 0 18px 60px rgba(20,38,31,.10);
- overflow: hidden;
- }
- .hero {
- padding: 28px 28px 18px;
- background:
- linear-gradient(130deg, rgba(15,118,110,.10), rgba(15,118,110,0)),
- linear-gradient(180deg, rgba(255,255,255,.92), rgba(255,255,255,.75));
- border-bottom: 1px solid rgba(20,38,31,.08);
- }
- .eyebrow {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 6px 10px;
- border-radius: 999px;
- background: rgba(15,118,110,.10);
- color: var(--accent-deep);
- font-size: 12px;
- font-weight: 700;
- letter-spacing: .04em;
- text-transform: uppercase;
- margin-bottom: 14px;
- }
- .hero h1 { margin: 0 0 10px; font-size: 34px; line-height: 1.05; }
- .hero p { margin: 0; max-width: 620px; font-size: 16px; line-height: 1.6; color: var(--muted); }
- .content { display: grid; gap: 0; }
- @media (min-width: 760px) { .content { grid-template-columns: 1.2fr .8fr; } }
- .form-col { padding: 24px 28px 28px; }
- .aside {
- padding: 24px 28px 28px;
- background: rgba(20,38,31,.03);
- border-top: 1px solid rgba(20,38,31,.08);
- }
- @media (min-width: 760px) { .aside { border-top: 0; border-left: 1px solid rgba(20,38,31,.08); } }
- h2 { margin: 0 0 10px; font-size: 20px; }
- p { margin: 0 0 16px; line-height: 1.6; color: var(--muted); }
- .meta {
- background: rgba(255,255,255,.75);
- border: 1px solid var(--line);
- border-radius: 12px;
- padding: 14px 16px;
- margin-bottom: 16px;
- font-size: 14px;
- color: var(--muted);
- }
- .meta strong, .summary strong { display: block; margin-bottom: 3px; color: var(--text); font-size: 12px; letter-spacing: .03em; text-transform: uppercase; }
- .summary {
- background: rgba(255,255,255,.78);
- border: 1px solid var(--line);
- border-radius: 12px;
- padding: 14px 16px;
- margin: 16px 0;
- }
- .summary + .summary { margin-top: 12px; }
- label { display: block; margin: 12px 0 6px; font-size: 14px; font-weight: 600; color: #0f172a; }
- input {
- width: 100%;
- border: 1px solid #c8d2ca;
- border-radius: 10px;
- padding: 11px 13px;
- font-size: 15px;
- background: #fff;
- color: var(--text);
- }
- .row { display: grid; gap: 12px; grid-template-columns: 1fr; }
- @media (min-width: 680px) { .row { grid-template-columns: 1fr 1fr; } }
- .error, .note {
- border-radius: 10px;
- padding: 11px 13px;
- margin-bottom: 14px;
- font-size: 14px;
- line-height: 1.5;
- }
- .error { background: var(--error-bg); color: var(--error-text); border: 1px solid var(--error-line); }
- .note { background: var(--note-bg); color: var(--note-text); border: 1px solid var(--note-line); }
- .cta {
- margin-top: 18px;
- border: 0;
- border-radius: 12px;
- background: var(--accent);
- color: #fff;
- font-size: 16px;
- font-weight: 700;
- padding: 13px 18px;
- width: 100%;
- cursor: pointer;
- }
- .cta:hover { background: var(--accent-deep); }
- .fine { font-size: 12px; color: #64748b; margin-top: 12px; }
- .steps { margin: 0; padding-left: 18px; color: var(--muted); }
- .steps li { margin-bottom: 10px; line-height: 1.5; }
- .mini { font-size: 13px; color: #5f7168; }
- </style>
-</head>
-<body>
- <div class="wrap">
- <div class="card">
- <div class="hero">
- <div class="eyebrow">Pulse Pro Trial</div>
- <h1>Start your 14-day Pro trial for {{.ReturnTarget}}</h1>
- <p>Pulse uses a secure hosted handoff to create the trial entitlement for this specific instance and send you straight back here. I only keep your work email as a recovery contact if this browser session is lost.</p>
- </div>
- <div class="content">
- <div class="form-col">
- {{if .ErrorMessage}}<div class="error">{{.ErrorMessage}}</div>{{end}}
- {{if .Cancelled}}<div class="note">Secure setup was cancelled. You can continue again below.</div>{{end}}
- {{if .VerificationSent}}<div class="note">A backup link was sent to {{.Email}}. You do not need it unless this browser session is lost.</div>{{end}}
-
- {{if .Verified}}
- <h2>Backup link confirmed</h2>
- <p>This recovery link is valid. Continue securely to finish starting the Pro trial for this Pulse instance.</p>
-
- <div class="summary">
- <strong>Work email</strong>
- <div>{{.Email}}</div>
- </div>
- <div class="summary">
- <strong>Name</strong>
- <div>{{.Name}}</div>
- </div>
- {{if .Company}}<div class="summary">
- <strong>Company</strong>
- <div>{{.Company}}</div>
- </div>{{end}}
-
- <form method="POST" action="/api/trial-signup/checkout">
- <input type="hidden" name="verified_token" value="{{.VerifiedToken}}">
- <button class="cta" type="submit">Continue To Secure Trial Setup</button>
- </form>
- <p class="fine">This recovery link is optional. The secure trial session remains the authoritative entitlement handoff.</p>
- {{else}}
- <h2>Continue securely</h2>
- <p>Start the secure trial handoff from this Pulse-initiated session. Email is attached as a recovery contact only.</p>
-
- <form method="POST" action="/api/trial-signup/checkout">
- <input type="hidden" name="org_id" value="{{.OrgID}}">
- <input type="hidden" name="return_url" value="{{.ReturnURL}}">
- <input type="hidden" name="instance_token" value="{{.InstanceToken}}">
-
- <div class="row">
- <div>
- <label for="name">Name</label>
- <input id="name" name="name" type="text" value="{{.Name}}" autocomplete="name" required>
- </div>
- <div>
- <label for="email">Work Email</label>
- <input id="email" name="email" type="email" value="{{.Email}}" autocomplete="email" required>
- </div>
- </div>
-
- <label for="company">Company (optional)</label>
- <input id="company" name="company" type="text" value="{{.Company}}" autocomplete="organization">
-
- <button class="cta" type="submit">Continue To Secure Trial Setup</button>
- </form>
- <p class="fine">Email is used as a recovery contact only. The secure session and signed return to Pulse carry the entitlement.</p>
- {{end}}
- </div>
-
- <div class="aside">
- <div class="meta">
- <strong>Pulse instance</strong>
- <div>{{.ReturnTarget}}</div>
- </div>
- <div class="meta">
- <strong>Workspace</strong>
- <div>{{.OrgID}}</div>
- </div>
- <p class="mini">After secure setup completes, Pulse sends you back to the exact instance that opened this flow.</p>
- <ol class="steps">
- <li>Open a secure trial session for this Pulse instance.</li>
- <li>Confirm the 14-day Pro trial handoff.</li>
- <li>Return to Pulse and activate the entitlement immediately.</li>
- </ol>
- </div>
- </div>
- </div>
- </div>
-</body>
-</html>
-`))
-
-var trialSignupSuccessTemplate = template.Must(template.New("trial-signup-success").Parse(`<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Pulse Pro Trial Ready</title>
- <style nonce="{{.Nonce}}">
- :root {
- color-scheme: light;
- --bg-top: #f7f3ea;
- --bg-bottom: #e9efe8;
- --card: #fffdf8;
- --line: #d8dccf;
- --text: #14261f;
- --muted: #4d5f57;
- --accent: #0f766e;
- --accent-deep: #115e59;
- --good-bg: #eefbf4;
- --good-line: #bfe8ce;
- --good-text: #166534;
- }
- * { box-sizing: border-box; }
- body {
- margin: 0;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
- background:
- radial-gradient(circle at top left, rgba(15,118,110,.10), transparent 34%),
- linear-gradient(155deg, var(--bg-top), var(--bg-bottom));
- color: var(--text);
- }
- .wrap { max-width: 760px; margin: 40px auto; padding: 0 18px; }
- .card {
- background: var(--card);
- border-radius: 18px;
- border: 1px solid rgba(20,38,31,.10);
- box-shadow: 0 18px 60px rgba(20,38,31,.10);
- padding: 28px;
- }
- .eyebrow {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 6px 10px;
- border-radius: 999px;
- background: rgba(15,118,110,.10);
- color: var(--accent-deep);
- font-size: 12px;
- font-weight: 700;
- letter-spacing: .04em;
- text-transform: uppercase;
- margin-bottom: 14px;
- }
- h1 { margin: 0 0 10px; font-size: 34px; line-height: 1.05; }
- p { margin: 0 0 16px; line-height: 1.6; color: var(--muted); }
- .status {
- background: var(--good-bg);
- border: 1px solid var(--good-line);
- border-radius: 12px;
- color: var(--good-text);
- padding: 14px 16px;
- margin: 20px 0;
- font-size: 14px;
- line-height: 1.5;
- }
- .meta {
- display: grid;
- gap: 16px;
- margin: 20px 0;
- }
- @media (min-width: 680px) { .meta { grid-template-columns: 1fr 1fr; } }
- .meta-card {
- background: rgba(255,255,255,.78);
- border: 1px solid var(--line);
- border-radius: 12px;
- padding: 14px 16px;
- }
- .meta-card strong {
- display: block;
- margin-bottom: 6px;
- color: var(--text);
- font-size: 12px;
- letter-spacing: .03em;
- text-transform: uppercase;
- }
- .cta {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- border: 0;
- border-radius: 12px;
- background: var(--accent);
- color: #fff;
- font-size: 16px;
- font-weight: 700;
- padding: 13px 18px;
- text-decoration: none;
- }
- .cta:hover { background: var(--accent-deep); }
- .fine { font-size: 12px; color: #64748b; margin-top: 14px; }
- </style>
-</head>
-<body>
- <div class="wrap">
- <div class="card">
- <div class="eyebrow">Pulse Pro Trial</div>
- <h1>Trial entitlement ready</h1>
- <p>Secure trial setup completed successfully. This session has prepared the signed activation handoff for {{.ReturnTarget}}.</p>
-
- <div class="status">
- Pulse can activate the Pro trial immediately when you return to the originating instance.
- </div>
-
- <div class="meta">
- <div class="meta-card">
- <strong>Pulse instance</strong>
- <div>{{.ReturnTarget}}</div>
- </div>
- <div class="meta-card">
- <strong>Backup email</strong>
- <div>{{.Email}}</div>
- </div>
- </div>
-
- <a class="cta" href="{{.ActivateURL}}">Return To Pulse</a>
- <p class="fine">Email is only a recovery contact. The secure session and this signed return are the authoritative entitlement handoff.</p>
- </div>
- </div>
-</body>
-</html>
-`))
-
-var trialSignupFailureTemplate = template.Must(template.New("trial-signup-failure").Parse(`<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Pulse Pro Trial Setup Issue</title>
- <style nonce="{{.Nonce}}">
- :root {
- color-scheme: light;
- --bg-top: #f7f3ea;
- --bg-bottom: #e9efe8;
- --card: #fffdf8;
- --line: #d8dccf;
- --text: #14261f;
- --muted: #4d5f57;
- --accent: #0f766e;
- --accent-deep: #115e59;
- --warn-bg: #fff7ed;
- --warn-line: #fdba74;
- --warn-text: #9a3412;
- }
- * { box-sizing: border-box; }
- body {
- margin: 0;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
- background:
- radial-gradient(circle at top left, rgba(15,118,110,.10), transparent 34%),
- linear-gradient(155deg, var(--bg-top), var(--bg-bottom));
- color: var(--text);
- }
- .wrap { max-width: 760px; margin: 40px auto; padding: 0 18px; }
- .card {
- background: var(--card);
- border-radius: 18px;
- border: 1px solid rgba(20,38,31,.10);
- box-shadow: 0 18px 60px rgba(20,38,31,.10);
- padding: 28px;
- }
- .eyebrow {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- padding: 6px 10px;
- border-radius: 999px;
- background: rgba(15,118,110,.10);
- color: var(--accent-deep);
- font-size: 12px;
- font-weight: 700;
- letter-spacing: .04em;
- text-transform: uppercase;
- margin-bottom: 14px;
- }
- h1 { margin: 0 0 10px; font-size: 34px; line-height: 1.05; }
- p { margin: 0 0 16px; line-height: 1.6; color: var(--muted); }
- .status {
- background: var(--warn-bg);
- border: 1px solid var(--warn-line);
- border-radius: 12px;
- color: var(--warn-text);
- padding: 14px 16px;
- margin: 20px 0;
- font-size: 14px;
- line-height: 1.5;
- }
- .meta {
- background: rgba(255,255,255,.78);
- border: 1px solid var(--line);
- border-radius: 12px;
- padding: 14px 16px;
- margin: 20px 0;
- }
- .meta strong {
- display: block;
- margin-bottom: 6px;
- color: var(--text);
- font-size: 12px;
- letter-spacing: .03em;
- text-transform: uppercase;
- }
- .cta {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- border: 0;
- border-radius: 12px;
- background: var(--accent);
- color: #fff;
- font-size: 16px;
- font-weight: 700;
- padding: 13px 18px;
- text-decoration: none;
- }
- .cta:hover { background: var(--accent-deep); }
- .fine { font-size: 12px; color: #64748b; margin-top: 14px; }
- </style>
-</head>
-<body>
- <div class="wrap">
- <div class="card">
- <div class="eyebrow">Pulse Pro Trial</div>
- <h1>{{.Title}}</h1>
- <p>{{.Message}}</p>
-
- <div class="status">{{.StatusMessage}}</div>
-
- <div class="meta">
- <strong>Pulse instance</strong>
- <div>{{.ReturnTarget}}</div>
- </div>
-
- {{if .ActionURL}}<a class="cta" href="{{.ActionURL}}">{{.ActionLabel}}</a>{{end}}
- <p class="fine">{{.FinePrint}}</p>
- </div>
- </div>
-</body>
-</html>
-`))
-
-type TrialSignupHandlers struct {
- cfg *CPConfig
- emailSender cpemail.Sender
- verificationStore *TrialSignupStore
- entitlements *entitlements.Service
- createCheckoutSession func(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
- getCheckoutSession func(id string, params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error)
- now func() time.Time
-}
-
-type trialSignupPageData struct {
- OrgID string
- ReturnURL string
- InstanceToken string
- ReturnTarget string
- Name string
- Email string
- Company string
- ErrorMessage string
- Cancelled bool
- VerificationSent bool
- Verified bool
- VerifiedToken string
- Nonce string
-}
-
-type trialSignupSuccessData struct {
- ReturnTarget string
- Email string
- ActivateURL string
- Nonce string
-}
-
-type trialSignupFailureData struct {
- Title string
- Message string
- ReturnTarget string
- StatusMessage string
- ActionURL string
- ActionLabel string
- FinePrint string
- Nonce string
-}
-
-type trialSignupFailureKind string
-
-const (
- trialSignupFailureRetryable trialSignupFailureKind = "retryable"
- trialSignupFailureConflict trialSignupFailureKind = "conflict"
- trialSignupFailureInvalidLink trialSignupFailureKind = "invalid_link"
- trialSignupFailureUnavailable trialSignupFailureKind = "unavailable"
-)
-
-type trialSignupRedeemRequest struct {
- Token string `json:"token"`
-}
-
-type trialSignupRedeemResponse struct {
- EntitlementJWT string `json:"entitlement_jwt"`
- EntitlementRefreshToken string `json:"entitlement_refresh_token"`
-}
-
-func NewTrialSignupHandlers(cfg *CPConfig, emailSender cpemail.Sender, verificationStore *TrialSignupStore, entitlementService *entitlements.Service) *TrialSignupHandlers {
- return &TrialSignupHandlers{
- cfg: cfg,
- emailSender: emailSender,
- verificationStore: verificationStore,
- entitlements: entitlementService,
- createCheckoutSession: stripesession.New,
- getCheckoutSession: stripesession.Get,
- now: func() time.Time { return time.Now().UTC() },
- }
-}
-
-// HandleStartProTrial renders the hosted trial registration form.
-func (h *TrialSignupHandlers) HandleStartProTrial(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
- data := trialSignupPageData{
- OrgID: normalizeTrialOrgID(r.URL.Query().Get("org_id")),
- ReturnURL: strings.TrimSpace(r.URL.Query().Get("return_url")),
- InstanceToken: strings.TrimSpace(r.URL.Query().Get("instance_token")),
- Name: strings.TrimSpace(r.URL.Query().Get("name")),
- Email: strings.TrimSpace(r.URL.Query().Get("email")),
- Company: strings.TrimSpace(r.URL.Query().Get("company")),
- Cancelled: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("cancelled")), "1"),
- ReturnTarget: summarizeTrialReturnTarget(r.URL.Query().Get("return_url")),
- }
- if data.ReturnURL == "" {
- data.ErrorMessage = "Missing return_url. Please restart from Pulse Settings > Pro License."
- }
- if strings.TrimSpace(data.InstanceToken) == "" {
- data.ErrorMessage = "Missing trial initiation token. Please restart from Pulse Settings > Pro License."
- }
- h.renderTrialSignupPage(w, r, http.StatusOK, data)
-}
-
-// HandleRequestVerification emails a short-lived verification link before checkout.
-func (h *TrialSignupHandlers) HandleRequestVerification(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
- if err := r.ParseForm(); err != nil {
- http.Error(w, "Invalid form body", http.StatusBadRequest)
- return
- }
-
- data := trialSignupPageData{
- OrgID: normalizeTrialOrgID(r.FormValue("org_id")),
- ReturnURL: strings.TrimSpace(r.FormValue("return_url")),
- InstanceToken: strings.TrimSpace(r.FormValue("instance_token")),
- Name: strings.TrimSpace(r.FormValue("name")),
- Email: strings.TrimSpace(r.FormValue("email")),
- Company: strings.TrimSpace(r.FormValue("company")),
- ReturnTarget: summarizeTrialReturnTarget(r.FormValue("return_url")),
- }
- unavailable := func(status int, message string) {
- h.renderTrialSignupFailurePage(w, r, status, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureUnavailable,
- message,
- ))
- }
- if strings.TrimSpace(data.InstanceToken) == "" {
- data.ErrorMessage = "This trial request must be started from Pulse. Return to Pulse Settings > Pro License and try again."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if !isValidTrialReturnURL(data.ReturnURL) {
- data.ErrorMessage = "A valid Pulse return URL is required. Please restart from Pulse Settings > Pro License."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if strings.TrimSpace(data.Name) == "" {
- data.ErrorMessage = "Your name is required."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if !isValidTrialEmail(data.Email) {
- data.ErrorMessage = "A valid work email address is required."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if isPublicTrialSignupEmailDomain(normalizeTrialSignupEmailDomain(data.Email)) {
- data.ErrorMessage = "Use your work email to start a Pulse Pro trial. Consumer email addresses are not eligible."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if h.verificationStore != nil {
- pendingRecord, err := h.verificationStore.FindPendingVerificationByEmail(data.Email, h.now().UTC())
- if err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup pending verification lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
- return
- }
- if pendingRecord != nil {
- data.ErrorMessage = "A verification email was already sent recently. Check your inbox or wait for the current link to expire before requesting another one."
- h.renderTrialSignupPage(w, r, http.StatusTooManyRequests, data)
- return
- }
- conflict, err := h.verificationStore.FindIssuedTrialConflict(data.Email, data.Company)
- if err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup issuance lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
- return
- }
- if conflict != nil {
- h.renderTrialSignupFailurePage(w, r, http.StatusConflict, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureConflict,
- trialSignupIssuanceConflictMessage(conflict),
- ))
- return
- }
- }
- if h.emailSender == nil || h.cfg == nil || strings.TrimSpace(h.cfg.EmailFrom) == "" || h.verificationStore == nil {
- unavailable(http.StatusServiceUnavailable, "Email verification is not configured yet. Please contact support.")
- return
- }
-
- token, err := h.verificationStore.CreateVerification(&TrialSignupRecord{
- OrgID: data.OrgID,
- ReturnURL: data.ReturnURL,
- InstanceToken: data.InstanceToken,
- Name: data.Name,
- Email: data.Email,
- Company: data.Company,
- CreatedAt: h.now().UTC(),
- VerificationExpiresAt: h.now().UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup verification record creation failed")
- unavailable(http.StatusInternalServerError, "Unable to prepare the verification link. Please try again.")
- return
- }
-
- verifyURL := buildTrialSignupVerificationURL(h.cfg.BaseURL, token)
- if err := h.sendTrialVerificationEmail(data.Email, verifyURL); err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup verification email send failed")
- unavailable(http.StatusBadGateway, "Unable to send the verification email. Please try again.")
- return
- }
-
- data.VerificationSent = true
- h.renderTrialSignupPage(w, r, http.StatusOK, data)
-}
-
-// HandleVerifyEmail validates the verification token and shows the final checkout step.
-func (h *TrialSignupHandlers) HandleVerifyEmail(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- if token := strings.TrimSpace(r.URL.Query().Get("token")); token != "" {
- record, err := h.verificationStore.ConsumeVerification(token, h.now().UTC())
- if err != nil {
- log.Warn().Err(err).Msg("trial signup verification token invalid")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- ))
- return
- }
- verifiedToken, err := h.verificationStore.IssueCheckoutToken(record.ID, h.now().UTC(), trialSignupVerificationTTL)
- if err != nil {
- log.Error().Err(err).Str("request_id", record.ID).Msg("trial checkout token issuance failed")
- h.renderTrialSignupFailurePage(w, r, http.StatusInternalServerError, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: summarizeTrialReturnTarget(record.ReturnURL)},
- trialSignupFailureUnavailable,
- "Unable to continue to trial checkout. Please try again.",
- ))
- return
- }
- http.Redirect(w, r, buildTrialSignupVerifiedURL(h.cfg.BaseURL, verifiedToken, false), http.StatusSeeOther)
- return
- }
-
- verifiedToken := strings.TrimSpace(r.URL.Query().Get("verified"))
- record, err := h.lookupVerifiedTrialSignupRecord(verifiedToken)
- if err != nil {
- log.Warn().Err(err).Msg("trial signup verified state invalid")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- ))
- return
- }
-
- h.renderTrialSignupPage(w, r, http.StatusOK, trialSignupPageData{
- OrgID: record.OrgID,
- ReturnURL: record.ReturnURL,
- ReturnTarget: summarizeTrialReturnTarget(record.ReturnURL),
- Name: record.Name,
- Email: record.Email,
- Company: record.Company,
- Cancelled: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("cancelled")), "1"),
- Verified: true,
- VerifiedToken: verifiedToken,
- })
-}
-
-// HandleCheckout creates a Stripe Checkout Session for trial signup.
-func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
- if err := r.ParseForm(); err != nil {
- http.Error(w, "Invalid form body", http.StatusBadRequest)
- return
- }
-
- verifiedToken := strings.TrimSpace(r.FormValue("verified_token"))
- record := &TrialSignupRecord{}
- data := trialSignupPageData{}
- unavailable := func(status int, message string) {
- h.renderTrialSignupFailurePage(w, r, status, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureUnavailable,
- message,
- ))
- }
- if verifiedToken != "" {
- verifiedRecord, err := h.lookupVerifiedTrialSignupRecord(verifiedToken)
- if err != nil {
- log.Warn().Err(err).Msg("trial signup checkout requested without valid verified token")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That backup link is invalid or expired. Return to Pulse to create a fresh secure trial session.",
- ))
- return
- }
- record = verifiedRecord
- data = trialSignupPageData{
- OrgID: record.OrgID,
- ReturnURL: record.ReturnURL,
- InstanceToken: record.InstanceToken,
- ReturnTarget: summarizeTrialReturnTarget(record.ReturnURL),
- Name: record.Name,
- Email: record.Email,
- Company: record.Company,
- Verified: true,
- VerifiedToken: verifiedToken,
- }
- } else {
- data = trialSignupPageData{
- OrgID: normalizeTrialOrgID(r.FormValue("org_id")),
- ReturnURL: strings.TrimSpace(r.FormValue("return_url")),
- InstanceToken: strings.TrimSpace(r.FormValue("instance_token")),
- Name: strings.TrimSpace(r.FormValue("name")),
- Email: strings.TrimSpace(r.FormValue("email")),
- Company: strings.TrimSpace(r.FormValue("company")),
- ReturnTarget: summarizeTrialReturnTarget(r.FormValue("return_url")),
- }
- if strings.TrimSpace(data.InstanceToken) == "" {
- data.ErrorMessage = "This checkout must be started from Pulse. Return to Pulse Settings > Pro License and try again."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if !isValidTrialReturnURL(data.ReturnURL) {
- data.ErrorMessage = "A valid Pulse return URL is required. Please restart from Pulse Settings > Pro License."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if strings.TrimSpace(data.Name) == "" {
- data.ErrorMessage = "Your name is required."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if !isValidTrialEmail(data.Email) {
- data.ErrorMessage = "A valid work email address is required."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if isPublicTrialSignupEmailDomain(normalizeTrialSignupEmailDomain(data.Email)) {
- data.ErrorMessage = "Use your work email to start a Pulse Pro trial. Consumer email addresses are not eligible."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if h.verificationStore == nil {
- unavailable(http.StatusServiceUnavailable, "Trial checkout is unavailable right now. Please try again.")
- return
- }
- conflict, err := h.verificationStore.FindIssuedTrialConflict(data.Email, data.Company)
- if err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup issuance lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
- return
- }
- if conflict != nil {
- h.renderTrialSignupFailurePage(w, r, http.StatusConflict, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureConflict,
- trialSignupIssuanceConflictMessage(conflict),
- ))
- return
- }
- record = &TrialSignupRecord{
- OrgID: data.OrgID,
- ReturnURL: data.ReturnURL,
- InstanceToken: data.InstanceToken,
- Name: data.Name,
- Email: data.Email,
- Company: data.Company,
- CreatedAt: h.now().UTC(),
- }
- if err := h.verificationStore.CreateCheckoutRequest(record); err != nil {
- log.Error().Err(err).Str("email", data.Email).Msg("trial signup checkout request creation failed")
- unavailable(http.StatusInternalServerError, "Unable to prepare checkout. Please try again.")
- return
- }
- }
-
- if !isValidTrialReturnURL(data.ReturnURL) {
- data.ErrorMessage = "A valid Pulse return URL is required. Please restart from Pulse Settings > Pro License."
- h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
- return
- }
- if strings.TrimSpace(h.cfg.StripeAPIKey) == "" || strings.TrimSpace(h.cfg.TrialSignupPriceID) == "" {
- unavailable(http.StatusServiceUnavailable, "Checkout is not configured yet. Please contact support.")
- return
- }
-
- stripe.Key = strings.TrimSpace(h.cfg.StripeAPIKey)
- successURL := buildTrialSignupSuccessURL(h.cfg.BaseURL)
- cancelURL := buildTrialSignupCancelURL(h.cfg.BaseURL, data, verifiedToken)
-
- params := &stripe.CheckoutSessionParams{
- Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
- SuccessURL: stripe.String(successURL),
- CancelURL: stripe.String(cancelURL),
- CustomerEmail: stripe.String(data.Email),
- PaymentMethodCollection: stripe.String(string(stripe.CheckoutSessionPaymentMethodCollectionIfRequired)),
- LineItems: []*stripe.CheckoutSessionLineItemParams{
- {
- Price: stripe.String(strings.TrimSpace(h.cfg.TrialSignupPriceID)),
- Quantity: stripe.Int64(1),
- },
- },
- SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
- TrialPeriodDays: stripe.Int64(trialSignupTrialDays),
- TrialSettings: &stripe.CheckoutSessionSubscriptionDataTrialSettingsParams{
- EndBehavior: &stripe.CheckoutSessionSubscriptionDataTrialSettingsEndBehaviorParams{
- MissingPaymentMethod: stripe.String("cancel"),
- },
- },
- },
- Metadata: map[string]string{
- "org_id": data.OrgID,
- "return_url": data.ReturnURL,
- "instance_token": data.InstanceToken,
- "name": data.Name,
- "email": data.Email,
- "company": data.Company,
- "trial_request_id": record.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }
-
- session, err := h.createCheckoutSession(params)
- if err != nil || session == nil || strings.TrimSpace(session.URL) == "" {
- log.Error().Err(err).
- Str("org_id", data.OrgID).
- Str("email", data.Email).
- Msg("trial signup checkout session creation failed")
- unavailable(http.StatusBadGateway, "Unable to create checkout session. Please try again.")
- return
- }
- if err := h.verificationStore.MarkCheckoutStarted(record.ID, session.ID, h.now().UTC()); err != nil {
- log.Warn().Err(err).Str("request_id", record.ID).Msg("trial signup checkout start could not be recorded")
- }
-
- http.Redirect(w, r, session.URL, http.StatusSeeOther)
-}
-
-// HandleTrialSignupComplete validates the Stripe checkout session and renders
-// the hosted success page with the signed activation handoff back to Pulse.
-func (h *TrialSignupHandlers) HandleTrialSignupComplete(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- fail := func(status int, kind trialSignupFailureKind, data trialSignupPageData, message string) {
- h.renderTrialSignupFailurePage(w, r, status, trialSignupFailureDataForPage(h.cfg, data, kind, message))
- }
-
- sessionID := strings.TrimSpace(r.URL.Query().Get("session_id"))
- if sessionID == "" {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, trialSignupPageData{}, "This secure trial session is missing its completion token.")
- return
- }
- if strings.TrimSpace(h.cfg.StripeAPIKey) == "" {
- fail(http.StatusServiceUnavailable, trialSignupFailureUnavailable, trialSignupPageData{}, "Secure trial setup is unavailable right now.")
- return
- }
-
- stripe.Key = strings.TrimSpace(h.cfg.StripeAPIKey)
- session, err := h.getCheckoutSession(sessionID, nil)
- if err != nil || session == nil {
- log.Warn().Err(err).Str("session_id", sessionID).Msg("trial signup checkout session lookup failed")
- fail(http.StatusBadRequest, trialSignupFailureRetryable, trialSignupPageData{}, "This secure trial session could not be confirmed.")
- return
- }
- data := trialSignupPageData{
- OrgID: normalizeTrialOrgID(session.Metadata["org_id"]),
- ReturnURL: strings.TrimSpace(session.Metadata["return_url"]),
- ReturnTarget: summarizeTrialReturnTarget(session.Metadata["return_url"]),
- }
- if session.Status != stripe.CheckoutSessionStatusComplete {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial session has not completed yet.")
- return
- }
- if session.Mode != stripe.CheckoutSessionModeSubscription {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial session is not valid for a Pulse Pro trial.")
- return
- }
- if strings.TrimSpace(session.Metadata["signup_source"]) != "pulse_pro_trial" {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial session is not valid for a Pulse Pro trial.")
- return
- }
-
- returnURL := strings.TrimSpace(session.Metadata["return_url"])
- if !isValidTrialReturnURL(returnURL) {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This trial return target is no longer valid.")
- return
- }
- instanceHost, err := trialSignupReturnURLHost(returnURL)
- if err != nil {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This trial return target is no longer valid.")
- return
- }
-
- orgID := normalizeTrialOrgID(session.Metadata["org_id"])
- email := strings.TrimSpace(session.Metadata["email"])
- if strings.TrimSpace(email) == "" {
- email = strings.TrimSpace(session.CustomerEmail)
- }
- if session.CustomerDetails != nil && strings.TrimSpace(session.CustomerDetails.Email) != "" {
- email = strings.TrimSpace(session.CustomerDetails.Email)
- }
-
- now := h.now().UTC()
- requestID := strings.TrimSpace(session.Metadata["trial_request_id"])
- if requestID == "" {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial session is missing its request binding.")
- return
- }
- if h.verificationStore == nil {
- fail(http.StatusServiceUnavailable, trialSignupFailureUnavailable, data, "Secure trial setup is unavailable right now.")
- return
- }
- record, err := h.verificationStore.GetRecord(requestID)
- if err != nil {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request could not be confirmed.")
- return
- }
- data.InstanceToken = record.InstanceToken
- data.Name = record.Name
- data.Email = record.Email
- data.Company = record.Company
- if record.VerifiedAt.IsZero() {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request could not be confirmed.")
- return
- }
- if strings.TrimSpace(record.OrgID) != orgID {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request does not match the originating workspace.")
- return
- }
- if strings.TrimSpace(record.ReturnURL) != returnURL {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request does not match the originating Pulse instance.")
- return
- }
- if strings.TrimSpace(record.InstanceToken) == "" {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request is missing its Pulse initiation binding.")
- return
- }
- if verifiedEmail := normalizeTrialSignupEmail(record.Email); verifiedEmail == "" || normalizeTrialSignupEmail(email) != verifiedEmail {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request does not match the verified recovery contact.")
- return
- }
- if existingSessionID := strings.TrimSpace(record.CheckoutSessionID); existingSessionID != "" && existingSessionID != sessionID {
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request does not match the checkout session that was already started.")
- return
- }
- if err := h.verificationStore.MarkCheckoutCompleted(requestID, sessionID, now); err != nil {
- switch {
- case errors.Is(err, ErrTrialSignupRecordNotFound):
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request could not be confirmed.")
- default:
- log.Error().Err(err).Str("request_id", requestID).Str("session_id", sessionID).Msg("failed to record checkout completion")
- fail(http.StatusInternalServerError, trialSignupFailureUnavailable, data, "Pulse could not finish recording this secure trial checkout.")
- }
- return
- }
- if err := h.verificationStore.MarkTrialIssued(requestID, now); err != nil {
- switch {
- case errors.Is(err, ErrTrialSignupEmailAlreadyUsed):
- fail(http.StatusConflict, trialSignupFailureConflict, data, "This recovery email has already used a Pulse Pro trial.")
- case errors.Is(err, ErrTrialSignupOrganizationUsed):
- fail(http.StatusConflict, trialSignupFailureConflict, data, "This organization has already used a Pulse Pro trial.")
- case errors.Is(err, ErrTrialSignupRecordNotFound), errors.Is(err, ErrTrialSignupVerificationInvalid):
- fail(http.StatusBadRequest, trialSignupFailureRetryable, data, "This secure trial request could not be confirmed.")
- default:
- log.Error().Err(err).Str("request_id", requestID).Msg("failed to record trial issuance")
- fail(http.StatusInternalServerError, trialSignupFailureUnavailable, data, "Pulse could not finalize this trial issuance.")
- }
- return
- }
- if h.entitlements == nil {
- fail(http.StatusServiceUnavailable, trialSignupFailureUnavailable, data, "Secure trial activation is unavailable right now.")
- return
- }
- token, err := h.entitlements.IssueTrialActivation(entitlements.TrialActivationInput{
- RequestID: requestID,
- OrgID: orgID,
- Email: email,
- ReturnURL: returnURL,
- InstanceToken: record.InstanceToken,
- InstanceHost: instanceHost,
- CheckoutSessionID: sessionID,
- TrialStartedAt: now,
- IssuedAt: now,
- TTL: trialSignupActivationTokenTTL,
- })
- if err != nil {
- log.Error().Err(err).Str("request_id", requestID).Str("session_id", sessionID).Msg("failed to persist trial activation token")
- fail(http.StatusInternalServerError, trialSignupFailureUnavailable, data, "Pulse could not prepare the activation handoff for this trial.")
- return
- }
-
- finalReturnURL, err := appendQueryParams(returnURL, map[string]string{
- "token": token,
- })
- if err != nil {
- log.Error().Err(err).Str("return_url", returnURL).Msg("failed to build trial activation redirect URL")
- fail(http.StatusInternalServerError, trialSignupFailureUnavailable, data, "Pulse could not prepare the return link back to your instance.")
- return
- }
- h.renderTrialSignupSuccessPage(w, r, http.StatusOK, trialSignupSuccessData{
- ReturnTarget: summarizeTrialReturnTarget(returnURL),
- Email: email,
- ActivateURL: finalReturnURL,
- })
-}
-
-func (h *TrialSignupHandlers) HandleTrialSignupRedeem(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
- if h.verificationStore == nil {
- http.Error(w, "trial signup store not configured", http.StatusServiceUnavailable)
- return
- }
- if h.entitlements == nil {
- http.Error(w, "hosted entitlement service unavailable", http.StatusServiceUnavailable)
- return
- }
-
- var reqBody trialSignupRedeemRequest
- if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
- http.Error(w, "invalid request body", http.StatusBadRequest)
- return
- }
- token := strings.TrimSpace(reqBody.Token)
- if token == "" {
- http.Error(w, "token is required", http.StatusBadRequest)
- return
- }
-
- privateKey, err := pkglicensing.DecodeEd25519PrivateKey(strings.TrimSpace(h.cfg.TrialActivationPrivateKey))
- if err != nil {
- log.Error().Err(err).Msg("trial activation private key invalid")
- http.Error(w, "trial activation verifier unavailable", http.StatusServiceUnavailable)
- return
- }
- publicKey, ok := privateKey.Public().(ed25519.PublicKey)
- if !ok || len(publicKey) != ed25519.PublicKeySize {
- http.Error(w, "trial activation verifier unavailable", http.StatusServiceUnavailable)
- return
- }
-
- now := h.now().UTC()
- claims, err := pkglicensing.VerifyTrialActivationToken(token, publicKey, "", now)
- if err != nil {
- switch {
- case errors.Is(err, pkglicensing.ErrTrialActivationHostMismatch):
- http.Error(w, "activation token host mismatch", http.StatusBadRequest)
- case errors.Is(err, pkglicensing.ErrTrialActivationReturnURLMissing), errors.Is(err, pkglicensing.ErrTrialActivationReturnURLInvalid):
- http.Error(w, "invalid return url", http.StatusBadRequest)
- default:
- http.Error(w, "invalid activation token", http.StatusBadRequest)
- }
- return
- }
- if _, err := trialSignupReturnURLHost(claims.ReturnURL); err != nil {
- http.Error(w, "invalid return url host", http.StatusBadRequest)
- return
- }
- if strings.TrimSpace(claims.InstanceToken) == "" {
- http.Error(w, "activation token missing initiation token", http.StatusBadRequest)
- return
- }
-
- entitlement, err := h.entitlements.ResolveTrialActivation(token, claims.InstanceHost)
- if err != nil {
- switch {
- case errors.Is(err, entitlements.ErrHostedEntitlementNotFound), errors.Is(err, entitlements.ErrHostedEntitlementTargetMismatch), errors.Is(err, entitlements.ErrHostedEntitlementInactive), errors.Is(err, entitlements.ErrHostedEntitlementInvalid):
- http.Error(w, "invalid trial redemption", http.StatusBadRequest)
- default:
- log.Error().Err(err).Str("org_id", claims.OrgID).Msg("failed to resolve hosted trial activation")
- http.Error(w, "failed to load trial redemption", http.StatusInternalServerError)
- }
- return
- }
- if err := h.verificationStore.MarkRedemptionRecorded(entitlement.TrialRequestID, claims.OrgID, claims.ReturnURL, claims.InstanceToken, claims.InstanceHost, now); err != nil {
- switch {
- case errors.Is(err, ErrTrialSignupRecordNotFound):
- http.Error(w, "invalid trial redemption", http.StatusBadRequest)
- default:
- log.Error().Err(err).Str("org_id", claims.OrgID).Msg("failed to record hosted trial redemption")
- http.Error(w, "failed to record trial redemption", http.StatusInternalServerError)
- }
- return
- }
- record, err := h.verificationStore.GetRecord(entitlement.TrialRequestID)
- if err != nil {
- switch {
- case errors.Is(err, ErrTrialSignupRecordNotFound):
- http.Error(w, "invalid trial redemption", http.StatusBadRequest)
- default:
- log.Error().Err(err).Str("org_id", claims.OrgID).Msg("failed to load hosted trial redemption record")
- http.Error(w, "failed to load trial redemption", http.StatusInternalServerError)
- }
- return
- }
- trialStartedAt := now
- if !record.CheckoutCompletedAt.IsZero() {
- trialStartedAt = record.CheckoutCompletedAt.UTC()
- }
- redemption, err := h.entitlements.RedeemTrialEntitlement(entitlements.TrialEntitlementInput{
- RequestID: entitlement.TrialRequestID,
- OrgID: claims.OrgID,
- Email: record.Email,
- ReturnURL: claims.ReturnURL,
- InstanceToken: record.InstanceToken,
- InstanceHost: claims.InstanceHost,
- TrialStartedAt: trialStartedAt,
- IssuedAt: now,
- RedeemedAt: now,
- })
- if err != nil {
- log.Error().Err(err).Str("org_id", claims.OrgID).Msg("failed to redeem hosted trial entitlement")
- http.Error(w, "failed to generate entitlement lease", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(trialSignupRedeemResponse{
- EntitlementJWT: redemption.EntitlementJWT,
- EntitlementRefreshToken: redemption.EntitlementRefreshToken,
- }); err != nil {
- log.Error().Err(err).Str("org_id", claims.OrgID).Msg("failed to encode hosted trial redemption response")
- }
-}
-
-func (h *TrialSignupHandlers) renderTrialSignupPage(w http.ResponseWriter, r *http.Request, status int, data trialSignupPageData) {
- data.Nonce = cpsec.NonceFromContext(r.Context())
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
- if err := trialSignupPageTemplate.Execute(w, data); err != nil {
- log.Error().Err(err).Msg("trial signup page render failed")
- }
-}
-
-func (h *TrialSignupHandlers) renderTrialSignupSuccessPage(w http.ResponseWriter, r *http.Request, status int, data trialSignupSuccessData) {
- data.Nonce = cpsec.NonceFromContext(r.Context())
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
- if err := trialSignupSuccessTemplate.Execute(w, data); err != nil {
- log.Error().Err(err).Msg("trial signup success page render failed")
- }
-}
-
-func (h *TrialSignupHandlers) HandleRateLimitedTrialSignup(w http.ResponseWriter, r *http.Request, retryAfter int) {
- data := h.trialSignupPageDataFromRequest(r)
- data.ErrorMessage = trialSignupRateLimitMessage(retryAfter)
- h.renderTrialSignupPage(w, r, http.StatusTooManyRequests, data)
-}
-
-func (h *TrialSignupHandlers) trialSignupPageDataFromRequest(r *http.Request) trialSignupPageData {
- data := trialSignupPageData{
- OrgID: trialSignupDefaultOrgID,
- ReturnTarget: "your Pulse instance",
- Cancelled: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("cancelled")), "1"),
- VerifiedToken: strings.TrimSpace(r.URL.Query().Get("verified")),
- }
-
- switch r.Method {
- case http.MethodGet:
- q := r.URL.Query()
- data.OrgID = normalizeTrialOrgID(q.Get("org_id"))
- data.ReturnURL = strings.TrimSpace(q.Get("return_url"))
- data.InstanceToken = strings.TrimSpace(q.Get("instance_token"))
- data.Name = strings.TrimSpace(q.Get("name"))
- data.Email = strings.TrimSpace(q.Get("email"))
- data.Company = strings.TrimSpace(q.Get("company"))
- default:
- if err := r.ParseForm(); err == nil {
- data.OrgID = normalizeTrialOrgID(r.FormValue("org_id"))
- data.ReturnURL = strings.TrimSpace(r.FormValue("return_url"))
- data.InstanceToken = strings.TrimSpace(r.FormValue("instance_token"))
- data.Name = strings.TrimSpace(r.FormValue("name"))
- data.Email = strings.TrimSpace(r.FormValue("email"))
- data.Company = strings.TrimSpace(r.FormValue("company"))
- if verifiedToken := strings.TrimSpace(r.FormValue("verified_token")); verifiedToken != "" {
- data.VerifiedToken = verifiedToken
- }
- }
- }
-
- if data.ReturnURL != "" {
- data.ReturnTarget = summarizeTrialReturnTarget(data.ReturnURL)
- }
- if data.VerifiedToken == "" {
- return data
- }
-
- record, err := h.lookupVerifiedTrialSignupRecord(data.VerifiedToken)
- if err != nil || record == nil {
- return data
- }
-
- data.OrgID = record.OrgID
- data.ReturnURL = record.ReturnURL
- data.InstanceToken = record.InstanceToken
- data.ReturnTarget = summarizeTrialReturnTarget(record.ReturnURL)
- data.Name = record.Name
- data.Email = record.Email
- data.Company = record.Company
- data.Verified = true
- return data
-}
-
-func (h *TrialSignupHandlers) renderTrialSignupFailurePage(w http.ResponseWriter, r *http.Request, status int, data trialSignupFailureData) {
- data.Nonce = cpsec.NonceFromContext(r.Context())
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
- if err := trialSignupFailureTemplate.Execute(w, data); err != nil {
- log.Error().Err(err).Msg("trial signup failure page render failed")
- }
-}
-
-func trialSignupRateLimitMessage(retryAfter int) string {
- return "Too many trial setup attempts from this browser. " + humanizeTrialSignupRetryAfter(retryAfter) + "."
-}
-
-func humanizeTrialSignupRetryAfter(retryAfter int) string {
- if retryAfter <= 0 {
- return "Try again later"
- }
- if retryAfter < 90 {
- return "Try again in about a minute"
- }
- if retryAfter < 3600 {
- minutes := int((time.Duration(retryAfter)*time.Second + time.Minute - 1) / time.Minute)
- return "Try again in about " + strconv.Itoa(minutes) + " minutes"
- }
- hours := int((time.Duration(retryAfter)*time.Second + time.Hour - 1) / time.Hour)
- if hours == 1 {
- return "Try again in about 1 hour"
- }
- return "Try again in about " + strconv.Itoa(hours) + " hours"
-}
-
-func (h *TrialSignupHandlers) lookupVerifiedTrialSignupRecord(verifiedToken string) (*TrialSignupRecord, error) {
- if h.verificationStore == nil {
- return nil, ErrTrialSignupRecordNotFound
- }
- record, err := h.verificationStore.GetRecordByCheckoutToken(verifiedToken, h.now().UTC())
- if err != nil {
- return nil, err
- }
- if record.VerifiedAt.IsZero() {
- return nil, ErrTrialSignupVerificationInvalid
- }
- return record, nil
-}
-
-func (h *TrialSignupHandlers) sendTrialVerificationEmail(email, verifyURL string) error {
- htmlBody, textBody, err := cpemail.RenderTrialVerificationEmail(cpemail.TrialVerificationData{
- VerifyURL: verifyURL,
- })
- if err != nil {
- return err
- }
- return h.emailSender.Send(context.Background(), cpemail.Message{
- From: strings.TrimSpace(h.cfg.EmailFrom),
- To: email,
- Subject: "Verify your Pulse Pro trial request",
- HTML: htmlBody,
- Text: textBody,
- })
-}
-
-func isValidTrialEmail(email string) bool {
- email = strings.TrimSpace(email)
- if email == "" {
- return false
- }
- parsed, err := mail.ParseAddress(email)
- if err != nil {
- return false
- }
- return strings.TrimSpace(parsed.Address) != ""
-}
-
-func isValidTrialReturnURL(raw string) bool {
- _, err := pkglicensing.ValidateTrialActivationReturnURL(raw, "")
- return err == nil
-}
-
-func normalizeTrialOrgID(raw string) string {
- orgID := strings.TrimSpace(raw)
- if orgID == "" {
- return trialSignupDefaultOrgID
- }
- return orgID
-}
-
-func trialSignupFailureDataForPage(cfg *CPConfig, data trialSignupPageData, kind trialSignupFailureKind, message string) trialSignupFailureData {
- title := "Trial setup could not be completed"
- statusMessage := "Return to Pulse and start the secure trial handoff again if you still want to activate Pro on this instance."
- finePrint := "Pulse could not complete this secure trial handoff."
-
- switch kind {
- case trialSignupFailureConflict:
- title = "Trial already used"
- statusMessage = "This trial request cannot be restarted for the same recovery contact or organization."
- finePrint = "Upgrade the existing account or contact support if you need help reconciling prior trial usage."
- case trialSignupFailureInvalidLink:
- title = "Backup link expired"
- statusMessage = "This backup link can no longer continue the hosted trial handoff."
- finePrint = "Return to Pulse to request a fresh backup email or restart the secure trial setup."
- case trialSignupFailureUnavailable:
- title = "Trial setup is unavailable"
- statusMessage = "Pulse could not finish the secure trial handoff right now."
- finePrint = "Return to Pulse and try again later."
- }
-
- page := trialSignupFailureData{
- Title: title,
- Message: strings.TrimSpace(message),
- ReturnTarget: strings.TrimSpace(data.ReturnTarget),
- StatusMessage: statusMessage,
- FinePrint: finePrint,
- }
- if page.Message == "" {
- page.Message = "Pulse could not complete this secure trial handoff."
- }
- if page.ReturnTarget == "" {
- page.ReturnTarget = "your Pulse instance"
- }
- if kind != trialSignupFailureRetryable {
- return page
- }
- if strings.TrimSpace(data.ReturnURL) == "" || strings.TrimSpace(data.InstanceToken) == "" {
- return page
- }
- baseURL := ""
- if cfg != nil {
- baseURL = cfg.BaseURL
- }
- page.ActionURL = buildTrialSignupStartURL(baseURL, data, false)
- page.ActionLabel = "Start Trial Again"
- return page
-}
-
-func trialSignupIssuanceConflictMessage(conflict *TrialSignupIssuanceConflict) string {
- switch {
- case conflict == nil:
- return "This Pulse Pro trial request conflicts with a previous trial issuance. Upgrade the existing account or contact support if you need help."
- case conflict.Kind == trialSignupConflictEmail:
- return "This recovery email has already used a Pulse Pro trial. Upgrade the existing account or contact support if you need help."
- default:
- return "This organization has already used a Pulse Pro trial. Upgrade the existing account or contact support if you need help."
- }
-}
-
-func buildCPURL(baseURL, path string, query url.Values) string {
- base := strings.TrimSpace(baseURL)
- if base == "" {
- return path
- }
- parsed, err := url.Parse(base)
- if err != nil {
- return path
- }
- parsed.Path = strings.TrimRight(parsed.Path, "/") + path
- parsed.RawQuery = query.Encode()
- return parsed.String()
-}
-
-func buildTrialSignupSuccessURL(baseURL string) string {
- parsed, err := url.Parse(strings.TrimSpace(baseURL))
- if err != nil || parsed == nil {
- return "/trial-signup/complete?session_id=" + stripeCheckoutSessionIDPlaceholder
- }
- parsed.Path = strings.TrimRight(parsed.Path, "/") + "/trial-signup/complete"
- encoded := url.Values{
- "session_id": {stripeCheckoutSessionIDPlaceholder},
- }.Encode()
- parsed.RawQuery = strings.ReplaceAll(
- encoded,
- url.QueryEscape(stripeCheckoutSessionIDPlaceholder),
- stripeCheckoutSessionIDPlaceholder,
- )
- return parsed.String()
-}
-
-func buildTrialSignupVerificationURL(baseURL, token string) string {
- query := url.Values{}
- if strings.TrimSpace(token) != "" {
- query.Set("token", strings.TrimSpace(token))
- }
- return buildCPURL(baseURL, "/trial-signup/verify", query)
-}
-
-func buildTrialSignupStartURL(baseURL string, data trialSignupPageData, cancelled bool) string {
- query := url.Values{
- "org_id": {data.OrgID},
- "return_url": {data.ReturnURL},
- "instance_token": {data.InstanceToken},
- "name": {data.Name},
- "email": {data.Email},
- "company": {data.Company},
- }
- if cancelled {
- query.Set("cancelled", "1")
- }
- return buildCPURL(baseURL, "/start-pro-trial", query)
-}
-
-func buildTrialSignupVerifiedURL(baseURL, verifiedToken string, cancelled bool) string {
- query := url.Values{}
- if strings.TrimSpace(verifiedToken) != "" {
- query.Set("verified", strings.TrimSpace(verifiedToken))
- }
- if cancelled {
- query.Set("cancelled", "1")
- }
- return buildCPURL(baseURL, "/trial-signup/verify", query)
-}
-
-func buildTrialSignupCancelURL(baseURL string, data trialSignupPageData, verifiedToken string) string {
- if strings.TrimSpace(verifiedToken) != "" {
- return buildTrialSignupVerifiedURL(baseURL, verifiedToken, true)
- }
- return buildTrialSignupStartURL(baseURL, data, true)
-}
-
-func summarizeTrialReturnTarget(raw string) string {
- parsed, err := url.Parse(strings.TrimSpace(raw))
- if err != nil || parsed == nil {
- return "your Pulse instance"
- }
- if host := strings.TrimSpace(parsed.Host); host != "" {
- return host
- }
- return "your Pulse instance"
-}
-
-func appendQueryParams(base string, params map[string]string) (string, error) {
- parsed, err := url.Parse(strings.TrimSpace(base))
- if err != nil {
- return "", err
- }
- query := parsed.Query()
- for key, value := range params {
- key = strings.TrimSpace(key)
- if key == "" {
- continue
- }
- query.Set(key, value)
- }
- parsed.RawQuery = query.Encode()
- return parsed.String(), nil
-}
diff --git a/internal/cloudcp/trial_signup_handlers_test.go b/internal/cloudcp/trial_signup_handlers_test.go
deleted file mode 100644
index 1d3ae10117..0000000000
--- a/internal/cloudcp/trial_signup_handlers_test.go
+++ /dev/null
@@ -1,1610 +0,0 @@
-package cloudcp
-
-import (
- "crypto/ed25519"
- "encoding/base64"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "net/url"
- "strings"
- "testing"
- "time"
-
- "github.com/golang-jwt/jwt/v5"
- "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/entitlements"
- "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- stripe "github.com/stripe/stripe-go/v82"
-)
-
-func TestTrialSignupHandleStartProTrialRendersCheckoutForm(t *testing.T) {
- h := NewTrialSignupHandlers(&CPConfig{}, nil, nil, nil)
- req := httptest.NewRequest(http.MethodGet, "/start-pro-trial?org_id=default&return_url=https://pulse.example.com:7655/auth/trial-activate&instance_token=tsi_test", nil)
- rec := httptest.NewRecorder()
-
- h.HandleStartProTrial(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d", rec.Code, http.StatusOK)
- }
- body := rec.Body.String()
- if !strings.Contains(body, "Continue To Secure Trial Setup") {
- t.Fatalf("expected checkout CTA in response body")
- }
- if !strings.Contains(body, "pulse.example.com:7655") {
- t.Fatalf("expected instance host in response body")
- }
- if strings.Contains(body, "Activation Return URL") {
- t.Fatalf("raw activation callback should not be shown")
- }
-}
-
-func TestTrialSignupHandleRateLimitedTrialSignupPreservesVerifiedCheckoutState(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
-
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(url.Values{
- "verified_token": {verifiedToken},
- }.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRateLimitedTrialSignup(rec, req, 120)
-
- if rec.Code != http.StatusTooManyRequests {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusTooManyRequests, rec.Body.String())
- }
- body := rec.Body.String()
- if !strings.Contains(body, "Too many trial setup attempts from this browser. Try again in about 2 minutes.") {
- t.Fatalf("expected rate-limit guidance, got %q", body)
- }
- if !strings.Contains(body, "Backup link confirmed") {
- t.Fatalf("expected verified state to be preserved, got %q", body)
- }
- if !strings.Contains(body, "[email protected]") {
- t.Fatalf("expected verified email in response body")
- }
-}
-
-func TestTrialSignupHandleRequestVerificationSendsEmail(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
- }
- if sender.calls != 1 {
- t.Fatalf("email sender calls=%d, want 1", sender.calls)
- }
- if !strings.Contains(rec.Body.String(), "A backup link was sent to [email protected]") {
- t.Fatalf("expected verification sent message")
- }
- if !strings.Contains(sender.msg.Text, "/trial-signup/verify?token=") {
- t.Fatalf("expected verification email to contain verify URL")
- }
-}
-
-func TestTrialSignupHandleRequestVerificationRejectsConsumerEmailDomain(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- if sender.calls != 0 {
- t.Fatalf("email sender calls=%d, want 0", sender.calls)
- }
- if !strings.Contains(rec.Body.String(), "Consumer email addresses are not eligible") {
- t.Fatalf("expected consumer email rejection message, got %q", rec.Body.String())
- }
-}
-
-func TestTrialSignupHandleRequestVerificationRejectsPendingVerificationResend(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
-
- firstReq := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- firstReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- firstRec := httptest.NewRecorder()
- h.HandleRequestVerification(firstRec, firstReq)
- if firstRec.Code != http.StatusOK {
- t.Fatalf("first status=%d, want %d body=%q", firstRec.Code, http.StatusOK, firstRec.Body.String())
- }
-
- secondReq := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- secondReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- secondRec := httptest.NewRecorder()
- h.HandleRequestVerification(secondRec, secondReq)
-
- if secondRec.Code != http.StatusTooManyRequests {
- t.Fatalf("second status=%d, want %d body=%q", secondRec.Code, http.StatusTooManyRequests, secondRec.Body.String())
- }
- if sender.calls != 1 {
- t.Fatalf("email sender calls=%d, want 1", sender.calls)
- }
- if !strings.Contains(secondRec.Body.String(), "verification email was already sent recently") {
- t.Fatalf("expected pending verification message, got %q", secondRec.Body.String())
- }
-}
-
-func TestTrialSignupHandleRequestVerificationReturnsUnavailableOutcomeWhenEmailVerificationNotConfigured(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
- h.emailSender = nil
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
-
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup is unavailable",
- "Email verification is not configured yet. Please contact support.",
- "pulse.example.com",
- "Pulse could not finish the secure trial handoff right now.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleRequestVerificationRejectsEmailThatAlreadyUsedTrial(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
- recordID := parseVerifiedTokenRequestID(t, h, verifiedToken)
- if err := store.MarkTrialIssued(recordID, h.now().UTC()); err != nil {
- t.Fatalf("MarkTrialIssued: %v", err)
- }
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
-
- if rec.Code != http.StatusConflict {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This recovery email has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleRequestVerificationRejectsCorporateDomainReuse(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
-
- firstForm := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Alice Admin"},
- "email": {"[email protected]"},
- "company": {"Acme Inc."},
- }
- firstReq := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(firstForm.Encode()))
- firstReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- firstRec := httptest.NewRecorder()
- h.HandleRequestVerification(firstRec, firstReq)
- if firstRec.Code != http.StatusOK {
- t.Fatalf("first status=%d, want %d body=%q", firstRec.Code, http.StatusOK, firstRec.Body.String())
- }
- firstRawToken := extractQueryValueFromTextURL(t, sender.msg.Text, "token")
- firstVerifiedToken := verifyTrialRequest(t, h, firstRawToken)
- firstRequestID := parseVerifiedTokenRequestID(t, h, firstVerifiedToken)
- if err := store.MarkTrialIssued(firstRequestID, h.now().UTC()); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
-
- secondForm := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Bob Builder"},
- "email": {"[email protected]"},
- "company": {"Acme Holdings"},
- }
- secondReq := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(secondForm.Encode()))
- secondReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- secondRec := httptest.NewRecorder()
- h.HandleRequestVerification(secondRec, secondReq)
-
- if secondRec.Code != http.StatusConflict {
- t.Fatalf("status=%d, want %d body=%q", secondRec.Code, http.StatusConflict, secondRec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, secondRec.Body.String(),
- "Trial already used",
- "This organization has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, secondRec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleVerifyEmailConsumesSingleUseToken(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- rawToken := requestTrialVerification(t, h, sender)
-
- firstReq := httptest.NewRequest(http.MethodGet, "/trial-signup/verify?token="+url.QueryEscape(rawToken), nil)
- firstRec := httptest.NewRecorder()
- h.HandleVerifyEmail(firstRec, firstReq)
- if firstRec.Code != http.StatusSeeOther {
- t.Fatalf("first verify status=%d, want %d body=%q", firstRec.Code, http.StatusSeeOther, firstRec.Body.String())
- }
- location := firstRec.Header().Get("Location")
- if !strings.Contains(location, "/trial-signup/verify?verified=") {
- t.Fatalf("location=%q, want verified redirect", location)
- }
-
- secondReq := httptest.NewRequest(http.MethodGet, "/trial-signup/verify?token="+url.QueryEscape(rawToken), nil)
- secondRec := httptest.NewRecorder()
- h.HandleVerifyEmail(secondRec, secondReq)
- if secondRec.Code != http.StatusBadRequest {
- t.Fatalf("second verify status=%d, want %d body=%q", secondRec.Code, http.StatusBadRequest, secondRec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, secondRec.Body.String(),
- "Backup link expired",
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- "your Pulse instance",
- "This backup link can no longer continue the hosted trial handoff.",
- )
- assertTrialSignupFailurePageOmits(t, secondRec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleVerifyEmailRendersVerifiedState(t *testing.T) {
- h, _, sender := newTrialSignupTestHandler(t)
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/verify?verified="+url.QueryEscape(verifiedToken), nil)
- rec := httptest.NewRecorder()
-
- h.HandleVerifyEmail(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
- }
- body := rec.Body.String()
- if !strings.Contains(body, "Backup link confirmed") || !strings.Contains(body, "Continue To Secure Trial Setup") {
- t.Fatalf("expected verified state in response body")
- }
-}
-
-func TestTrialSignupHandleCheckoutRejectsRequestWithoutPulseContext(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(url.Values{}.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- if !strings.Contains(rec.Body.String(), "must be started from Pulse") {
- t.Fatalf("expected Pulse context error, got %q", rec.Body.String())
- }
-}
-
-func TestTrialSignupHandleCheckoutRedirectsToStripe(t *testing.T) {
- h, store, _ := newTrialSignupTestHandler(t)
- capturedSuccessURL := ""
- capturedCancelURL := ""
- capturedRequestID := ""
- h.cfg.StripeAPIKey = "sk_test_123"
- h.cfg.TrialSignupPriceID = "price_test_123"
- h.createCheckoutSession = func(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- if params == nil {
- t.Fatal("expected params")
- }
- if got := strings.TrimSpace(params.Metadata["org_id"]); got != "default" {
- t.Fatalf("metadata org_id=%q, want %q", got, "default")
- }
- if got := strings.TrimSpace(params.Metadata["email_mode"]); got != "backup" {
- t.Fatalf("metadata email_mode=%q, want %q", got, "backup")
- }
- capturedRequestID = strings.TrimSpace(params.Metadata["trial_request_id"])
- if capturedRequestID == "" {
- t.Fatalf("expected trial_request_id metadata")
- }
- if got := strings.TrimSpace(params.Metadata["instance_token"]); got != "tsi_test" {
- t.Fatalf("metadata instance_token=%q, want %q", got, "tsi_test")
- }
- capturedSuccessURL = strings.TrimSpace(stripe.StringValue(params.SuccessURL))
- capturedCancelURL = strings.TrimSpace(stripe.StringValue(params.CancelURL))
- return &stripe.CheckoutSession{ID: "cs_test_new", URL: "https://checkout.stripe.com/c/pay/cs_test"}, nil
- }
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusSeeOther {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusSeeOther, rec.Body.String())
- }
- if loc := rec.Header().Get("Location"); loc != "https://checkout.stripe.com/c/pay/cs_test" {
- t.Fatalf("location=%q, want stripe checkout URL", loc)
- }
- if !strings.Contains(capturedSuccessURL, "session_id={CHECKOUT_SESSION_ID}") {
- t.Fatalf("success_url=%q, expected unescaped Stripe session placeholder", capturedSuccessURL)
- }
- if !strings.Contains(capturedCancelURL, "/start-pro-trial?") || !strings.Contains(capturedCancelURL, "cancelled=1") {
- t.Fatalf("cancel_url=%q, expected hosted start page return", capturedCancelURL)
- }
-
- record, err := store.GetRecord(capturedRequestID)
- if err != nil {
- t.Fatalf("GetRecord: %v", err)
- }
- if record.CheckoutStartedAt.IsZero() {
- t.Fatalf("expected checkout_started_at to be recorded")
- }
- if record.CheckoutSessionID != "cs_test_new" {
- t.Fatalf("checkout_session_id=%q, want %q", record.CheckoutSessionID, "cs_test_new")
- }
-}
-
-func TestTrialSignupHandleCheckoutReturnsUnavailableOutcomeWhenCheckoutNotConfigured(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup is unavailable",
- "Checkout is not configured yet. Please contact support.",
- "pulse.example.com",
- "Pulse could not finish the secure trial handoff right now.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleCheckoutCreatesFreshSessionWhenRecordAlreadyHasSession(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
- h.cfg.StripeAPIKey = "sk_test_123"
- h.cfg.TrialSignupPriceID = "price_test_123"
-
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
- recordID := parseVerifiedTokenRequestID(t, h, verifiedToken)
- if err := store.MarkCheckoutStarted(recordID, "cs_existing_open", h.now().UTC()); err != nil {
- t.Fatalf("MarkCheckoutStarted: %v", err)
- }
-
- createCalls := 0
- h.createCheckoutSession = func(params *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- createCalls++
- return &stripe.CheckoutSession{ID: "cs_fresh_new", URL: "https://checkout.stripe.com/c/pay/cs_fresh_new"}, nil
- }
-
- form := url.Values{"verified_token": {verifiedToken}}
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusSeeOther {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusSeeOther, rec.Body.String())
- }
- if loc := rec.Header().Get("Location"); loc != "https://checkout.stripe.com/c/pay/cs_fresh_new" {
- t.Fatalf("location=%q, want fresh checkout URL", loc)
- }
- if createCalls != 1 {
- t.Fatalf("createCheckoutSession calls=%d, want 1", createCalls)
- }
- updatedRecord, err := store.GetRecord(recordID)
- if err != nil {
- t.Fatalf("GetRecord(updated): %v", err)
- }
- if updatedRecord.CheckoutSessionID != "cs_fresh_new" {
- t.Fatalf("checkout_session_id=%q, want %q", updatedRecord.CheckoutSessionID, "cs_fresh_new")
- }
-}
-
-func TestTrialSignupHandleCheckoutRejectsEmailThatAlreadyUsedTrial(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
- requestID := parseVerifiedTokenRequestID(t, h, verifiedToken)
- if err := store.MarkTrialIssued(requestID, h.now().UTC()); err != nil {
- t.Fatalf("MarkTrialIssued: %v", err)
- }
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusConflict {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This recovery email has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleCheckoutRejectsInvalidVerifiedTokenAsOutcomePage(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
- form := url.Values{"verified_token": {"not_a_real_verified_token"}}
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Backup link expired",
- "That backup link is invalid or expired. Return to Pulse to create a fresh secure trial session.",
- "your Pulse instance",
- "This backup link can no longer continue the hosted trial handoff.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleCompleteRedirectsWithActivationToken(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: time.Unix(1710000000, 0).UTC(),
- VerificationExpiresAt: time.Unix(1710000000, 0).UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, time.Unix(1710000000, 0).UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
-
- h := NewTrialSignupHandlers(&CPConfig{
- StripeAPIKey: "sk_test_123",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, svc)
- h.now = func() time.Time { return time.Unix(1710000000, 0).UTC() }
- h.entitlements.SetNow(h.now)
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": record.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_123", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
- }
- if !strings.Contains(rec.Body.String(), "Trial entitlement ready") {
- t.Fatalf("expected success page body, got %q", rec.Body.String())
- }
-
- updatedRecord, err := store.GetRecord(record.ID)
- if err != nil {
- t.Fatalf("GetRecord(updated): %v", err)
- }
- entitlement, err := reg.GetHostedEntitlementByTrialRequestID(record.ID)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID: %v", err)
- }
- if entitlement == nil {
- t.Fatal("expected hosted entitlement record")
- }
- token := strings.TrimSpace(entitlement.ActivationToken)
- claims, err := pkglicensing.VerifyTrialActivationToken(token, pub, "pulse.example.com", h.now().UTC())
- if err != nil {
- t.Fatalf("VerifyTrialActivationToken: %v", err)
- }
- if claims.OrgID != "default" {
- t.Fatalf("claims.OrgID=%q, want %q", claims.OrgID, "default")
- }
- if claims.ReturnURL != "https://pulse.example.com/auth/trial-activate" {
- t.Fatalf("claims.ReturnURL=%q, want %q", claims.ReturnURL, "https://pulse.example.com/auth/trial-activate")
- }
- if updatedRecord.CheckoutSessionID != "cs_test_123" {
- t.Fatalf("checkout_session_id=%q, want %q", updatedRecord.CheckoutSessionID, "cs_test_123")
- }
- if updatedRecord.CheckoutCompletedAt.IsZero() {
- t.Fatalf("expected checkout_completed_at to be recorded")
- }
- if entitlement.ActivationIssuedAt == nil || entitlement.ActivationIssuedAt.IsZero() {
- t.Fatalf("expected activation_issued_at to be recorded")
- }
- if strings.TrimSpace(entitlement.ActivationToken) == "" {
- t.Fatalf("expected activation_token to be persisted")
- }
- if entitlement.ActivationToken != token {
- t.Fatalf("activation_token=%q, want issued redirect token", entitlement.ActivationToken)
- }
-}
-
-func TestTrialSignupHandleCompleteReusesStoredActivationToken(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: time.Unix(1710000000, 0).UTC(),
- VerificationExpiresAt: time.Unix(1710000000, 0).UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, time.Unix(1710000000, 0).UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
-
- h := NewTrialSignupHandlers(&CPConfig{
- StripeAPIKey: "sk_test_123",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, svc)
- h.now = func() time.Time { return time.Unix(1710000000, 0).UTC() }
- h.entitlements.SetNow(h.now)
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": record.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- firstReq := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_reuse", nil)
- firstRec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(firstRec, firstReq)
- if firstRec.Code != http.StatusOK {
- t.Fatalf("first status=%d, want %d body=%q", firstRec.Code, http.StatusOK, firstRec.Body.String())
- }
- firstEntitlement, err := reg.GetHostedEntitlementByTrialRequestID(record.ID)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID(first): %v", err)
- }
- firstIssuedToken := strings.TrimSpace(firstEntitlement.ActivationToken)
- if firstIssuedToken == "" {
- t.Fatal("expected first activation token")
- }
-
- secondReq := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_reuse", nil)
- secondRec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(secondRec, secondReq)
- if secondRec.Code != http.StatusOK {
- t.Fatalf("second status=%d, want %d body=%q", secondRec.Code, http.StatusOK, secondRec.Body.String())
- }
- secondEntitlement, err := reg.GetHostedEntitlementByTrialRequestID(record.ID)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID(second): %v", err)
- }
- secondIssuedToken := strings.TrimSpace(secondEntitlement.ActivationToken)
- if secondIssuedToken == "" {
- t.Fatal("expected second activation token")
- }
- if secondIssuedToken != firstIssuedToken {
- t.Fatalf("second token=%q, want first token=%q", secondIssuedToken, firstIssuedToken)
- }
-
- claims, err := pkglicensing.VerifyTrialActivationToken(secondIssuedToken, pub, "pulse.example.com", h.now().UTC())
- if err != nil {
- t.Fatalf("VerifyTrialActivationToken: %v", err)
- }
- if claims.Subject != "cs_test_reuse" {
- t.Fatalf("claims.Subject=%q, want %q", claims.Subject, "cs_test_reuse")
- }
- if claims.ReturnURL != "https://pulse.example.com/auth/trial-activate" {
- t.Fatalf("claims.ReturnURL=%q, want %q", claims.ReturnURL, "https://pulse.example.com/auth/trial-activate")
- }
-}
-
-func TestTrialSignupHandleCompleteRotatesExpiredActivationToken(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- baseNow := time.Unix(1710000000, 0).UTC()
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: baseNow,
- VerificationExpiresAt: baseNow.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, baseNow)
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
-
- now := baseNow
- h := NewTrialSignupHandlers(&CPConfig{
- StripeAPIKey: "sk_test_123",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, svc)
- h.now = func() time.Time { return now }
- h.entitlements.SetNow(h.now)
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": record.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- firstReq := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_rotate", nil)
- firstRec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(firstRec, firstReq)
- if firstRec.Code != http.StatusOK {
- t.Fatalf("first status=%d, want %d body=%q", firstRec.Code, http.StatusOK, firstRec.Body.String())
- }
- firstEntitlement, err := reg.GetHostedEntitlementByTrialRequestID(record.ID)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID(first): %v", err)
- }
- firstIssuedToken := strings.TrimSpace(firstEntitlement.ActivationToken)
- if firstIssuedToken == "" {
- t.Fatal("expected first activation token")
- }
-
- now = now.Add(trialSignupActivationTokenTTL + time.Minute)
-
- secondReq := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_rotate", nil)
- secondRec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(secondRec, secondReq)
- if secondRec.Code != http.StatusOK {
- t.Fatalf("second status=%d, want %d body=%q", secondRec.Code, http.StatusOK, secondRec.Body.String())
- }
- secondEntitlement, err := reg.GetHostedEntitlementByTrialRequestID(record.ID)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByTrialRequestID(second): %v", err)
- }
- secondIssuedToken := strings.TrimSpace(secondEntitlement.ActivationToken)
- if secondIssuedToken == "" {
- t.Fatal("expected second activation token")
- }
- if secondIssuedToken == firstIssuedToken {
- t.Fatal("expected expired activation token to be rotated")
- }
-
- claims, err := pkglicensing.VerifyTrialActivationToken(secondIssuedToken, pub, "pulse.example.com", now)
- if err != nil {
- t.Fatalf("VerifyTrialActivationToken: %v", err)
- }
- if claims.Subject != "cs_test_rotate" {
- t.Fatalf("claims.Subject=%q, want %q", claims.Subject, "cs_test_rotate")
- }
- if claims.ReturnURL != "https://pulse.example.com/auth/trial-activate" {
- t.Fatalf("claims.ReturnURL=%q, want %q", claims.ReturnURL, "https://pulse.example.com/auth/trial-activate")
- }
-}
-
-func TestTrialSignupHandleRedeemRecordsRedemption(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- if err := store.MarkCheckoutCompleted(record.ID, "cs_test_redeem", now); err != nil {
- t.Fatalf("MarkCheckoutCompleted: %v", err)
- }
-
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
- h := NewTrialSignupHandlers(&CPConfig{
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, svc)
- h.now = func() time.Time { return now }
- h.entitlements.SetNow(h.now)
- activationToken, err := h.entitlements.IssueTrialActivation(entitlements.TrialActivationInput{
- RequestID: record.ID,
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- CheckoutSessionID: "cs_test_redeem",
- TrialStartedAt: now,
- IssuedAt: now,
- TTL: trialSignupActivationTokenTTL,
- })
- if err != nil {
- t.Fatalf("IssueTrialActivation: %v", err)
- }
-
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/redeem", strings.NewReader(`{"token":"`+activationToken+`"}`))
- req.Header.Set("Content-Type", "application/json")
- rec := httptest.NewRecorder()
- h.HandleTrialSignupRedeem(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
- }
-
- var resp trialSignupRedeemResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode response: %v", err)
- }
- if strings.TrimSpace(resp.EntitlementJWT) == "" {
- t.Fatal("expected entitlement_jwt in response")
- }
- if strings.TrimSpace(resp.EntitlementRefreshToken) == "" {
- t.Fatal("expected entitlement_refresh_token in response")
- }
- entitlementClaims, err := pkglicensing.VerifyEntitlementLeaseToken(resp.EntitlementJWT, pub, "pulse.example.com", now)
- if err != nil {
- t.Fatalf("VerifyEntitlementLeaseToken: %v", err)
- }
- if entitlementClaims.OrgID != "default" {
- t.Fatalf("entitlementClaims.OrgID=%q, want %q", entitlementClaims.OrgID, "default")
- }
- if entitlementClaims.SubscriptionState != pkglicensing.SubStateTrial {
- t.Fatalf("entitlementClaims.SubscriptionState=%q, want %q", entitlementClaims.SubscriptionState, pkglicensing.SubStateTrial)
- }
-
- updatedRecord, err := store.GetRecord(record.ID)
- if err != nil {
- t.Fatalf("GetRecord(updated): %v", err)
- }
- if updatedRecord.RedemptionRecordedAt.IsZero() {
- t.Fatalf("expected redemption_recorded_at to be set")
- }
- entitlement, err := reg.GetHostedEntitlementByRefreshToken(resp.EntitlementRefreshToken)
- if err != nil {
- t.Fatalf("GetHostedEntitlementByRefreshToken: %v", err)
- }
- if entitlement == nil || entitlement.TrialRequestID != record.ID {
- t.Fatalf("expected hosted trial entitlement for request %q, got %#v", record.ID, entitlement)
- }
-
- claims, err := pkglicensing.VerifyTrialActivationToken(activationToken, pub, "pulse.example.com", now)
- if err != nil {
- t.Fatalf("VerifyTrialActivationToken: %v", err)
- }
- if claims.ReturnURL != "https://pulse.example.com/auth/trial-activate" {
- t.Fatalf("claims.ReturnURL=%q, want %q", claims.ReturnURL, "https://pulse.example.com/auth/trial-activate")
- }
-}
-
-func TestTrialSignupHandleRedeemRejectsHostMismatch(t *testing.T) {
- _, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- activationToken, err := jwt.NewWithClaims(jwt.SigningMethodEdDSA, pkglicensing.TrialActivationClaims{
- OrgID: "default",
- Email: "[email protected]",
- InstanceHost: "wrong.example.com",
- InstanceToken: "tsi_test",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- RegisteredClaims: jwt.RegisteredClaims{
- Issuer: pkglicensing.TrialActivationIssuer,
- Audience: jwt.ClaimStrings{pkglicensing.TrialActivationAudience},
- Subject: "cs_bad_host",
- IssuedAt: jwt.NewNumericDate(now),
- ExpiresAt: jwt.NewNumericDate(now.Add(trialSignupActivationTokenTTL)),
- },
- }).SignedString(priv)
- if err != nil {
- t.Fatalf("SignedString: %v", err)
- }
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
-
- h := NewTrialSignupHandlers(&CPConfig{
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, svc)
- h.now = func() time.Time { return now }
- h.entitlements.SetNow(h.now)
-
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/redeem", strings.NewReader(`{"token":"`+activationToken+`"}`))
- req.Header.Set("Content-Type", "application/json")
- rec := httptest.NewRecorder()
- h.HandleTrialSignupRedeem(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- if !strings.Contains(rec.Body.String(), "host mismatch") {
- t.Fatalf("expected host mismatch error, got %q", rec.Body.String())
- }
-}
-
-func TestTrialSignupHandleRefreshReturnsLease(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- now := time.Unix(1710000000, 0).UTC()
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
- svc.SetNow(func() time.Time { return now.Add(time.Hour) })
- if _, _, err := reg.StoreOrIssueTrialHostedEntitlement(registry.TrialHostedEntitlementInput{
- RequestID: "trial_request_refresh",
- OrgID: "default",
- Email: "[email protected]",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- InstanceHost: "pulse.example.com",
- TrialStartedAt: now,
- IssuedAt: now,
- RedeemedAt: now,
- RefreshToken: "etr_test_refresh",
- }); err != nil {
- t.Fatalf("StoreOrIssueTrialHostedEntitlement: %v", err)
- }
- h := NewHostedEntitlementHandlers(svc)
-
- req := httptest.NewRequest(http.MethodPost, "/api/entitlements/refresh", strings.NewReader(`{"org_id":"default","instance_host":"pulse.example.com","entitlement_refresh_token":"etr_test_refresh"}`))
- req.Header.Set("Content-Type", "application/json")
- rec := httptest.NewRecorder()
- h.HandleRefresh(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
- }
-
- var resp hostedEntitlementRefreshResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode response: %v", err)
- }
- if strings.TrimSpace(resp.EntitlementJWT) == "" {
- t.Fatal("expected entitlement_jwt in refresh response")
- }
- claims, err := pkglicensing.VerifyEntitlementLeaseToken(resp.EntitlementJWT, pub, "pulse.example.com", now.Add(time.Hour))
- if err != nil {
- t.Fatalf("VerifyEntitlementLeaseToken: %v", err)
- }
- if claims.OrgID != "default" {
- t.Fatalf("claims.OrgID=%q, want %q", claims.OrgID, "default")
- }
-}
-
-func TestTrialSignupHandleRefreshReturnsPaidTenantLease(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
-
- accountID, err := registry.GenerateAccountID()
- if err != nil {
- t.Fatalf("GenerateAccountID: %v", err)
- }
- if err := reg.CreateAccount(&registry.Account{
- ID: accountID,
- Kind: registry.AccountKindIndividual,
- DisplayName: "Pulse Labs",
- }); err != nil {
- t.Fatalf("CreateAccount: %v", err)
- }
- if err := reg.CreateStripeAccount(&registry.StripeAccount{
- AccountID: accountID,
- StripeCustomerID: "cus_paid_refresh",
- PlanVersion: "cloud_starter",
- SubscriptionState: "active",
- }); err != nil {
- t.Fatalf("CreateStripeAccount: %v", err)
- }
- tenant := &registry.Tenant{
- ID: "t-PAIDREF01",
- AccountID: accountID,
- Email: "[email protected]",
- State: registry.TenantStateActive,
- StripeCustomerID: "cus_paid_refresh",
- PlanVersion: "cloud_starter",
- }
- if err := reg.Create(tenant); err != nil {
- t.Fatalf("Create: %v", err)
- }
- now := time.Unix(1710000000, 0).UTC()
- if _, _, err := reg.StoreOrIssueHostedEntitlement(tenant.ID, "etr_paid_refresh", now); err != nil {
- t.Fatalf("StoreOrIssueHostedEntitlement: %v", err)
- }
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(priv))
- svc.SetNow(func() time.Time { return now })
- h := NewHostedEntitlementHandlers(svc)
-
- req := httptest.NewRequest(http.MethodPost, "/api/entitlements/refresh", strings.NewReader(`{"org_id":"default","instance_host":"t-PAIDREF01.cloud.example.com","entitlement_refresh_token":"etr_paid_refresh"}`))
- req.Header.Set("Content-Type", "application/json")
- rec := httptest.NewRecorder()
- h.HandleRefresh(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusOK, rec.Body.String())
- }
-
- var resp hostedEntitlementRefreshResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode response: %v", err)
- }
- claims, err := pkglicensing.VerifyEntitlementLeaseToken(resp.EntitlementJWT, pub, "t-PAIDREF01.cloud.example.com", now)
- if err != nil {
- t.Fatalf("VerifyEntitlementLeaseToken: %v", err)
- }
- if claims.SubscriptionState != pkglicensing.SubStateActive {
- t.Fatalf("claims.SubscriptionState=%q, want %q", claims.SubscriptionState, pkglicensing.SubStateActive)
- }
- if claims.PlanVersion != "cloud_starter" {
- t.Fatalf("claims.PlanVersion=%q, want %q", claims.PlanVersion, "cloud_starter")
- }
- if len(claims.Capabilities) == 0 {
- t.Fatal("expected paid capabilities in refreshed lease")
- }
- entitlement, err := reg.GetHostedEntitlementByRefreshToken("etr_paid_refresh")
- if err != nil {
- t.Fatalf("GetHostedEntitlementByRefreshToken: %v", err)
- }
- if entitlement.LastRefreshedAt == nil || entitlement.LastRefreshedAt.Unix() != now.Unix() {
- t.Fatalf("last_refreshed_at=%v, want %v", entitlement.LastRefreshedAt, now)
- }
-}
-
-func TestTrialSignupHandleCompleteRejectsDuplicateIssuedEmail(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
- h.cfg.StripeAPIKey = "sk_test_123"
-
- firstRawToken := requestTrialVerification(t, h, sender)
- firstVerifiedToken := verifyTrialRequest(t, h, firstRawToken)
- firstRequestID := parseVerifiedTokenRequestID(t, h, firstVerifiedToken)
-
- secondRawToken := requestTrialVerification(t, h, sender)
- secondVerifiedToken := verifyTrialRequest(t, h, secondRawToken)
- secondRequestID := parseVerifiedTokenRequestID(t, h, secondVerifiedToken)
- if err := store.MarkTrialIssued(firstRequestID, h.now().UTC()); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
-
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": secondRequestID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_dupe", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusConflict {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This recovery email has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Start Trial Again")
-}
-
-func TestTrialSignupHandleCompleteRejectsDuplicateCorporateDomainIssuedEmail(t *testing.T) {
- h, store, _ := newTrialSignupTestHandler(t)
- h.cfg.StripeAPIKey = "sk_test_123"
-
- firstToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Alice Admin",
- Email: "[email protected]",
- Company: "Acme Inc.",
- CreatedAt: h.now().UTC(),
- VerificationExpiresAt: h.now().UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(first): %v", err)
- }
- firstRecord, err := store.ConsumeVerification(firstToken, h.now().UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification(first): %v", err)
- }
- if err := store.MarkTrialIssued(firstRecord.ID, h.now().UTC()); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
-
- secondToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Bob Builder",
- Email: "[email protected]",
- Company: "Acme Holdings",
- CreatedAt: h.now().UTC(),
- VerificationExpiresAt: h.now().UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(second): %v", err)
- }
- secondRecord, err := store.ConsumeVerification(secondToken, h.now().UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification(second): %v", err)
- }
-
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": secondRecord.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_domain_dupe", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusConflict {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This organization has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Start Trial Again")
-}
-
-func TestTrialSignupHandleCompleteRejectsCheckoutSessionMismatch(t *testing.T) {
- h, store, sender := newTrialSignupTestHandler(t)
- h.cfg.StripeAPIKey = "sk_test_123"
-
- rawToken := requestTrialVerification(t, h, sender)
- verifiedToken := verifyTrialRequest(t, h, rawToken)
- requestID := parseVerifiedTokenRequestID(t, h, verifiedToken)
- if err := store.MarkCheckoutStarted(requestID, "cs_bound_original", h.now().UTC()); err != nil {
- t.Fatalf("MarkCheckoutStarted: %v", err)
- }
-
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": requestID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_other_session", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup could not be completed",
- "This secure trial request does not match the checkout session that was already started.",
- "pulse.example.com",
- "Start Trial Again",
- )
-}
-
-func TestTrialSignupHandleCompleteRejectsNonTrialCheckoutSession(t *testing.T) {
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: time.Unix(1710000000, 0).UTC(),
- VerificationExpiresAt: time.Unix(1710000000, 0).UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, time.Unix(1710000000, 0).UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
-
- h := NewTrialSignupHandlers(&CPConfig{
- StripeAPIKey: "sk_test_123",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, nil)
- h.now = func() time.Time { return time.Unix(1710000000, 0).UTC() }
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModePayment,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": record.ID,
- "signup_source": "pulse_pro_trial",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_non_trial", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup could not be completed",
- "This secure trial session is not valid for a Pulse Pro trial.",
- "pulse.example.com",
- )
-
- _ = pub
-}
-
-func TestTrialSignupHandleCompleteRejectsMissingVerifiedTrialMetadata(t *testing.T) {
- _, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey: %v", err)
- }
-
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: time.Unix(1710000000, 0).UTC(),
- VerificationExpiresAt: time.Unix(1710000000, 0).UTC().Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, time.Unix(1710000000, 0).UTC())
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
-
- h := NewTrialSignupHandlers(&CPConfig{
- StripeAPIKey: "sk_test_123",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(priv),
- }, nil, store, nil)
- h.now = func() time.Time { return time.Unix(1710000000, 0).UTC() }
- h.getCheckoutSession = func(id string, _ *stripe.CheckoutSessionParams) (*stripe.CheckoutSession, error) {
- return &stripe.CheckoutSession{
- ID: id,
- Status: stripe.CheckoutSessionStatusComplete,
- Mode: stripe.CheckoutSessionModeSubscription,
- CustomerEmail: "[email protected]",
- Metadata: map[string]string{
- "org_id": "default",
- "return_url": "https://pulse.example.com/auth/trial-activate",
- "trial_request_id": record.ID,
- "signup_source": "something_else",
- "email_mode": "backup",
- },
- }, nil
- }
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/complete?session_id=cs_test_bad_metadata", nil)
- rec := httptest.NewRecorder()
- h.HandleTrialSignupComplete(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup could not be completed",
- "This secure trial session is not valid for a Pulse Pro trial.",
- "pulse.example.com",
- )
-}
-
-func newTrialSignupTestHandler(t *testing.T) (*TrialSignupHandlers, *TrialSignupStore, *captureEmailSender) {
- t.Helper()
-
- _, activationPriv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey activation: %v", err)
- }
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
- reg, err := registry.NewTenantRegistry(t.TempDir())
- if err != nil {
- t.Fatalf("NewTenantRegistry: %v", err)
- }
- t.Cleanup(func() { _ = reg.Close() })
-
- sender := &captureEmailSender{}
- svc := entitlements.NewService(reg, "https://cloud.example.com", base64.StdEncoding.EncodeToString(activationPriv))
- h := NewTrialSignupHandlers(&CPConfig{
- BaseURL: "https://cloud.example.com",
- TrialActivationPrivateKey: base64.StdEncoding.EncodeToString(activationPriv),
- EmailFrom: "[email protected]",
- }, sender, store, svc)
- h.now = func() time.Time { return time.Unix(1710000000, 0).UTC() }
- h.entitlements.SetNow(h.now)
- return h, store, sender
-}
-
-func requestTrialVerification(t *testing.T, h *TrialSignupHandlers, sender *captureEmailSender) string {
- t.Helper()
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("request verification status=%d body=%q", rec.Code, rec.Body.String())
- }
-
- rawToken := extractQueryValueFromTextURL(t, sender.msg.Text, "token")
- if rawToken == "" {
- t.Fatalf("expected token in verification email body")
- }
- return rawToken
-}
-
-func verifyTrialRequest(t *testing.T, h *TrialSignupHandlers, rawToken string) string {
- t.Helper()
-
- req := httptest.NewRequest(http.MethodGet, "/trial-signup/verify?token="+url.QueryEscape(rawToken), nil)
- rec := httptest.NewRecorder()
- h.HandleVerifyEmail(rec, req)
- if rec.Code != http.StatusSeeOther {
- t.Fatalf("verify request status=%d body=%q", rec.Code, rec.Body.String())
- }
- verifiedToken := extractQueryValueFromURL(t, rec.Header().Get("Location"), "verified")
- if verifiedToken == "" {
- t.Fatalf("expected verified token in redirect URL")
- }
- return verifiedToken
-}
-
-func parseVerifiedTokenRequestID(t *testing.T, h *TrialSignupHandlers, verifiedToken string) string {
- t.Helper()
- record, err := h.lookupVerifiedTrialSignupRecord(verifiedToken)
- if err != nil {
- t.Fatalf("lookupVerifiedTrialSignupRecord: %v", err)
- }
- return record.ID
-}
-
-func assertTrialSignupFailurePageContains(t *testing.T, body string, parts ...string) {
- t.Helper()
- if !strings.Contains(body, "Pulse Pro Trial") {
- t.Fatalf("expected trial failure page chrome, got %q", body)
- }
- for _, part := range parts {
- if !strings.Contains(body, part) {
- t.Fatalf("expected response body to contain %q, got %q", part, body)
- }
- }
-}
-
-func assertTrialSignupFailurePageOmits(t *testing.T, body string, parts ...string) {
- t.Helper()
- for _, part := range parts {
- if strings.Contains(body, part) {
- t.Fatalf("expected response body to omit %q, got %q", part, body)
- }
- }
-}
-
-func extractQueryValueFromTextURL(t *testing.T, text, key string) string {
- t.Helper()
- start := strings.Index(text, "https://")
- if start == -1 {
- t.Fatalf("no URL found in %q", text)
- }
- rawURL := strings.Fields(text[start:])[0]
- return extractQueryValueFromURL(t, rawURL, key)
-}
-
-func extractQueryValueFromURL(t *testing.T, rawURL, key string) string {
- t.Helper()
- parsed, err := url.Parse(strings.TrimSpace(rawURL))
- if err != nil {
- t.Fatalf("Parse URL %q: %v", rawURL, err)
- }
- return strings.TrimSpace(parsed.Query().Get(key))
-}
-
-func TestIsValidTrialReturnURL(t *testing.T) {
- tests := []struct {
- name string
- raw string
- want bool
- }{
- {name: "https callback", raw: "https://pulse.example.com/auth/trial-activate", want: true},
- {name: "private http callback", raw: "http://192.168.0.98:7655/auth/trial-activate", want: true},
- {name: "localhost http callback", raw: "http://localhost:7655/auth/trial-activate", want: true},
- {name: "local dns http callback", raw: "http://pulse.local:7655/auth/trial-activate", want: true},
- {name: "wrong path", raw: "https://pulse.example.com/settings", want: false},
- {name: "query not allowed", raw: "https://pulse.example.com/auth/trial-activate?next=1", want: false},
- {name: "fragment not allowed", raw: "https://pulse.example.com/auth/trial-activate#token=x", want: false},
- {name: "public http not allowed", raw: "http://pulse.example.com/auth/trial-activate", want: false},
- {name: "arbitrary https path under callback prefix not allowed", raw: "https://pulse.example.com/auth/trial-activate/extra", want: false},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := isValidTrialReturnURL(tt.raw); got != tt.want {
- t.Fatalf("isValidTrialReturnURL(%q)=%v, want %v", tt.raw, got, tt.want)
- }
- })
- }
-}
diff --git a/internal/cloudcp/trial_signup_store.go b/internal/cloudcp/trial_signup_store.go
deleted file mode 100644
index 9e4eb2f46b..0000000000
--- a/internal/cloudcp/trial_signup_store.go
+++ /dev/null
@@ -1,1288 +0,0 @@
-package cloudcp
-
-import (
- "crypto/rand"
- "crypto/sha256"
- "database/sql"
- "encoding/base64"
- "encoding/hex"
- "errors"
- "fmt"
- "net/url"
- "os"
- "path/filepath"
- "regexp"
- "strings"
- "sync"
- "time"
-
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rs/zerolog/log"
- _ "modernc.org/sqlite"
-)
-
-var (
- ErrTrialSignupVerificationInvalid = errors.New("trial signup verification token is invalid")
- ErrTrialSignupVerificationExpired = errors.New("trial signup verification token is expired")
- ErrTrialSignupVerificationUsed = errors.New("trial signup verification token already used")
- ErrTrialSignupVerificationPending = errors.New("trial signup verification already pending")
- ErrTrialSignupRecordNotFound = errors.New("trial signup record not found")
- ErrTrialSignupEmailAlreadyUsed = errors.New("trial signup email already used")
- ErrTrialSignupOrganizationUsed = errors.New("trial signup organization already used")
-)
-
-const (
- trialSignupStoreCleanupInterval = 10 * time.Minute
- trialSignupStorePrivateDirPerm = 0o700
- trialSignupTokenPrefix = "tsv1_"
-)
-
-var (
- trialSignupCompanyNoiseTokens = map[string]struct{}{
- "and": {}, "co": {}, "company": {}, "corp": {}, "corporation": {}, "gmbh": {}, "group": {},
- "holding": {}, "holdings": {}, "inc": {}, "incorporated": {}, "limited": {}, "llc": {},
- "llp": {}, "ltd": {}, "plc": {}, "pte": {}, "pty": {}, "sa": {}, "sas": {}, "sarl": {},
- }
- trialSignupPublicEmailDomains = map[string]struct{}{
- "aol.com": {}, "fastmail.com": {}, "gmail.com": {}, "gmx.com": {}, "googlemail.com": {},
- "hey.com": {}, "hotmail.com": {}, "icloud.com": {}, "live.com": {}, "mac.com": {},
- "mail.com": {}, "me.com": {}, "msn.com": {}, "outlook.com": {}, "pm.me": {},
- "proton.me": {}, "protonmail.com": {}, "rocketmail.com": {}, "yahoo.com": {},
- "ymail.com": {}, "zoho.com": {},
- }
- trialSignupNonAlnumPattern = regexp.MustCompile(`[^a-z0-9]+`)
-)
-
-type trialSignupIssuanceConflictKind string
-
-const (
- trialSignupConflictNone trialSignupIssuanceConflictKind = ""
- trialSignupConflictEmail trialSignupIssuanceConflictKind = "email"
- trialSignupConflictDomain trialSignupIssuanceConflictKind = "domain"
- trialSignupConflictPublicCompany trialSignupIssuanceConflictKind = "public_company"
-)
-
-type TrialSignupIssuanceConflict struct {
- RequestID string
- Kind trialSignupIssuanceConflictKind
-}
-
-type TrialSignupRecord struct {
- ID string
- OrgID string
- ReturnURL string
- InstanceToken string
- Name string
- Email string
- Company string
- VerificationExpiresAt time.Time
- CreatedAt time.Time
- VerifiedAt time.Time
- CheckoutTokenExpiresAt time.Time
- CheckoutStartedAt time.Time
- CheckoutCompletedAt time.Time
- CheckoutTokenHash string
- CheckoutSessionID string
- RedemptionRecordedAt time.Time
-}
-
-type TrialSignupStore struct {
- db *sql.DB
- stopCleanup chan struct{}
- mu sync.Mutex
-}
-
-func NewTrialSignupStore(dir string) (*TrialSignupStore, error) {
- dir = filepath.Clean(dir)
- if strings.TrimSpace(dir) == "" {
- return nil, fmt.Errorf("dir is required")
- }
- if err := ensureTrialSignupStoreDir(dir); err != nil {
- return nil, fmt.Errorf("create trial signup store dir: %w", err)
- }
-
- dbPath := filepath.Join(dir, "trial_signup.db")
- dsn := dbPath + "?" + url.Values{
- "_pragma": []string{
- "busy_timeout(30000)",
- "journal_mode(WAL)",
- "synchronous(NORMAL)",
- },
- }.Encode()
-
- db, err := sql.Open("sqlite", dsn)
- if err != nil {
- return nil, fmt.Errorf("open trial signup db: %w", err)
- }
- db.SetMaxOpenConns(1)
- db.SetMaxIdleConns(1)
- db.SetConnMaxLifetime(0)
-
- s := &TrialSignupStore{
- db: db,
- stopCleanup: make(chan struct{}),
- }
- if err := s.initSchema(); err != nil {
- if closeErr := db.Close(); closeErr != nil {
- return nil, errors.Join(err, fmt.Errorf("close trial signup db after schema init failure: %w", closeErr))
- }
- return nil, err
- }
-
- go s.cleanupLoop()
- return s, nil
-}
-
-func ensureTrialSignupStoreDir(dir string) error {
- if err := os.MkdirAll(dir, trialSignupStorePrivateDirPerm); err != nil {
- return err
- }
- return os.Chmod(dir, trialSignupStorePrivateDirPerm)
-}
-
-func (s *TrialSignupStore) initSchema() error {
- schema := `
- CREATE TABLE IF NOT EXISTS trial_signup_requests (
- request_id TEXT PRIMARY KEY,
- verification_token_hash TEXT NOT NULL UNIQUE,
- org_id TEXT NOT NULL,
- return_url TEXT NOT NULL,
- instance_token TEXT NOT NULL DEFAULT '',
- name TEXT NOT NULL,
- email TEXT NOT NULL,
- company TEXT NOT NULL DEFAULT '',
- verification_expires_at INTEGER NOT NULL,
- created_at INTEGER NOT NULL,
- verified_at INTEGER,
- checkout_token_expires_at INTEGER,
- checkout_started_at INTEGER,
- checkout_completed_at INTEGER,
- checkout_token_hash TEXT NOT NULL DEFAULT '',
- checkout_session_id TEXT NOT NULL DEFAULT '',
- redemption_recorded_at INTEGER
- );
- CREATE INDEX IF NOT EXISTS idx_trial_signup_email ON trial_signup_requests(email);
- CREATE INDEX IF NOT EXISTS idx_trial_signup_instance_token ON trial_signup_requests(instance_token);
- CREATE INDEX IF NOT EXISTS idx_trial_signup_verify_expiry ON trial_signup_requests(verification_expires_at);
- CREATE INDEX IF NOT EXISTS idx_trial_signup_verified_at ON trial_signup_requests(verified_at);
- CREATE TABLE IF NOT EXISTS trial_signup_issuances (
- email TEXT PRIMARY KEY,
- request_id TEXT NOT NULL UNIQUE,
- email_domain TEXT NOT NULL DEFAULT '',
- company_key TEXT NOT NULL DEFAULT '',
- issued_at INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS idx_trial_signup_issuances_request_id ON trial_signup_issuances(request_id);
- CREATE INDEX IF NOT EXISTS idx_trial_signup_issuances_domain ON trial_signup_issuances(email_domain);
- CREATE INDEX IF NOT EXISTS idx_trial_signup_issuances_company_key ON trial_signup_issuances(company_key);
- `
- if _, err := s.db.Exec(schema); err != nil {
- return fmt.Errorf("init trial signup schema: %w", err)
- }
- hasDomain, err := s.tableHasColumn("trial_signup_issuances", "email_domain")
- if err != nil {
- return fmt.Errorf("check trial_signup_issuances schema for email_domain: %w", err)
- }
- if !hasDomain {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_issuances ADD COLUMN email_domain TEXT NOT NULL DEFAULT ''`); err != nil {
- return fmt.Errorf("migrate trial_signup_issuances: add email_domain: %w", err)
- }
- }
- hasCompanyKey, err := s.tableHasColumn("trial_signup_issuances", "company_key")
- if err != nil {
- return fmt.Errorf("check trial_signup_issuances schema for company_key: %w", err)
- }
- if !hasCompanyKey {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_issuances ADD COLUMN company_key TEXT NOT NULL DEFAULT ''`); err != nil {
- return fmt.Errorf("migrate trial_signup_issuances: add company_key: %w", err)
- }
- }
- if err := s.backfillTrialSignupIssuanceIdentities(); err != nil {
- return fmt.Errorf("backfill trial signup issuance identities: %w", err)
- }
- hasCheckoutCompletedAt, err := s.tableHasColumn("trial_signup_requests", "checkout_completed_at")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for checkout_completed_at: %w", err)
- }
- if !hasCheckoutCompletedAt {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN checkout_completed_at INTEGER`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add checkout_completed_at: %w", err)
- }
- }
- hasInstanceToken, err := s.tableHasColumn("trial_signup_requests", "instance_token")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for instance_token: %w", err)
- }
- if !hasInstanceToken {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN instance_token TEXT NOT NULL DEFAULT ''`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add instance_token: %w", err)
- }
- }
- hasCheckoutTokenExpiresAt, err := s.tableHasColumn("trial_signup_requests", "checkout_token_expires_at")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for checkout_token_expires_at: %w", err)
- }
- if !hasCheckoutTokenExpiresAt {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN checkout_token_expires_at INTEGER`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add checkout_token_expires_at: %w", err)
- }
- }
- hasCheckoutTokenHash, err := s.tableHasColumn("trial_signup_requests", "checkout_token_hash")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for checkout_token_hash: %w", err)
- }
- if !hasCheckoutTokenHash {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN checkout_token_hash TEXT NOT NULL DEFAULT ''`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add checkout_token_hash: %w", err)
- }
- }
- hasCheckoutSessionID, err := s.tableHasColumn("trial_signup_requests", "checkout_session_id")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for checkout_session_id: %w", err)
- }
- if !hasCheckoutSessionID {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN checkout_session_id TEXT NOT NULL DEFAULT ''`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add checkout_session_id: %w", err)
- }
- }
- hasRedemptionRecordedAt, err := s.tableHasColumn("trial_signup_requests", "redemption_recorded_at")
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for redemption_recorded_at: %w", err)
- }
- if !hasRedemptionRecordedAt {
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests ADD COLUMN redemption_recorded_at INTEGER`); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: add redemption_recorded_at: %w", err)
- }
- }
- for _, legacyColumn := range []string{
- "activation_issued_at",
- "activation_token",
- "entitlement_refresh_issued_at",
- "entitlement_refresh_token",
- } {
- hasLegacyColumn, err := s.tableHasColumn("trial_signup_requests", legacyColumn)
- if err != nil {
- return fmt.Errorf("check trial_signup_requests schema for %s: %w", legacyColumn, err)
- }
- if !hasLegacyColumn {
- continue
- }
- if _, err := s.db.Exec(`ALTER TABLE trial_signup_requests DROP COLUMN ` + legacyColumn); err != nil {
- return fmt.Errorf("migrate trial_signup_requests: drop %s: %w", legacyColumn, err)
- }
- }
- return nil
-}
-
-func (s *TrialSignupStore) cleanupLoop() {
- ticker := time.NewTicker(trialSignupStoreCleanupInterval)
- defer ticker.Stop()
- for {
- select {
- case <-ticker.C:
- if err := s.DeleteExpired(time.Now().UTC()); err != nil {
- log.Warn().Err(err).Msg("Failed to delete expired trial signup requests")
- }
- case <-s.stopCleanup:
- return
- }
- }
-}
-
-func (s *TrialSignupStore) CreateVerification(rec *TrialSignupRecord) (string, error) {
- if s == nil {
- return "", fmt.Errorf("trial signup store not configured")
- }
- if rec == nil {
- return "", fmt.Errorf("trial signup record is required")
- }
- requestID, err := randomHex(16)
- if err != nil {
- return "", fmt.Errorf("generate request id: %w", err)
- }
- rawToken, err := randomPrefixedToken()
- if err != nil {
- return "", fmt.Errorf("generate verification token: %w", err)
- }
- tokenHash := hashTrialSignupToken(rawToken)
-
- now := rec.CreatedAt.UTC()
- if now.IsZero() {
- now = time.Now().UTC()
- }
- expiresAt := rec.VerificationExpiresAt.UTC()
- if expiresAt.IsZero() {
- return "", fmt.Errorf("verification expiry is required")
- }
- email := normalizeTrialSignupEmail(rec.Email)
- if email == "" {
- return "", fmt.Errorf("email is required")
- }
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return "", fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- _, err = db.Exec(
- `INSERT INTO trial_signup_requests (
- request_id, verification_token_hash, org_id, return_url, instance_token, name, email, company,
- verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, '', '', NULL)`,
- requestID,
- tokenHash,
- rec.OrgID,
- rec.ReturnURL,
- rec.InstanceToken,
- rec.Name,
- email,
- rec.Company,
- expiresAt.Unix(),
- now.Unix(),
- )
- if err != nil {
- return "", fmt.Errorf("insert trial signup request: %w", err)
- }
- rec.ID = requestID
- rec.CreatedAt = now
- rec.VerificationExpiresAt = expiresAt
- rec.Email = email
- return rawToken, nil
-}
-
-func (s *TrialSignupStore) CreateCheckoutRequest(rec *TrialSignupRecord) error {
- if s == nil {
- return fmt.Errorf("trial signup store not configured")
- }
- if rec == nil {
- return fmt.Errorf("trial signup record is required")
- }
- requestID, err := randomHex(16)
- if err != nil {
- return fmt.Errorf("generate request id: %w", err)
- }
- rawToken, err := randomPrefixedToken()
- if err != nil {
- return fmt.Errorf("generate request token: %w", err)
- }
- tokenHash := hashTrialSignupToken(rawToken)
-
- now := rec.CreatedAt.UTC()
- if now.IsZero() {
- now = time.Now().UTC()
- }
- expiresAt := rec.VerificationExpiresAt.UTC()
- if expiresAt.IsZero() {
- expiresAt = now.Add(trialSignupVerificationTTL)
- }
- email := normalizeTrialSignupEmail(rec.Email)
- if email == "" {
- return fmt.Errorf("email is required")
- }
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- _, err = db.Exec(
- `INSERT INTO trial_signup_requests (
- request_id, verification_token_hash, org_id, return_url, instance_token, name, email, company,
- verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, '', '', NULL)`,
- requestID,
- tokenHash,
- rec.OrgID,
- rec.ReturnURL,
- rec.InstanceToken,
- rec.Name,
- email,
- rec.Company,
- expiresAt.Unix(),
- now.Unix(),
- now.Unix(),
- )
- if err != nil {
- return fmt.Errorf("insert trial signup checkout request: %w", err)
- }
- rec.ID = requestID
- rec.CreatedAt = now
- rec.VerificationExpiresAt = expiresAt
- rec.VerifiedAt = now
- rec.Email = email
- return nil
-}
-
-func (s *TrialSignupStore) ConsumeVerification(rawToken string, now time.Time) (*TrialSignupRecord, error) {
- if s == nil {
- return nil, ErrTrialSignupVerificationInvalid
- }
- tokenHash := hashTrialSignupToken(rawToken)
- if tokenHash == "" {
- return nil, ErrTrialSignupVerificationInvalid
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil, ErrTrialSignupVerificationInvalid
- }
- defer s.mu.Unlock()
-
- tx, err := db.Begin()
- if err != nil {
- return nil, fmt.Errorf("begin trial signup consume tx: %w", err)
- }
- defer func() {
- if rollbackErr := tx.Rollback(); rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {
- log.Warn().Err(rollbackErr).Msg("Failed to rollback trial signup consume transaction")
- }
- }()
-
- rec, err := loadTrialSignupRecord(tx.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE verification_token_hash = ?`,
- tokenHash,
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return nil, ErrTrialSignupVerificationInvalid
- }
- return nil, fmt.Errorf("load trial signup request: %w", err)
- }
- if now.After(rec.VerificationExpiresAt) {
- return nil, ErrTrialSignupVerificationExpired
- }
- if !rec.VerifiedAt.IsZero() {
- return nil, ErrTrialSignupVerificationUsed
- }
-
- res, err := tx.Exec(
- `UPDATE trial_signup_requests
- SET verified_at = ?
- WHERE request_id = ? AND verified_at IS NULL`,
- now.Unix(),
- rec.ID,
- )
- if err != nil {
- return nil, fmt.Errorf("mark trial signup verified: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return nil, fmt.Errorf("get trial signup update rows affected: %w", err)
- }
- if affected == 0 {
- return nil, ErrTrialSignupVerificationUsed
- }
- if err := tx.Commit(); err != nil {
- return nil, fmt.Errorf("commit trial signup consume tx: %w", err)
- }
- rec.VerifiedAt = now
- return rec, nil
-}
-
-func (s *TrialSignupStore) GetRecord(id string) (*TrialSignupRecord, error) {
- if s == nil {
- return nil, ErrTrialSignupRecordNotFound
- }
- id = strings.TrimSpace(id)
- if id == "" {
- return nil, ErrTrialSignupRecordNotFound
- }
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil, ErrTrialSignupRecordNotFound
- }
- defer s.mu.Unlock()
-
- rec, err := loadTrialSignupRecord(db.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE request_id = ?`,
- id,
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return nil, ErrTrialSignupRecordNotFound
- }
- return nil, fmt.Errorf("load trial signup request: %w", err)
- }
- return rec, nil
-}
-
-func (s *TrialSignupStore) MarkCheckoutStarted(id, sessionID string, now time.Time) error {
- if s == nil {
- return fmt.Errorf("trial signup store not configured")
- }
- id = strings.TrimSpace(id)
- sessionID = strings.TrimSpace(sessionID)
- if id == "" {
- return ErrTrialSignupRecordNotFound
- }
- if sessionID == "" {
- return fmt.Errorf("checkout session id is required")
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- res, err := db.Exec(
- `UPDATE trial_signup_requests
- SET checkout_started_at = ?,
- checkout_session_id = ?
- WHERE request_id = ? AND verified_at IS NOT NULL`,
- now.Unix(),
- sessionID,
- id,
- )
- if err != nil {
- return fmt.Errorf("mark trial signup checkout started: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return fmt.Errorf("get trial signup checkout rows affected: %w", err)
- }
- if affected == 0 {
- return ErrTrialSignupRecordNotFound
- }
- return nil
-}
-
-func (s *TrialSignupStore) MarkCheckoutCompleted(id, sessionID string, now time.Time) error {
- if s == nil {
- return fmt.Errorf("trial signup store not configured")
- }
- id = strings.TrimSpace(id)
- sessionID = strings.TrimSpace(sessionID)
- if id == "" || sessionID == "" {
- return ErrTrialSignupRecordNotFound
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- res, err := db.Exec(
- `UPDATE trial_signup_requests
- SET checkout_session_id = CASE
- WHEN checkout_session_id = '' THEN ?
- ELSE checkout_session_id
- END,
- checkout_completed_at = CASE
- WHEN checkout_completed_at IS NULL THEN ?
- ELSE checkout_completed_at
- END
- WHERE request_id = ?
- AND verified_at IS NOT NULL
- AND (checkout_session_id = '' OR checkout_session_id = ?)`,
- sessionID,
- now.Unix(),
- id,
- sessionID,
- )
- if err != nil {
- return fmt.Errorf("mark trial signup checkout completed: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return fmt.Errorf("get trial signup checkout completed rows affected: %w", err)
- }
- if affected == 0 {
- return ErrTrialSignupRecordNotFound
- }
- return nil
-}
-
-func (s *TrialSignupStore) HasIssuedTrialForEmail(email string) (bool, error) {
- if s == nil {
- return false, fmt.Errorf("trial signup store not configured")
- }
- email = normalizeTrialSignupEmail(email)
- if email == "" {
- return false, nil
- }
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return false, fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- var issuedAt int64
- err := db.QueryRow(
- `SELECT issued_at
- FROM trial_signup_issuances
- WHERE email = ?`,
- email,
- ).Scan(&issuedAt)
- if err == nil {
- return true, nil
- }
- if errors.Is(err, sql.ErrNoRows) {
- return false, nil
- }
- return false, fmt.Errorf("lookup trial signup issuance: %w", err)
-}
-
-func (s *TrialSignupStore) FindIssuedTrialConflict(email, company string) (*TrialSignupIssuanceConflict, error) {
- if s == nil {
- return nil, fmt.Errorf("trial signup store not configured")
- }
- email = normalizeTrialSignupEmail(email)
- if email == "" {
- return nil, nil
- }
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil, fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- return findTrialSignupIssuanceConflict(db, email, company, "")
-}
-
-func (s *TrialSignupStore) FindPendingVerificationByEmail(email string, now time.Time) (*TrialSignupRecord, error) {
- if s == nil {
- return nil, fmt.Errorf("trial signup store not configured")
- }
- email = normalizeTrialSignupEmail(email)
- if email == "" {
- return nil, nil
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil, fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- rec, err := loadTrialSignupRecord(db.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE email = ?
- AND verified_at IS NULL
- AND verification_expires_at >= ?
- ORDER BY created_at DESC
- LIMIT 1`,
- email,
- now.Unix(),
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return nil, nil
- }
- return nil, fmt.Errorf("load pending trial signup verification: %w", err)
- }
- return rec, nil
-}
-
-func (s *TrialSignupStore) IssueCheckoutToken(id string, issuedAt time.Time, ttl time.Duration) (string, error) {
- if s == nil {
- return "", fmt.Errorf("trial signup store not configured")
- }
- id = strings.TrimSpace(id)
- if id == "" {
- return "", ErrTrialSignupRecordNotFound
- }
- if ttl <= 0 {
- return "", fmt.Errorf("checkout token ttl is required")
- }
- rawToken, err := randomPrefixedToken()
- if err != nil {
- return "", fmt.Errorf("generate checkout token: %w", err)
- }
- tokenHash := hashTrialSignupToken(rawToken)
- issuedAt = issuedAt.UTC()
- expiresAt := issuedAt.Add(ttl)
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return "", fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- res, err := db.Exec(
- `UPDATE trial_signup_requests
- SET checkout_token_hash = ?,
- checkout_token_expires_at = ?
- WHERE request_id = ?
- AND verified_at IS NOT NULL`,
- tokenHash,
- expiresAt.Unix(),
- id,
- )
- if err != nil {
- return "", fmt.Errorf("store trial signup checkout token: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return "", fmt.Errorf("get checkout token rows affected: %w", err)
- }
- if affected == 0 {
- return "", ErrTrialSignupRecordNotFound
- }
- return rawToken, nil
-}
-
-func (s *TrialSignupStore) GetRecordByCheckoutToken(rawToken string, now time.Time) (*TrialSignupRecord, error) {
- if s == nil {
- return nil, ErrTrialSignupRecordNotFound
- }
- tokenHash := hashTrialSignupToken(rawToken)
- if tokenHash == "" {
- return nil, ErrTrialSignupVerificationInvalid
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil, ErrTrialSignupRecordNotFound
- }
- defer s.mu.Unlock()
-
- rec, err := loadTrialSignupRecord(db.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE checkout_token_hash = ?`,
- tokenHash,
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return nil, ErrTrialSignupVerificationInvalid
- }
- return nil, fmt.Errorf("load trial signup checkout token: %w", err)
- }
- if rec.VerifiedAt.IsZero() {
- return nil, ErrTrialSignupVerificationInvalid
- }
- if rec.CheckoutTokenExpiresAt.IsZero() || now.After(rec.CheckoutTokenExpiresAt) {
- return nil, ErrTrialSignupVerificationExpired
- }
- return rec, nil
-}
-
-func (s *TrialSignupStore) MarkTrialIssued(id string, now time.Time) error {
- if s == nil {
- return fmt.Errorf("trial signup store not configured")
- }
- id = strings.TrimSpace(id)
- if id == "" {
- return ErrTrialSignupRecordNotFound
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- tx, err := db.Begin()
- if err != nil {
- return fmt.Errorf("begin trial issuance tx: %w", err)
- }
- defer func() {
- if rollbackErr := tx.Rollback(); rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {
- log.Warn().Err(rollbackErr).Msg("Failed to rollback trial issuance transaction")
- }
- }()
-
- rec, err := loadTrialSignupRecord(tx.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE request_id = ?`,
- id,
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return ErrTrialSignupRecordNotFound
- }
- return fmt.Errorf("load trial signup request for issuance: %w", err)
- }
- if rec.VerifiedAt.IsZero() {
- return ErrTrialSignupVerificationInvalid
- }
-
- email := normalizeTrialSignupEmail(rec.Email)
- if email == "" {
- return ErrTrialSignupVerificationInvalid
- }
- conflict, err := findTrialSignupIssuanceConflict(tx, email, rec.Company, rec.ID)
- if err != nil {
- return fmt.Errorf("find trial issuance conflict: %w", err)
- }
- if conflict != nil {
- switch conflict.Kind {
- case trialSignupConflictEmail:
- return ErrTrialSignupEmailAlreadyUsed
- case trialSignupConflictDomain, trialSignupConflictPublicCompany:
- return ErrTrialSignupOrganizationUsed
- default:
- return ErrTrialSignupOrganizationUsed
- }
- }
- emailDomain := normalizeTrialSignupEmailDomain(email)
- companyKey := normalizeTrialSignupCompany(rec.Company)
-
- res, err := tx.Exec(
- `INSERT OR IGNORE INTO trial_signup_issuances (email, request_id, email_domain, company_key, issued_at)
- VALUES (?, ?, ?, ?, ?)`,
- email,
- rec.ID,
- emailDomain,
- companyKey,
- now.Unix(),
- )
- if err != nil {
- return fmt.Errorf("insert trial issuance: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return fmt.Errorf("get trial issuance rows affected: %w", err)
- }
- if affected == 0 {
- conflict, conflictErr := findTrialSignupIssuanceConflict(tx, email, rec.Company, rec.ID)
- if conflictErr != nil {
- return fmt.Errorf("lookup existing trial issuance: %w", conflictErr)
- }
- if conflict != nil {
- switch conflict.Kind {
- case trialSignupConflictEmail:
- return ErrTrialSignupEmailAlreadyUsed
- default:
- return ErrTrialSignupOrganizationUsed
- }
- }
- }
-
- if err := tx.Commit(); err != nil {
- return fmt.Errorf("commit trial issuance tx: %w", err)
- }
- return nil
-}
-
-func (s *TrialSignupStore) MarkRedemptionRecorded(requestID, orgID, returnURL, instanceToken, instanceHost string, now time.Time) error {
- if s == nil {
- return fmt.Errorf("trial signup store not configured")
- }
- requestID = strings.TrimSpace(requestID)
- orgID = normalizeTrialOrgID(orgID)
- returnURL = strings.TrimSpace(returnURL)
- instanceToken = strings.TrimSpace(instanceToken)
- instanceHost = strings.ToLower(strings.TrimSpace(instanceHost))
- if requestID == "" || returnURL == "" || instanceToken == "" || instanceHost == "" {
- return ErrTrialSignupRecordNotFound
- }
- now = now.UTC()
-
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return fmt.Errorf("trial signup store not configured")
- }
- defer s.mu.Unlock()
-
- rec, err := loadTrialSignupRecord(db.QueryRow(
- `SELECT request_id, org_id, return_url, instance_token, name, email, company, verification_expires_at, created_at, verified_at, checkout_token_expires_at, checkout_started_at, checkout_completed_at, checkout_token_hash, checkout_session_id, redemption_recorded_at
- FROM trial_signup_requests
- WHERE request_id = ?`,
- requestID,
- ))
- if err != nil {
- if errors.Is(err, sql.ErrNoRows) {
- return ErrTrialSignupRecordNotFound
- }
- return fmt.Errorf("load trial signup request for redemption: %w", err)
- }
- if rec.VerifiedAt.IsZero() {
- return ErrTrialSignupRecordNotFound
- }
- if normalizeTrialOrgID(rec.OrgID) != orgID {
- return ErrTrialSignupRecordNotFound
- }
- if strings.TrimSpace(rec.ReturnURL) != returnURL {
- return ErrTrialSignupRecordNotFound
- }
- if strings.TrimSpace(rec.InstanceToken) != instanceToken {
- return ErrTrialSignupRecordNotFound
- }
- recordHost, err := trialSignupReturnURLHost(rec.ReturnURL)
- if err != nil || recordHost != instanceHost {
- return ErrTrialSignupRecordNotFound
- }
-
- res, err := db.Exec(
- `UPDATE trial_signup_requests
- SET redemption_recorded_at = COALESCE(redemption_recorded_at, ?)
- WHERE request_id = ?`,
- now.Unix(),
- rec.ID,
- )
- if err != nil {
- return fmt.Errorf("mark trial redemption recorded: %w", err)
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return fmt.Errorf("get trial redemption rows affected: %w", err)
- }
- if affected == 0 {
- return ErrTrialSignupRecordNotFound
- }
- return nil
-}
-
-func (s *TrialSignupStore) DeleteExpired(now time.Time) error {
- if s == nil {
- return nil
- }
- s.mu.Lock()
- db := s.db
- if db == nil {
- s.mu.Unlock()
- return nil
- }
- defer s.mu.Unlock()
- _, err := db.Exec(
- `DELETE FROM trial_signup_requests
- WHERE verified_at IS NULL AND verification_expires_at < ?`,
- now.UTC().Unix(),
- )
- if err != nil {
- return fmt.Errorf("delete expired trial signup requests: %w", err)
- }
- return nil
-}
-
-func (s *TrialSignupStore) Close() {
- if s == nil {
- return
- }
- s.mu.Lock()
- defer s.mu.Unlock()
-
- select {
- case <-s.stopCleanup:
- default:
- close(s.stopCleanup)
- }
- if s.db != nil {
- if err := s.db.Close(); err != nil {
- log.Warn().Err(err).Msg("Failed to close trial signup store database")
- }
- s.db = nil
- }
-}
-
-func loadTrialSignupRecord(scanner interface {
- Scan(dest ...any) error
-}) (*TrialSignupRecord, error) {
- rec := &TrialSignupRecord{}
- var verificationExpiresAt, createdAt int64
- var verifiedAt, checkoutTokenExpiresAt, checkoutStartedAt, checkoutCompletedAt, redemptionRecordedAt sql.NullInt64
- if err := scanner.Scan(
- &rec.ID,
- &rec.OrgID,
- &rec.ReturnURL,
- &rec.InstanceToken,
- &rec.Name,
- &rec.Email,
- &rec.Company,
- &verificationExpiresAt,
- &createdAt,
- &verifiedAt,
- &checkoutTokenExpiresAt,
- &checkoutStartedAt,
- &checkoutCompletedAt,
- &rec.CheckoutTokenHash,
- &rec.CheckoutSessionID,
- &redemptionRecordedAt,
- ); err != nil {
- return nil, err
- }
- rec.VerificationExpiresAt = time.Unix(verificationExpiresAt, 0).UTC()
- rec.CreatedAt = time.Unix(createdAt, 0).UTC()
- if verifiedAt.Valid {
- rec.VerifiedAt = time.Unix(verifiedAt.Int64, 0).UTC()
- }
- if checkoutTokenExpiresAt.Valid {
- rec.CheckoutTokenExpiresAt = time.Unix(checkoutTokenExpiresAt.Int64, 0).UTC()
- }
- if checkoutStartedAt.Valid {
- rec.CheckoutStartedAt = time.Unix(checkoutStartedAt.Int64, 0).UTC()
- }
- if checkoutCompletedAt.Valid {
- rec.CheckoutCompletedAt = time.Unix(checkoutCompletedAt.Int64, 0).UTC()
- }
- if redemptionRecordedAt.Valid {
- rec.RedemptionRecordedAt = time.Unix(redemptionRecordedAt.Int64, 0).UTC()
- }
- return rec, nil
-}
-
-func hashTrialSignupToken(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return ""
- }
- sum := sha256.Sum256([]byte(raw))
- return hex.EncodeToString(sum[:])
-}
-
-func randomPrefixedToken() (string, error) {
- buf := make([]byte, 32)
- if _, err := rand.Read(buf); err != nil {
- return "", err
- }
- return trialSignupTokenPrefix + base64.RawURLEncoding.EncodeToString(buf), nil
-}
-
-func randomHex(n int) (string, error) {
- buf := make([]byte, n)
- if _, err := rand.Read(buf); err != nil {
- return "", err
- }
- return hex.EncodeToString(buf), nil
-}
-
-func normalizeTrialSignupEmail(email string) string {
- return strings.ToLower(strings.TrimSpace(email))
-}
-
-func normalizeTrialSignupEmailDomain(email string) string {
- email = normalizeTrialSignupEmail(email)
- at := strings.LastIndex(email, "@")
- if at == -1 || at == len(email)-1 {
- return ""
- }
- return strings.TrimSpace(email[at+1:])
-}
-
-func normalizeTrialSignupCompany(company string) string {
- raw := strings.ToLower(strings.TrimSpace(company))
- if raw == "" {
- return ""
- }
- raw = strings.ReplaceAll(raw, "&", " and ")
- raw = trialSignupNonAlnumPattern.ReplaceAllString(raw, " ")
- fields := strings.Fields(raw)
- if len(fields) == 0 {
- return ""
- }
- normalized := make([]string, 0, len(fields))
- for _, field := range fields {
- if _, noise := trialSignupCompanyNoiseTokens[field]; noise {
- continue
- }
- normalized = append(normalized, field)
- }
- if len(normalized) == 0 {
- return ""
- }
- return strings.Join(normalized, " ")
-}
-
-func isPublicTrialSignupEmailDomain(domain string) bool {
- _, ok := trialSignupPublicEmailDomains[strings.ToLower(strings.TrimSpace(domain))]
- return ok
-}
-
-func trialSignupReturnURLHost(raw string) (string, error) {
- host, err := pkglicensing.ValidateTrialActivationReturnURL(raw, "")
- if err != nil {
- return "", fmt.Errorf("invalid return url")
- }
- return host, nil
-}
-
-func findTrialSignupIssuanceConflict(
- queryable interface {
- QueryRow(query string, args ...any) *sql.Row
- },
- email, company, excludeRequestID string,
-) (*TrialSignupIssuanceConflict, error) {
- email = normalizeTrialSignupEmail(email)
- if email == "" {
- return nil, nil
- }
- excludeRequestID = strings.TrimSpace(excludeRequestID)
-
- requestID, err := queryIssuanceConflictRequestID(queryable,
- `SELECT request_id FROM trial_signup_issuances
- WHERE email = ? AND (? = '' OR request_id <> ?)
- LIMIT 1`,
- email, excludeRequestID, excludeRequestID,
- )
- if err != nil {
- return nil, err
- }
- if requestID != "" {
- return &TrialSignupIssuanceConflict{RequestID: requestID, Kind: trialSignupConflictEmail}, nil
- }
-
- domain := normalizeTrialSignupEmailDomain(email)
- if domain != "" && !isPublicTrialSignupEmailDomain(domain) {
- requestID, err = queryIssuanceConflictRequestID(queryable,
- `SELECT request_id FROM trial_signup_issuances
- WHERE email_domain = ? AND (? = '' OR request_id <> ?)
- LIMIT 1`,
- domain, excludeRequestID, excludeRequestID,
- )
- if err != nil {
- return nil, err
- }
- if requestID != "" {
- return &TrialSignupIssuanceConflict{RequestID: requestID, Kind: trialSignupConflictDomain}, nil
- }
- return nil, nil
- }
-
- companyKey := normalizeTrialSignupCompany(company)
- if companyKey == "" {
- return nil, nil
- }
- requestID, err = queryIssuanceConflictRequestID(queryable,
- `SELECT request_id FROM trial_signup_issuances
- WHERE company_key = ? AND company_key <> '' AND (? = '' OR request_id <> ?)
- LIMIT 1`,
- companyKey, excludeRequestID, excludeRequestID,
- )
- if err != nil {
- return nil, err
- }
- if requestID != "" {
- return &TrialSignupIssuanceConflict{RequestID: requestID, Kind: trialSignupConflictPublicCompany}, nil
- }
- return nil, nil
-}
-
-func queryIssuanceConflictRequestID(
- queryable interface {
- QueryRow(query string, args ...any) *sql.Row
- },
- query string,
- args ...any,
-) (string, error) {
- var requestID string
- err := queryable.QueryRow(query, args...).Scan(&requestID)
- if err == nil {
- return strings.TrimSpace(requestID), nil
- }
- if errors.Is(err, sql.ErrNoRows) {
- return "", nil
- }
- return "", err
-}
-
-func (s *TrialSignupStore) tableHasColumn(tableName, columnName string) (bool, error) {
- rows, err := s.db.Query(`PRAGMA table_info(` + tableName + `)`)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- for rows.Next() {
- var cid int
- var name, typeName string
- var notNull int
- var defaultValue any
- var pk int
- if err := rows.Scan(&cid, &name, &typeName, &notNull, &defaultValue, &pk); err != nil {
- return false, err
- }
- if strings.EqualFold(strings.TrimSpace(name), strings.TrimSpace(columnName)) {
- return true, nil
- }
- }
- return false, rows.Err()
-}
-
-func (s *TrialSignupStore) backfillTrialSignupIssuanceIdentities() error {
- rows, err := s.db.Query(`
- SELECT i.request_id, i.email, i.email_domain, i.company_key, COALESCE(r.company, '')
- FROM trial_signup_issuances i
- LEFT JOIN trial_signup_requests r ON r.request_id = i.request_id
- WHERE i.email_domain = '' OR i.company_key = ''
- `)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- type rowData struct {
- requestID string
- email string
- emailDomain string
- companyKey string
- company string
- }
- var updates []rowData
- for rows.Next() {
- var row rowData
- if err := rows.Scan(&row.requestID, &row.email, &row.emailDomain, &row.companyKey, &row.company); err != nil {
- return err
- }
- updates = append(updates, row)
- }
- if err := rows.Err(); err != nil {
- return err
- }
- for _, row := range updates {
- emailDomain := row.emailDomain
- if strings.TrimSpace(emailDomain) == "" {
- emailDomain = normalizeTrialSignupEmailDomain(row.email)
- }
- companyKey := row.companyKey
- if strings.TrimSpace(companyKey) == "" {
- companyKey = normalizeTrialSignupCompany(row.company)
- }
- if _, err := s.db.Exec(
- `UPDATE trial_signup_issuances
- SET email_domain = ?, company_key = ?
- WHERE request_id = ?`,
- emailDomain,
- companyKey,
- row.requestID,
- ); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/internal/cloudcp/trial_signup_store_test.go b/internal/cloudcp/trial_signup_store_test.go
deleted file mode 100644
index 7d52dc8f7b..0000000000
--- a/internal/cloudcp/trial_signup_store_test.go
+++ /dev/null
@@ -1,435 +0,0 @@
-package cloudcp
-
-import (
- "errors"
- "strings"
- "testing"
- "time"
-)
-
-func TestTrialSignupStoreMarkTrialIssuedEnforcesEmailUniqueness(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- firstToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(first): %v", err)
- }
- firstRecord, err := store.ConsumeVerification(firstToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification(first): %v", err)
- }
-
- secondToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Test User",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(second): %v", err)
- }
- secondRecord, err := store.ConsumeVerification(secondToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification(second): %v", err)
- }
-
- if err := store.MarkTrialIssued(firstRecord.ID, now); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
- if err := store.MarkTrialIssued(firstRecord.ID, now); err != nil {
- t.Fatalf("MarkTrialIssued(first repeat): %v", err)
- }
-
- used, err := store.HasIssuedTrialForEmail("[email protected]")
- if err != nil {
- t.Fatalf("HasIssuedTrialForEmail: %v", err)
- }
- if !used {
- t.Fatalf("expected issued email lookup to return true")
- }
-
- err = store.MarkTrialIssued(secondRecord.ID, now)
- if !errors.Is(err, ErrTrialSignupEmailAlreadyUsed) {
- t.Fatalf("MarkTrialIssued(second) error=%v, want %v", err, ErrTrialSignupEmailAlreadyUsed)
- }
-}
-
-func TestTrialSignupStoreMarkTrialIssuedEnforcesBusinessDomainUniqueness(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- firstToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Alice",
- Email: "[email protected]",
- Company: "Acme Inc.",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(first): %v", err)
- }
- firstRecord, err := store.ConsumeVerification(firstToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification(first): %v", err)
- }
- if err := store.MarkTrialIssued(firstRecord.ID, now); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
-
- conflict, err := store.FindIssuedTrialConflict("[email protected]", "Acme Holdings")
- if err != nil {
- t.Fatalf("FindIssuedTrialConflict: %v", err)
- }
- if conflict == nil || conflict.Kind != trialSignupConflictDomain {
- t.Fatalf("conflict=%#v, want business-domain conflict", conflict)
- }
-
- secondToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Bob",
- Email: "[email protected]",
- Company: "Acme Holdings",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(second): %v", err)
- }
- secondRecord, err := store.ConsumeVerification(secondToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification(second): %v", err)
- }
-
- err = store.MarkTrialIssued(secondRecord.ID, now)
- if !errors.Is(err, ErrTrialSignupOrganizationUsed) {
- t.Fatalf("MarkTrialIssued(second) error=%v, want %v", err, ErrTrialSignupOrganizationUsed)
- }
-}
-
-func TestTrialSignupStoreFindIssuedTrialConflictUsesCompanyForPublicEmailDomains(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- firstToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Alice",
- Email: "[email protected]",
- Company: "Pulse Labs Ltd.",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification(first): %v", err)
- }
- firstRecord, err := store.ConsumeVerification(firstToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification(first): %v", err)
- }
- if err := store.MarkTrialIssued(firstRecord.ID, now); err != nil {
- t.Fatalf("MarkTrialIssued(first): %v", err)
- }
-
- conflict, err := store.FindIssuedTrialConflict("[email protected]", "Pulse Labs")
- if err != nil {
- t.Fatalf("FindIssuedTrialConflict: %v", err)
- }
- if conflict == nil || conflict.Kind != trialSignupConflictPublicCompany {
- t.Fatalf("conflict=%#v, want public-company conflict", conflict)
- }
-
- noConflict, err := store.FindIssuedTrialConflict("[email protected]", "Different Company")
- if err != nil {
- t.Fatalf("FindIssuedTrialConflict(no conflict): %v", err)
- }
- if noConflict != nil {
- t.Fatalf("noConflict=%#v, want nil", noConflict)
- }
-}
-
-func TestTrialSignupStoreFindPendingVerificationByEmail(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- token, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- if strings.TrimSpace(token) == "" {
- t.Fatalf("expected raw token")
- }
-
- pending, err := store.FindPendingVerificationByEmail("[email protected]", now)
- if err != nil {
- t.Fatalf("FindPendingVerificationByEmail: %v", err)
- }
- if pending == nil {
- t.Fatal("expected pending verification record")
- }
-
- if _, err := store.ConsumeVerification(token, now); err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- pending, err = store.FindPendingVerificationByEmail("[email protected]", now)
- if err != nil {
- t.Fatalf("FindPendingVerificationByEmail after consume: %v", err)
- }
- if pending != nil {
- t.Fatalf("pending=%#v, want nil after consume", pending)
- }
-}
-
-func TestTrialSignupStoreCreateCheckoutRequestMarksRecordVerified(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- record := &TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- }
- if err := store.CreateCheckoutRequest(record); err != nil {
- t.Fatalf("CreateCheckoutRequest: %v", err)
- }
- if strings.TrimSpace(record.ID) == "" {
- t.Fatal("expected request id")
- }
- if record.VerifiedAt.IsZero() {
- t.Fatal("expected verified_at to be set immediately")
- }
-
- loaded, err := store.GetRecord(record.ID)
- if err != nil {
- t.Fatalf("GetRecord: %v", err)
- }
- if loaded.VerifiedAt.IsZero() {
- t.Fatal("expected persisted verified_at")
- }
- if loaded.Email != "[email protected]" {
- t.Fatalf("loaded.Email=%q, want %q", loaded.Email, "[email protected]")
- }
-}
-
-func TestTrialSignupStoreMarkCheckoutStartedOverwritesSessionBinding(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- record := &TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- }
- if err := store.CreateCheckoutRequest(record); err != nil {
- t.Fatalf("CreateCheckoutRequest: %v", err)
- }
- if err := store.MarkCheckoutStarted(record.ID, "cs_first", now); err != nil {
- t.Fatalf("MarkCheckoutStarted(first): %v", err)
- }
- if err := store.MarkCheckoutStarted(record.ID, "cs_second", now.Add(time.Minute)); err != nil {
- t.Fatalf("MarkCheckoutStarted(second): %v", err)
- }
-
- loaded, err := store.GetRecord(record.ID)
- if err != nil {
- t.Fatalf("GetRecord: %v", err)
- }
- if loaded.CheckoutSessionID != "cs_second" {
- t.Fatalf("checkout_session_id=%q, want %q", loaded.CheckoutSessionID, "cs_second")
- }
- if !loaded.CheckoutStartedAt.Equal(now.Add(time.Minute)) {
- t.Fatalf("checkout_started_at=%v, want %v", loaded.CheckoutStartedAt, now.Add(time.Minute))
- }
-}
-
-func TestTrialSignupStoreMarkRedemptionRecorded(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- if err := store.MarkCheckoutCompleted(record.ID, "cs_test_redeem", now); err != nil {
- t.Fatalf("MarkCheckoutCompleted: %v", err)
- }
-
- if err := store.MarkRedemptionRecorded(record.ID, "default", "https://pulse.example.com/auth/trial-activate", "tsi_test", "pulse.example.com", now); err != nil {
- t.Fatalf("MarkRedemptionRecorded(first): %v", err)
- }
- if err := store.MarkRedemptionRecorded(record.ID, "default", "https://pulse.example.com/auth/trial-activate", "tsi_test", "pulse.example.com", now.Add(time.Minute)); err != nil {
- t.Fatalf("MarkRedemptionRecorded(repeat): %v", err)
- }
-
- updated, err := store.GetRecord(record.ID)
- if err != nil {
- t.Fatalf("GetRecord(updated): %v", err)
- }
- if updated.RedemptionRecordedAt.IsZero() {
- t.Fatalf("expected redemption_recorded_at to be populated")
- }
- if !updated.RedemptionRecordedAt.Equal(now) {
- t.Fatalf("redemption_recorded_at=%v, want %v", updated.RedemptionRecordedAt, now)
- }
-}
-
-func TestTrialSignupStoreMarkRedemptionRecordedRejectsMismatchedReturnTarget(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
- if err := store.MarkCheckoutCompleted(record.ID, "cs_test_redeem", now); err != nil {
- t.Fatalf("MarkCheckoutCompleted: %v", err)
- }
-
- err = store.MarkRedemptionRecorded(record.ID, "default", "https://other.example.com/auth/trial-activate", "tsi_test", "other.example.com", now)
- if !errors.Is(err, ErrTrialSignupRecordNotFound) {
- t.Fatalf("MarkRedemptionRecorded error=%v, want %v", err, ErrTrialSignupRecordNotFound)
- }
-}
-
-func TestTrialSignupStoreIssueCheckoutTokenAndLookup(t *testing.T) {
- store, err := NewTrialSignupStore(t.TempDir())
- if err != nil {
- t.Fatalf("NewTrialSignupStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
-
- now := time.Unix(1710000000, 0).UTC()
- rawToken, err := store.CreateVerification(&TrialSignupRecord{
- OrgID: "default",
- ReturnURL: "https://pulse.example.com/auth/trial-activate",
- InstanceToken: "tsi_test",
- Name: "Owner",
- Email: "[email protected]",
- Company: "Pulse Labs",
- CreatedAt: now,
- VerificationExpiresAt: now.Add(trialSignupVerificationTTL),
- })
- if err != nil {
- t.Fatalf("CreateVerification: %v", err)
- }
- record, err := store.ConsumeVerification(rawToken, now)
- if err != nil {
- t.Fatalf("ConsumeVerification: %v", err)
- }
-
- checkoutToken, err := store.IssueCheckoutToken(record.ID, now, trialSignupVerificationTTL)
- if err != nil {
- t.Fatalf("IssueCheckoutToken: %v", err)
- }
- if checkoutToken == "" {
- t.Fatal("expected checkout token")
- }
-
- loaded, err := store.GetRecordByCheckoutToken(checkoutToken, now.Add(time.Minute))
- if err != nil {
- t.Fatalf("GetRecordByCheckoutToken: %v", err)
- }
- if loaded.ID != record.ID {
- t.Fatalf("loaded.ID=%q, want %q", loaded.ID, record.ID)
- }
- if loaded.CheckoutTokenHash == "" {
- t.Fatal("expected checkout token hash to be stored")
- }
- if loaded.CheckoutTokenExpiresAt.IsZero() {
- t.Fatal("expected checkout token expiry to be stored")
- }
-}
diff --git a/internal/cloudcp/url_helpers.go b/internal/cloudcp/url_helpers.go
new file mode 100644
index 0000000000..c88b6dc161
--- /dev/null
+++ b/internal/cloudcp/url_helpers.go
@@ -0,0 +1,20 @@
+package cloudcp
+
+import (
+ "net/url"
+ "strings"
+)
+
+func buildCPURL(baseURL, path string, query url.Values) string {
+ base := strings.TrimSpace(baseURL)
+ if base == "" {
+ return path
+ }
+ parsed, err := url.Parse(base)
+ if err != nil {
+ return path
+ }
+ parsed.Path = strings.TrimRight(parsed.Path, "/") + path
+ parsed.RawQuery = query.Encode()
+ return parsed.String()
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 3233601d34..587dcd3c9e 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -204,7 +204,7 @@ type Config struct {
TelemetryEnabled bool `envconfig:"PULSE_TELEMETRY" default:"true"` // Anonymous outbound usage telemetry enabled by default (install ID, version, resource counts, feature flags — opt out any time)
MultiTenantEnabled bool `envconfig:"PULSE_MULTI_TENANT_ENABLED" default:"false"` // Enable multi-tenant support
MetricsToken string `envconfig:"PULSE_METRICS_TOKEN" default:"" json:"-"` // Bearer token for /metrics endpoint (empty = unauthenticated)
- ProTrialSignupURL string `envconfig:"PULSE_PRO_TRIAL_SIGNUP_URL" default:""` // Hosted signup/checkout URL for starting Pulse Pro trials
+ ProTrialSignupURL string `envconfig:"PULSE_PRO_TRIAL_SIGNUP_URL" default:""` // Legacy hosted commercial base URL used for entitlement refresh compatibility
// Proxy authentication settings
ProxyAuthSecret string `envconfig:"PROXY_AUTH_SECRET"`
@@ -1071,7 +1071,7 @@ func load(initLogging bool) (*Config, error) {
cfg.ProTrialSignupURL = resolved
cfg.EnvOverrides[pkglicensing.ProTrialSignupURLEnvVar] = true
cfg.EnvOverrides["proTrialSignupURL"] = true
- log.Info().Str("url", resolved).Msg("Overriding Pulse Pro trial signup URL from environment")
+ log.Info().Str("url", resolved).Msg("Overriding hosted commercial base URL from environment")
} else {
log.Warn().Str("value", trialSignupURL).Msg("Invalid PULSE_PRO_TRIAL_SIGNUP_URL value, ignoring")
}
diff --git a/internal/config/config_load_env_test.go b/internal/config/config_load_env_test.go
index 9fb064525d..29178c09ee 100644
--- a/internal/config/config_load_env_test.go
+++ b/internal/config/config_load_env_test.go
@@ -31,7 +31,7 @@ func TestLoad_EnvOverrides_Detailed(t *testing.T) {
"DISCOVERY_DIAL_TIMEOUT_MS": "2000",
"ALLOWED_ORIGINS": "https://allowed.com",
"PULSE_PUBLIC_URL": "https://public.pulse.com",
- "PULSE_PRO_TRIAL_SIGNUP_URL": "https://billing.example.com/start-pro-trial?source=test",
+ "PULSE_PRO_TRIAL_SIGNUP_URL": "https://billing.example.com/commercial-base?source=test",
"NODE_ENV": "production", // Ensure valid origins not defaulted to localhost
}
@@ -69,7 +69,7 @@ func TestLoad_EnvOverrides_Detailed(t *testing.T) {
// Misc
assert.Equal(t, "https://allowed.com", cfg.AllowedOrigins)
assert.Equal(t, "https://public.pulse.com", cfg.PublicURL)
- assert.Equal(t, "https://billing.example.com/start-pro-trial?source=test", cfg.ProTrialSignupURL)
+ assert.Equal(t, "https://billing.example.com/commercial-base?source=test", cfg.ProTrialSignupURL)
assert.True(t, cfg.EnvOverrides["PULSE_PRO_TRIAL_SIGNUP_URL"])
}
@@ -88,7 +88,7 @@ func TestLoad_EnvOverrides_Invalid(t *testing.T) {
assert.NotEqual(t, "invalid_env", cfg.Discovery.EnvironmentOverride)
}
-func TestLoad_EnvOverrides_InvalidProTrialSignupURL(t *testing.T) {
+func TestLoad_EnvOverrides_InvalidHostedCommercialBaseURL(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
t.Setenv("PULSE_PRO_TRIAL_SIGNUP_URL", "javascript:alert(1)")
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 3514b3e7ee..db31e9d35f 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -31,6 +32,18 @@ func TestLoad_Defaults(t *testing.T) {
assert.Equal(t, tmpDefault, cfg.DataPath)
}
+func TestLoad_DefaultHostedCommercialBaseURLAvoidsRetiredTrialPath(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+ t.Setenv("PULSE_PRO_TRIAL_SIGNUP_URL", "")
+
+ cfg, err := Load()
+ require.NoError(t, err)
+
+ if strings.Contains(cfg.ProTrialSignupURL, "start-pro-trial") {
+ t.Fatalf("ProTrialSignupURL=%q must not default to retired trial signup route", cfg.ProTrialSignupURL)
+ }
+}
+
func TestResolveRuntimeDataDir(t *testing.T) {
tmpDefault := t.TempDir()
prevDefault := defaultDataDir
diff --git a/pkg/licensing/upgrade.go b/pkg/licensing/upgrade.go
index 1ea1acf01a..c8667abdc8 100644
--- a/pkg/licensing/upgrade.go
+++ b/pkg/licensing/upgrade.go
@@ -9,19 +9,20 @@ import (
// DefaultUpgradeURL is used when no feature-specific URL mapping exists.
const DefaultUpgradeURL = "https://pulserelay.pro/pricing?utm_source=pulse&utm_medium=app&utm_campaign=upgrade"
-// DefaultProTrialSignupURL is the hosted signup/checkout entrypoint for Pulse Pro trials.
-const DefaultProTrialSignupURL = "https://cloud.pulserelay.pro/start-pro-trial?utm_source=pulse&utm_medium=app&utm_campaign=trial_signup"
+// DefaultProTrialSignupURL is the legacy hosted commercial base URL used by
+// compatibility paths that derive hosted entitlement refresh endpoints.
+const DefaultProTrialSignupURL = "https://cloud.pulserelay.pro"
// DefaultPulseAccountPortalURL is the authenticated Pulse Account portal entrypoint.
const DefaultPulseAccountPortalURL = "https://cloud.pulserelay.pro/portal"
-// ProTrialSignupURLEnvVar overrides the hosted signup URL for Pulse Pro trials.
+// ProTrialSignupURLEnvVar overrides the legacy hosted commercial base URL.
const ProTrialSignupURLEnvVar = "PULSE_PRO_TRIAL_SIGNUP_URL"
// PulseAccountPortalURLEnvVar overrides the Pulse Account portal URL.
const PulseAccountPortalURLEnvVar = "PULSE_ACCOUNT_PORTAL_URL"
-// ResolveProTrialSignupURL returns the canonical hosted signup URL for Pulse Pro trials.
+// ResolveProTrialSignupURL returns the canonical legacy hosted commercial base URL.
// Invalid overrides are ignored and the default URL is returned.
func ResolveProTrialSignupURL(override string) string {
if normalized, ok := validateExternalUpgradeURLOverride(override); ok {
@@ -39,7 +40,7 @@ func ResolvePulseAccountPortalURL(override string) string {
return DefaultPulseAccountPortalURL
}
-// ProTrialSignupURL returns the default hosted signup URL for Pulse Pro trials.
+// ProTrialSignupURL returns the default legacy hosted commercial base URL.
func ProTrialSignupURL() string {
return DefaultProTrialSignupURL
}
diff --git a/pkg/licensing/upgrade_test.go b/pkg/licensing/upgrade_test.go
index f38b12cdfe..2a49175d9f 100644
--- a/pkg/licensing/upgrade_test.go
+++ b/pkg/licensing/upgrade_test.go
@@ -1,6 +1,9 @@
package licensing
-import "testing"
+import (
+ "strings"
+ "testing"
+)
func TestResolveProTrialSignupURL_DefaultWhenUnset(t *testing.T) {
if got := ResolveProTrialSignupURL(""); got != DefaultProTrialSignupURL {
@@ -8,8 +11,14 @@ func TestResolveProTrialSignupURL_DefaultWhenUnset(t *testing.T) {
}
}
+func TestResolveProTrialSignupURL_DefaultIsHostedCommercialBase(t *testing.T) {
+ if strings.Contains(DefaultProTrialSignupURL, "start-pro-trial") {
+ t.Fatalf("DefaultProTrialSignupURL=%q must not point at retired trial signup route", DefaultProTrialSignupURL)
+ }
+}
+
func TestResolveProTrialSignupURL_UsesValidOverride(t *testing.T) {
- const override = "https://example.com/start-pro-trial?src=test"
+ const override = "https://example.com/commercial-base?src=test"
if got := ResolveProTrialSignupURL(override); got != override {
t.Fatalf("ResolveProTrialSignupURL() = %q, want %q", got, override)
@@ -17,7 +26,7 @@ func TestResolveProTrialSignupURL_UsesValidOverride(t *testing.T) {
}
func TestResolveProTrialSignupURL_AllowsLoopbackHTTPOverride(t *testing.T) {
- const override = "http://127.0.0.1:8080/start-pro-trial?src=test"
+ const override = "http://127.0.0.1:8080/commercial-base?src=test"
if got := ResolveProTrialSignupURL(override); got != override {
t.Fatalf("ResolveProTrialSignupURL() = %q, want %q", got, override)
@@ -29,8 +38,8 @@ func TestResolveProTrialSignupURL_RejectsInvalidOverrides(t *testing.T) {
"relative/path",
"javascript:alert(1)",
"https://",
- "http://192.168.1.20/start-pro-trial",
- "ftp://example.com/start-pro-trial",
+ "http://192.168.1.20/commercial-base",
+ "ftp://example.com/commercial-base",
}
for _, tc := range testCases {