/vivreal-knowledge:vivreal-secure-api-knowledgefrom vivreal-knowledge
Use when working in VR_Secure_API, Vivreal's authenticated-ops backend (NEXT_PUBLIC_SECURE_URL) for groups, sites, billing, profiles, roles, Square and Shopify tokens, template instantiation, domains and site analytics. Covers the SAM stack and its websocket and media-CDN siblings, instantiateTemplateWorker, the scheduled jobs, `dbKey`-query-param routing (NOT `key`), the 7-step add-a-route checklist (502 if the SAM event is missed), Stripe downgrade preflight, overage and spending caps, the payments-provider mutex, tier-quotas sentinels (-1 unlimited / 0 no access), encrypted creds, owner/admin gates, and the cross-tenant IDOR fix pattern. Triggers on: VR_Secure_API, group management, site creation, billing, downgrade preflight, profileSwitch, overage billing, spending cap, createSites, instantiateTemplate, domain transfer, dbKey, Square refresh, Shopify refresh, featureFlags, pageFields, withSiteRole, domain renewal. Source of truth: `VR_Secure_API` `CLAUDE.md` (and the docs it links) at `origin/stable`.
Trending skills
7-day visitors to each skill page
Ships in vivreal-knowledge. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Cross-repo flows, decisions and maps: the vivreal-hq dev docs under ${VIVREAL_REPOS}/vivreal-hq/docs/dev-docs/, starting at 03-use-cases/U3-how-studio-works.md, 03-use-cases/U20-changing-plans.md, 03-use-cases/U14-domains-search-purchase-renewal.md; npm run docs:route -- "site save" from vivreal-hq names the rest. This skill and the repo's CLAUDE.md own the repo's internals.
Using this skill. It is loaded into the caller's own context; there is no expert agent to dispatch. Cite file:line at the deploy line's SHA for anything you act on, and re-derive any count or roster from source before you rely on it.
Source of truth: VR_Secure_API CLAUDE.md (and the docs it links) at origin/stable.
Last synced: 2026-10-28 against origin/stable at 0d955d82 (tag v2.23.1; read the tag; per-skill baseline in vivreal-skills scripts/skill-sources.json)
The authenticated-ops backend: group/team mgmt, site creation+deploy+template instantiation, Stripe billing/subscriptions/overage, domain purchase+transfer, Square token lifecycle, profile switching, roles, AI agent, per-site analytics reads. Maps to NEXT_PUBLIC_SECURE_URL. Express + serverless-express on Lambda (Node 22 on every function since 2026-10-02; arm64), JavaScript, MongoDB, Cognito JWT, SAM. Read CLAUDE.md at origin/stable for full route lists (test/unit/claudeMdClaims.test.js binds its function counts and runtime claim to the generated template).
Roster (read 2026-10-15 from the cloudformation/ fragments at origin/stable; re-derive it): AgentFunction, AlarmVerifierFunction, AnalyticsSnapshotFunction, BillingAndSubscriptionFunction, CampaignScheduleFireFunction, CreateAndJoinGroupFunction, CreateSitesFunction, GetGroupInformationFunction, InstantiateTemplateWorkerDlqConsumerFunction, InstantiateTemplateWorkerFunction, ParkedSignupsFunction, PaymentsDrainTeardownFunction, ShopifyTokenRefreshFunction, SocialGrantProbeFunction, SquareRefreshOneFunction, SquareTokenRefreshFunction, TenancyDetectorFunction, UpdateGroupFunction, UserAndAuthFunction, WebhookDeliveryFunction. QuotaReconcilerFunction shipped and was RETIRED the same day (2026-09-23). The repo also deploys websocket/cfn-template.yaml (4 functions, websocket.yml) and cloudformation/media-cdn.yaml (1 Lambda@Edge, media-cdn.yml), so a fleet-wide count spans three stacks. cloudYamls/allRoutes.packaged.yaml is build output: never count from it and never edit it.
Per function, in more detail: userAndAuth (profile switch, email, logout, email update now fails closed on Cognito ListUsers truncation and rejects an email held by another user), billingAndSubscription (Stripe checkout/portal/webhooks/preflight/overage), createAndJoinGroup, createSites (templates + template instantiation, Route53, domain purchase/transfer, Step Functions, WebSockets, most files + AWS integrations; 2048MB/60s since the instantiation work), getGroupInformation (read-only + admin attribution + GET /api/analytics/site/traffic; serializes overQuotaSinceCancellation + derived usage.{cdn,api,agent}.{pctOfQuota,nearQuota,overQuota}), updateGroup (members, roles, API keys, integrations, overage toggle, featureFlags, refreshSocialProfile), agent (src/agent/, the retired in-app agent: still deployed, refused on every tier), webhookDelivery (SQS consumer, HMAC-signed outbound webhooks), analyticsSnapshot (EventBridge cron(0 6 * * ? *)), squareTokenRefresh (daily sweep cron), squareRefreshOne (invoke-only, cross-stack target for VR_Client_API's squareTokenGuard), instantiateTemplateWorker (no HTTP route; direct-invoked by createSites' instantiateTemplate via the INSTANTIATE_TEMPLATE_WORKER_LAMBDA env; 1024MB/900s; own DLQ + InstantiateTemplateWorkerErrorsAlarm), instantiateTemplateWorkerDlqConsumer (InstantiateTemplateWorkerDlqConsumerFunction; consumes the worker's OnFailure DLQ; own webpack entry + SAM function; marks hard-killed final-attempt sites failed from the destination envelope; partial-batch semantics, poison messages dropped), ShopifyTokenRefreshFunction (NEW, daily sweep cron mirroring the Square token-refresh pattern), and AlarmVerifierFunction (NEW, sweeps CloudWatch alarms to verify SNS delivery actually fired, guarding against a silently degraded alerting pipeline). The websocket stack (websocket/cfn-template.yaml, the only websocket template since template.yaml was deleted) is separate, never count its functions in the main roster. The two v5 functions are invoke-only targets of one-time EventBridge Scheduler entries with FIXED names (@shared/scheduleTargets books against them): paymentsDrainTeardown (vr-payments-drain-<groupID>-<provider>, revokes the old payments provider at drainUntil) and campaignScheduleFire (vr-campaign-<campaignID>, re-checks the booking and dispatches through dispatchCampaign.js). The functions with WebSocket integration are agent, createAndJoinGroup, createSites and updateGroup. socialGrantProbe is a daily cron that asks Facebook and X whether a stored grant is still good and marks dead ones expired (the same contract as VR_CMS_API's markSocialAccountExpired). Shared: encryptionUtils.js (AES-256-GCM for integration creds), handleHBRoutes.js, socket.js, auditLog.js. Tenant placement no longer has a file here at all: it moved into @hillbombcreations/tenant-db, because one decision gets one implementation.
A cross-tenant IDOR class was fixed: tenant-scoped {_id, groupID} filters at the service layer AND req.validatedGroup precedence at the controller layer (a query/body-supplied groupID could previously diverge from the membership-validated group). Any new mutation route must scope BOTH layers. errorHandler now forwards err.code as errorCode on non-5xx responses, the portal's CancelFlow retention-offer UI depends on reading it. Also shipped this window: a featureFlags route allowlist flip, a last-admin guard on role/removal ops, an idempotency-key allowlist fix, account self-serve deletion, and video-transcode bounding. Test suite is now 100/100/100/100 coverage with a husky pre-push gate, this repo has no GitHub Actions test workflow, so the pre-merge review + the local husky gate are the only checks before code lands on main. Merging to main is not a prod deploy (release train, see below), it only ships once promoted to stable. The consolidated prod-bug punch list (portal + all backends, fixed vs still-open) lives at Vivreal_Portal_Mobile/docs/projects/portal-frontend-testing-strategy/prod-bugs-found.md.
Prod serves stable, never main; promote order: CMS first, Secure second, portal last, each a dispatched promote (nothing ships without a dispatch). The model (cut, promote, backport as a patch, rollback needing a manual lambda_api.yml run) is in vivreal-infra:vivreal-lambda references/deploy.md; this repo's runbook is docs/RELEASE.md.
withSiteRole (src/createSites/scripts/requireSiteManagerRole.js), applied at route registration in src/createSites/api/index.js: delete a site, rename a subdomain, connect or remove a custom domain, order or cancel a domain, attach, detach, transfer. POST /deploySite and POST /instantiateTemplate are gated too (Secure CLAUDE.md:608-700).createCheckoutSession checks requireGroupBillingRole on the group the controller operates on, and createCustomerPortalSession compares the requested Stripe customer to the verified custom:sID claim, closing an IDOR into any customer's invoices (vivreal-hq docs/projects/shipped-ledger.md, 2026-09-22 evening)./domain/:domainId/registrant, /domain/:domainId/renewal). CreateSitesFunction's role needed a scoped Vivreal-CreateSites-Route53Domains-Policy (#321) for those and for the already-live transfer-out, which had been failing on implicitDeny (ledger 2026-10-04 02:20Z)./tenant/integrations/purgeAccount, invoke-only). See vivreal-social-sync.syncIntegration renews a long-lived Instagram token inside its last 7 days and used to forward the OLD one to CMS.squareTokenRefresh: daily rate(24 hours) sweep refreshing tokens <14 days from Square's 30-day hard expiry; 36h dead-man + Errors≥1 alarms.squareRefreshOne: no route/schedule; resource-based AWS::Lambda::Permission for VR_Client_API's role (SquareRefreshOneInvokerRoleArn), synchronous single-account refresh.updateIntegrations.js + oauthService.js:storeTokens throw PaymentsProviderAlreadyActive.src/shared/square/revokeSquareToken.js. The featureFlags.squareStorefront gate is GONE platform-wide (flag retired from ALLOWED_FLAGS). PAYMENTS_WRITE added to the OAuth scope list, CreatePaymentLink 403s INSUFFICIENT_SCOPES without it.<ssm-prefix>/shared/square-env = production. Existing sandbox-connected accounts are dead against the production app, the refresh sweep marks them expired; merchants must re-OAuth.Quotas live in @hillbombcreations/tier-quotas. Sentinel scheme: -1 unlimited, 0 no access
(fail closed), >0 a cap, read through isUnlimited(<0), hasAccess(!== 0) and
getEffectiveLimit. The old isUnlimitedQuota(0) == unlimited inversion is gone, and 0 now
genuinely denies rather than sitting as a dead gate.
Read the tier ladder and every quota number from src/tierQuotas.ts on the package deployed
line. Do not quote one from here, and do not trust a remembered one. Three things have moved
under this file before: a tier was retired and folded into another, the alias table that used to
forgive its old spellings was then deleted (so a retired tier id now normalises to free rather
than erroring, which is a silent downgrade rather than a crash), and the agent-action allowance
changed by an order of magnitude in one release. A stored group document still carrying a retired
tier id is the case to think about: nothing rewrites it when a package folds a tier.
dbKey (NOT key)Secure reads req.query.dbKey, CMS reads key. The portal proxy must set dbKey explicitly for Secure routes. dynamicDb.js pools per-tenant connections (maxPoolSize=3). mainDb Vivreal holds group metadata. Never filter mainDb by groupName, use { _id: ObjectId(groupID) } (shell form; in Node write new ObjectId(groupID), bson 6 throws without new). { key } takes the group's slug, never dbKey: dbKey is the tenant database name (pod_01, pod_02), no group's key equals it, so { key: dbKey } returns null.
services/foo.js → 2. services/index.js → 3. api/controllers/foo.js (set req.resData) → 4. api/controllers/index.js → 5. scripts/validators.js (Joi) → 6. api/index.js (handleHBRoutes) → 7. cloudformation/<lambda>.yaml API Gateway event.Step 7 is a hard rule. Secure (like Client) registers one explicit API Gateway event per route, there is no catch-all {proxy+} integration (CMS no longer does this: since CMS #266 its routes live in base.yaml's route list, see vivreal-cms-api-knowledge). An Express route the gateway has no event for is unreachable: the request falls through and fails, 502 post-deploy here (CMS surfaces the same miss as a 403; Client rejects it at the edge). Always add the event in the cloudformation/ fragment; cloudYamls/allRoutes.yaml is generated by scripts/merge-template.js, never edit it directly. (Cross-repo rule + why Main API is exempt: vivreal-lambda deploy reference + vivreal-auth-architecture.)
GET /api/billing/preflightDowngrade), recounts collection_objects + webhooks via tenant connection, compares to target tier quotas, returns { ok, violations[], currentTier, targetTier }. Downgrade to a 0-access target (e.g. free's webhooks/agentActions 0) is now a preflight violation. Re-used by createCheckoutSession as a defence-in-depth gate (400 with violations on reject). Opportunistically heals entries.totalSize drift.handleSubscriptionEnd.js), demotes to free (it no longer writes the 6 tier-driven quota fields, they derive live from the tier), sets frozen:true + persists overQuotaSinceCancellation {violations, setAt} when over-limit; getGroupInfo serializes it → drives the portal frozen/over-quota banner. Webhook-order safe: lookup by stripeSubscriptionID misses (no-op) when cancellation is the side-effect of an in-progress tier change.STRIPE_PORTAL_CONFIGURATION_ID disables subscription_update so tier changes route through the preflight-gated Manage Plan page. Bootstrap is a manual one-time script.overageBilling.enabled + the tier default spending cap (DEFAULT_SPENDING_CAP; grandfathered if the prior tier was overage-eligible, enterprise excluded); toggle via NEW PUT /api/group/overageBilling (toggleOverageBilling.js, native-driver persist). createCheckoutSession discloses overage + cap in Stripe custom_text. handleInvoiceCreated.js adds Stripe invoice items at the tier-quotas OVERAGE_RATES (CDN $0.50/GB, API $0.005/call, agent $0.05/action); the overageBilling.lastInvoice snapshot persists via the native driver, and a deterministic per-(invoice,bucket) Stripe idempotency key stops duplicate charges on invoice.created retries; fails safe (undercharge not overcharge). The old "overageBilling + stripeSubscriptionID UNDECLARED in strict groupSchema" gotcha is RESOLVED by schemas 1.27.0, which declares dbKey, stripeSubscriptionID, subscriptionStatus, subscriptionCadence, currentPeriodEnd, overageBilling{enabled,spendingCap,lastInvoice}, scheduledTierChange, cancellation, pauseCollection, retentionDiscount. The native-driver write is retained DELIBERATELY (spendingCap is Mixed with dynamic bucketCaps.<bucket> keys), not because of stripping. featureFlags is declared in schemas 1.29.0 (strict:false sub-schema, only aiActionsEnabled declared), though updateFeatureFlags.js still writes via the native driver.billingAndSubscription/services/subscription/{cancelSubscription,pauseSubscription,reactivateSubscription,applyRetentionDiscount}.js, gated by requireGroupBillingRole.js; routes POST /api/billing/{cancelSubscription,pauseSubscription,reactivateSubscription,applyRetentionDiscount} + releaseScheduledChange. Cancellation is period-end, never immediate (cancel_at_period_end + cancellation.{requestedAt,effectiveAt,reason,feedback}; demotion happens in handleSubscriptionEnd). Pause does NOT set frozen (D9; frozen is the end-of-subscription state, and VR_Client_API serves a frozen site READ ONLY through frozenPolicy.js, refusing checkout, contact forms and writes); CMS blocks writes on a future pauseCollection.resumesAt (GroupPaused 403). One pause per 12 months, anchored on pauseCollection.lastPausedAt. Retention: coupon retention_save_30_3mo (30% off, repeating 3 months), RETENTION_COUPON_ID via SSM <ssm-prefix>/shared/stripe-retention-coupon-id, once per group guarded on retentionDiscount.appliedAt (NOT Stripe's discount list, that only reports currently-applied discounts); deliberately no max_redemptions. NY GBL 527-a imposes an advance-notice obligation before any price change.createSiteCollectionData is now site-doc-only (~p95 <5s); collection seeding moved to Vivreal_EventHandler/seedCollections (first Step Function state) to fix a 504. Keep manifests in templates/*.manifest.js synced with EventHandler. Blank sites: blank-template naming + explicit POST /api/deploySite first-deploy trigger (EventHandler short-circuits seeding on blank templateType).updateSiteValues, JSON body limit raised 100kb→512kb, logo included in mediaFields. Round 2: structural caps (20 top-level menuItems, 8 children, 6 footer columns, 20 links) now validate at the TOP of the service, before ANY side effect, previously they ran AFTER S3 deletions / media promotion / mediaFiles inserts / mediaUsage $inc, so one over-cap save with fresh media stranded promoted objects. navigation.menuItems[*].children capped server-side at 8 (lockstep with the portal's Studio/LeftRail/chrome/menuLimits.ts maxChildren). updateSiteValues also accepts the Studio favicon override + chrome subsystems (announcement, strips, floating CTA, motion preset) + footerNewsletter.preupload- to groupObjects/ then DELETES the source, one upload referenced from TWO paths promoted the first and destroyed the object (silent, HTTP 200, CloudFront masking it for hours; broke a live customer site). The guard lives in the shared promotion path used by /migrate, /template, the instantiation worker, and the Studio.StartJobCommand wrote deployment.status 'deploying' with NO completion path (only the SFN's MarkSiteLive/MarkSiteFailed write terminal status), so every redeploy hung "Publishing your site" forever. Uses deploySite.js's execution-input contract; jobType RETRY <jobId> becomes a fresh RELEASE of the channel branch. redeploySite also promotes hero carousel slides.createSiteCollectionData inserts: name, domainInformation, deployment{status:'deploying'}, siteInfo{templateType,mode}, key (slugified siteName), groupID, pages (empty unless the portal supplies them), collectionGroups:[], homeSections:[], integrationsUsed (['stripe'] for ecommerce, else []), businessInfo, socialLinks, siteDetails{schema,values} (service createSiteCollectionData.js). The EventHandler seedCollections step backfills pages + collectionGroups. The full schema (Vivreal-Schemas/schemas/siteSchema.js) also carries deployment{status,message,errorMessage,updatedAt,appId}, domainInformation{domain,subdomain,live_url,pendingCustomDomain,purchasedDomain{...}}, pages[].blocks[], collectionGroups[] (CollectionGroupRef = name+id), deprecated homeSections[], navigation{}, footer{}, emailPopup, businessInfo{}, archived.POST /api/instantiateTemplate + GET /api/siteTemplates (createSites) create a placeholder site then async-invoke instantiateTemplateWorker, which runs @hillbombcreations/site-loader's instantiateBlueprint() and calls markFailed() on renderer-guard refusal / blueprint fetch / loader error, debug via the worker DLQ + InstantiateTemplateWorkerErrorsAlarm; hard-killed final attempts are marked failed by instantiateTemplateWorkerDlqConsumer from the DLQ destination envelope. instantiateTemplate is exempt from the generic idempotency response cache; the worker strips the Bearer scheme before handing the token to the loader. site_templates has an ops seed script. Promote/chrome-media re-staging fixed (navigation + footer + page.cta media descriptors; page-media promotion parallelized).durableRunState.js: loadRunState (reads sites.instantiation.runState; siteId always forced for dedupe-tag stability) + createRunStatePersister (serialized latest-wins Mongo write chain fed by the loader's synchronous onStateChange, drained in BOTH success and catch paths, {strict:false}). A deadline watchdog throws RetryableInstantiationError at remaining-90s from inside onProgress/onStateChange, never Promise.race (that would abandon the loader in a frozen container). instantiation.attempts $inc per invoke, MAX_ATTEMPTS=2; guard refusals stay terminal; transient failures rethrow for Lambda async retry. respondToExistingInstantiation resets attempts and resumes from persisted checkpoints instead of re-seeding; callDeploySite is skipped when deployment.appId is already set. YAML MaximumRetryAttempts 0→1 (kept below MAX_ATTEMPTS because the forwarded IdToken lives ~1h).agentActions is 0 on every tier, so executeAgent refuses and nothing an owner sees calls it; the agent function and its router.js, transcript.js, tools/policy.js and siteComposeTools.js still deploy. Do not treat aiSiteEditing or agentActions as a claimable feature or a gap to fix. The AI offering is VR-MCP-Server (canUseMcp, metered in mcpToolCalls). In copy: "AI agent", never "assistant" or a model name.POST /api/domain/transfer + POST /api/domain/transfer/resend-auth (createSites). Charge-before-transfer (orderType:'transfer'); the domainPurchase webhook routes checkout.session.completed to the DOMAIN_TRANSFER_SAGA_ARN Step Function when orderType==='transfer'; resend cross-invokes EventHandler resendTransferAuthorization (RESEND_TRANSFER_AUTH_LAMBDA env). W9 bundle: free first-year domain on the annual paid plans (read which from the package), catalog price ≤$25, once per group (bundleApplied flag; isDomainBundleEligible() in tier-quotas).POST /api/group/refreshSocialProfile (updateGroup) self-heals stale TikTok avatars, refreshing the token first. Meta tenant data is purged on disconnect; the audit event routes by derived dbKey.updateCompanyInfo distinguishes full-save vs dismiss-only (dotted $set); companyInfo is in v1 getGroupInfo. Push prefs: team categories (content/sites/team/agent) opt-out/default-on, outreach keys opt-in; category = preference filter (fail-open); cross-tenant subscribe hole closed with a membership 403 guard; staleCallDigest + bookingScope pref types.hb-api-secrets onto <secret-prefix>/secure-api + shared <secret-prefix>/{core,stripe,social-oauth,github-app,vapid} + <ssm-prefix>/{shared,secure-api}/* SSM. Env var names/values unchanged.audit_logs collection (each row stamped expiresAt from the group's tier, reaped by a TTL index), from a large and growing set of services, and the audit write routes by the stored placement (resolvePlacement(group)), not by group.key. Count the emitters rather than quoting a number. No content versioning here; that is CMS.enc:v1: prefix); plaintext fallback for pre-migration keys. Stripe restricted-key validation: validateIntegrationCreds() probes stripe.products.list({limit:1}) (not accounts.retrieve), classifying via @shared/stripeCredentialError: 401→StripeKeyInvalid (400), 403→StripeKeyInsufficientScope (400 + permission checklist), network/5xx/429→StripeValidationUnavailable (503); social types still return true (Phase 1). An omitted active now preserves current state instead of silently deactivating + firing the zero-object teardown; checkIntegrationObjects fails closed (503) on Lambda-invoke errors.unauthorized_scope); fetchLinkedInProfile restored to the /v2/me + networkSizes + organizationAcls cascade, liveness probe back to /v2/me, refreshLinkedInProfile retained. storeTokens race-recovery bug FIXED: it projected {_id, active} on the group ROOT but active lives on the embedded integrations[] element, always undefined, so isActivation was true on EVERY race (double-incremented integrationUsage.totalSize, spurious PaymentsProviderAlreadyActive, duplicate notification). Denied-OAuth branch bounded + event.extra telemetry gap closed. Sentry beforeSendLog URL scrub had a quadratic ReDoS (512KB → 92s, synchronous), fixed with a 4096-char per-value cap (truncate-then-scrub) + non-backtracking scan, plus credential scrubbing.group.dbKey is written once at creation by choosePlacementForNewGroup() and read back by resolvePlacement(group) (@hillbombcreations/tenant-db/placement), which throws PlacementMissingError when it is absent or unroutable. The six derive implementations are deleted; a grep hit on the name is a comment recording the removal.bucketOf(group) (src/shared/groupBucket.js): the stored group.bucket wins, else ${group.type}-${group.key}, and it throws rather than touch undefined-undefined. New groups store bucket at creation, named from a pre-generated _id. Never assume a vivreal- prefix./api/admin/* routes (count the Path: /api/admin events in cloudformation/, never quote a number: they sit in getGroupInformation.yaml and, for the four admin push routes, userAndAuth.yaml) use MyAdminCognitoAuthorizer, the dedicated admin pool (Vivreal-Admin-Identity, MFA), so a customer-pool token is rejected at the gateway there. One exception on purpose: PUT /api/admin/groups/{groupID}/prospect takes the DEFAULT (customer pool) authorizer, because the site loader signs in there and sends no x-user-ctx; its controller gates on ADMIN_EMAILS. Read each event's Auth block before assuming the pool. PUT /api/group/featureFlags accepts either pool; every other route inherits the customer pool.iam simulate-principal-policy on the role (the granted actions allowed, a control implicitDeny) is only a PRE-CHECK: a simulation evaluates the resource ARN and context keys you hand it, and twice in v7 it passed grants the real call then denied. The proof of a grant is the first real call (vivreal-infra:vivreal-iam-secrets).origin/stable 0d955d82)New functions in cloudYamls/allRoutes.yaml, with their triggers:
AdsConversionExportFunction (dist/adsConversionExport), Schedule cron(5 14 * * ? *): stages the day's Google Ads offline conversion rows before Google's 09:00 Los Angeles fetch.MarketingRollupFunction, Schedule cron(35 9 * * ? *): nightly copy of Google Analytics, Ads cost and Search Console numbers into mainDb, which the admin Marketing page reads through GET /api/admin/marketing/funnel (#385).ShopifyRefreshOneFunction (dist/shopifyRefreshOne), NO events: invoked synchronously only by VR_CMS_API's CreateAndUpdateIntegrations role (ShopifyRefreshOneInvokerRoleArn, a parameter so a CMS role suffix change is an override, not an edit).New behaviour:
POST and GET /api/migration-request (src/getGroupInformation/api/controllers/migrationRequest.js, #364): an owner asks to move an existing site into the app from the portal.vivreal-domain-search (deploys from main) is the public, read-only domain service behind domains-api.vivreal.io: CloudFront with X-Origin-Verify in front of a Lambda Function URL, read-only mainDb, the shared parking WAF and limiter table, a 6-hour cache. It serves GET /public/parked and the public search endpoints. Its src/shared/tldAllowlist.js is the TWIN of Secure's src/createSites/services/sellableTlds.js and the guard in createDomainTransfer.js; change both together. Read its README at origin/main before quoting its routes.
PUT /api/group/timezone (UpdateGroup, setGroupTimeZone) lets an admin or the owner set groups.timezone. Every write is a compare-and-set on expectedTimezone, the zone the caller last saw (null for none), so the portal's automatic first save never replaces a zone someone already set; a lost race answers the stored zone with applied: false. createGroup stores a zone at creation too. Both go through canonicalTimeZone (src/shared/timeZone.js: canonical IANA name, UTC accepted, fixed offsets refused, InvalidTimeZone otherwise), the same rule VR_Client_API serves with. The write is verified by reading the field back, because a stale strict schema strips it silently.scrubKitZones in src/shared/kitIdentity.js removes the kit's timezone from every page's labels, labels.openingHours and each binding's sectionConfig, so a customer site inherits its business zone instead of the kit's city. It runs beside the contact scrub, before the name gate, and is skipped for the demo tenant (keepKitContact); the worker's log reports zoneFields.src/parkedSignups/services/recordParkedSignup.js saves a capture subscribed with consentSource: 'capture' and objectValue.source parked:<domain>; a hard bounce or complaint on the platform suppression list is still recorded but with a non-sendable status and suppressedAt, and an unreadable list writes nothing and returns the message to the queue. Same rule as VR_Client_API's site sign-ups.recountTenantUsage.js UNCOUNTED_SITE_ROLES (subscribers, group-subscribers, bookings) is the HEALER that leaves them out of the entries recount; VR_CMS_API's src/shared/uncountedSiteRoles.js is the ENFORCER. They must be the same set: vivreal-hq packages/fleet-ops/contract-drift checks it (contract uncounted-list-roles). The group-subscribers role is GROUP_SUBSCRIBERS_SITE_ROLE in parkedSignups/services/groupSubscribers.js.src/createSites/services/deleteSite.js (cleanupSeededCollections): "this site's" lists are the union of four shapes, the site's collectionGroups manifest, the content and integration bindings read through pageBindings, and the groups in this business tagged exactly site:<this site's _id> (the provenance tag seeding writes; needed because a kit site's manifest is always empty). Every lookup is scoped to the business's groupID. A list another site of the same business binds is left alone with its items (groupsSharedKept). A people list (PEOPLE_LIST_ROLES: subscribers, contact, reservations, quote-requests, bookings, group-subscribers) is KEPT with every item while it holds anyone, whatever deleteContent says, because those are real people's details and a sign-up list is also the suppression record; an empty one goes. Usage rows are matched under both collection_<id> and collectionObject_<id>. Do not widen the union: unreferenced lists are live working data.src/shared/renameIdentity.js, used by updateSiteValues and the agent's site tools). seo.metaTitle and detailPage.seo.titlePattern change only where the old name is the WHOLE title or a whole segment at either end joined by a kit separator (a pipe, a middle dot, a comma or a colon, each with its spaces), exact match after trimming. The campaign sender name changes only on an exact match, and fromLocalPart never changes. The title write is a native-driver write after the Mongoose commit, because the schemas package does not declare those paths.expiresAt from the group's tier (src/shared/auditLog.js, the same resolveExpiresAt semantics as VR_CMS_API), reaped by the schema's TTL index; rows written before it have none.PUT /api/admin/groups/{groupID}/billing-source (admin pool; adminSetBillingSource.js, setBillingSource.js) writes billing.source, the comped marker. Count paying customers by stripeSubscriptionID, never by tier.package.json on origin/stable, and compare origin/stable with the newest origin/release/v2.* before saying what the worker runs.POST /api/site/pages, PUT /api/site/pages/reorder, PUT /api/site/pages/{pageSlug}, DELETE /api/site/pages/{pageSlug} on UpdateGroup (the /api prefix is required: Express mounts /site/pages, the gateway declares /api/site/pages). Each reads the site projected and lean, scoped by { _id, groupID }.pageFields (updatePageValidator), the union of every key stored on a prod page; a new page field needs a line there and nowhere else. Send each touched top-level page field WHOLE: the service writes pages.$[elem].<key>.src/shared/pageOrder.js: order is an integer >= -1 on add, update, /sites/update and both site-create paths (-1 is the home page sentinel). PageSchema declares order: Number, so junk would be a CastError 500; each path refuses it as a 400. Add requires order and accepts no blocks, so an API-added page renders empty until an update writes them.bulkWrite before the schema declared order), refuses an unknown slug with 404 before any write, and returns only slugs and orders. Nothing calls it yet (no caller in the portal's src, VR-MCP-Server or the migrator). Known trap, fix on the next list: its controller calls errorHandler, which always calls a plain next(), so Express falls through to PUT /site/pages/:pageSlug with pageSlug = "reorder" and a refused reorder runs the page-update handler.collection_groups.commerce.state: 'paused'; absent means selling) and books the drain teardown. Connecting the other provider invokes VR_CMS_API's VR-CMS-API-PaymentsMoveWorker (services/payments/paymentsMove.js here decides payments_move_in_progress and currency_mismatch first, answered 409). Checkout refuses 409 not_for_sale unless the list is selling.services/campaigns/scheduleCampaign.js books a one-time Scheduler entry (ActionAfterCompletion: DELETE); campaignScheduleFire re-checks it and puts one message on the campaign send queue that VR_Main_API's CampaignSendFunction reads.$ body keys never reach a handler (express-mongo-sanitize in src/shared/createApp.js), so updates: { 'hero.title': ... } arrives as {} and the update 500s on an unused array filter. Send whole top-level fields.updateSiteValues MERGES siteDetails.values: an absent key is untouched and an explicit null clears ("THE WRITE CONTRACT" at the top of the file). It replaced the PRESERVE_ON_REPLACE allowlist after four losses. Its unconditional domainInformation $set is safe only because Mongoose strips undefined during cast. After any site write, re-read the whole document and diff it against a pre-write backup.undefined, not unbound. Each Lambda's main-db map declares its own models (instantiateTemplateWorker declares only siteTemplates), so mainDb.DB.groups there is a TypeError, and a mock carrying both models passed 100% coverage over a line that could never run. Read the worker's own models map first; assert Object.keys(mainDb.DB) against the real map in a test.errorHandler is correct only in controller position (it always calls next()). Router-level middleware writes its own response.AWS/Lambda Errors never moves. Alarm on the <Function>.failed literal errorHandler logs on every handled 5xx, paired with an API Gateway 5xx alarm for throttled requests that never ran.preupload-* keys live one day (ExpirePreuploadOrphans, set in createBucket.js). A save promotes the bytes to groupObjects/... and deletes the source; anything still referencing a preupload- key after that is dead.cloudformation/updateGroup.yaml now declares Path /api/group/featureFlags, the old "step 7" 403 is gone, and the source repo's CLAUDE.md now records it as resolved (Secure CLAUDE.md:1493). Feature flags are now Vivreal-admin-only: requireGlobalAdmin (portal-signed x-user-ctx HMAC vs ADMIN_EMAILS) runs in the controller before validation; the group-role membership check was REMOVED (the operator isn't a member of the customer group); CTX_SECRET added to updateGroup.yaml; audit actor { email: operatorEmail, role: 'globalAdmin' }. ALLOWED_FLAGS in src/updateGroup/services/updateFeatureFlags.js holds four flags (aiActionsEnabled, dashboardInsightsEnabled, navRedesignEnabled, facebookPageCommentsEnabled; read the array), squareStorefront + templatePicker RETIRED. The portal's flag console was deleted 2026-09-28; the operator console is now vivreal-hq/packages/admin-app. GET /api/admin/groups backs that console (paginated, limit clamped 200, regex-escaped search over groupName+key, projection excludes apiKey/integrations/users, deliberately NOT an extension of /searchGroups).cloudformation/updateGroup.yaml's Layers now carries only the ffmpeg ARN via <ssm-prefix>/shared/ffmpeg-arn SSM; no AWS_LAMBDA_EXEC_WRAPPER.stripe.webhooks.constructEvent in handleEvents.js, raw body captured via express.json({ verify }) in createApp.js); acceptRequest/denyRequest inherit the Cognito default authorizer + owner/admin 403; RBAC enforced on write ops (UnauthorizedRoleException); CORS is single-layer (createApp.js). Legit Authorizer: NONE remains only on the Stripe webhook + OAuth callback.site-loader and site-renderer are pinned EXACTLY (the worker bundles them as real files, and the renderer pin must not be loosened without regenerating renderer.capability.json); @hillbombcreations/schemas and @hillbombcreations/tier-quotas are CARET ranges, so the lockfile is what runs. Read every one of those pins from package.json on the deployed line. X-Ray is retired here (AWSXrayWriteOnlyAccess is no longer auto-attached).Load vivreal-workflow:verification-discipline. This is the highest-blast-radius backend, so an absence claim (a route, a policy, a Lambda, an env var) costs the most here: make the same check return a hit for something you know is there before calling anything absent.
secure-api expert agent, 2026-10-20)The expert agents are retired (2026-10-28), so the review checklist they used to carry lives
here. Query rules (tenant scoping, the mainDb _id
lookup, the publishDate and archived filters) live in vivreal-knowledge:vivreal-db, and
packaging and limits in vivreal-infra:vivreal-lambda; they are not repeated here.
build-lambdas.js roster entry; a function missing from the build roster fails packaging, not tests.WS_ENDPOINT + WS_TABLE. Send-message paths must be idempotent on stale connections.StartExecution ARN format, NOT DescribeExecution ARN format (different IAM resource types).activeGroupID on the user doc and re-issues the active_ctx JWT, verify the order doesn't leak across requests.groupID, userID, stripeSubscriptionID, cognitoSub must be indexed; groupID + userID compound index for membership queries.CTX_SECRET (HMAC(CTX_SECRET, 'vivreal/ctx/v2/<service>')) and checks aud; the admin gate requires exp and accepts only tokens addressed to this service. A token minted for one service is not valid at another, so a hand-minted test token must name the right audience.main; git push --no-verify bypasses the gate.userAndAuth/services/deleteAccount.js + preflightAccountDeletion.js) and video-transcode bounding (createSites/services/S3Functions/mediaHelperFns/createVideoObject.js) shipped this window, mind them when tracing account lifecycle or media upload paths.getTierQuotas(group.tier) at every gate (joinGroup, acceptRequest, agent metering, getAgentContext, instantiateTemplate, createSiteCollectionData, createSiteWithExistingCollections, getGroupInfo v1+legacy, updateEmail serializers). updateGroupTier + handleSubscriptionEnd STOPPED writing those fields. The per-group agentUsage.quota override is GONE from checkAgentQuota (src/agent/services/metering.js), past-quota agent use requires overageBilling.enabled and hard-stops at the spending cap; mediaUsage.quota is the only admin-override quota left (W7). Downgrade to a 0-access target is now a preflight violation.createSites Lambda, but only when site.siteInfo.mode === "hosted_by_us" (api/controllers/createSiteCollectionData.js); the state machine ARN is the STATE_MACHINE_ID env var, resolved from SSM (<ssm-prefix>/secure-api/state-machine-id, in cloudformation/createSites.yaml), NOT a CloudFormation export. (The Create-Site-State-Machine IAM policy IS from CFN, likely the source of the "CFN export" wording.) Cross-stack invocation: the deploy-pipeline Lambdas live in the EventHandler stack and are named vh-${stage}-<step> in Vivreal_EventHandler/serverless.yml; CI deploys with --stage site-deployment, so the deployed names are vh-site-deployment-seedCollections, vh-site-deployment-createAmplifyApp, vh-site-deployment-markSiteLive and so on (hyphens; an underscore spelling is only how the Lambda-tool MCP names its tools).config.stripeSecretKey (commit c653b85), do not inline a hardcoded Stripe key.{"message":"Internal server error"}) appears nowhere in the repo, the response passed Lambda's 6 MB ceiling and API Gateway substituted its own body. The site-version list did exactly this (each row carried a whole site snapshot; fixed v2.10.1 with an allowlist projection, SITE_VERSION_LIST_PROJECTION, and src/shared/responseSizeGuard.js, which makes a route refuse in owner words with an errorCode). Use an ALLOWLIST projection, not { field: 0 }, so the next Mixed field cannot re-inflate the list. The version DETAIL route still carries a snapshot.POST /api/site/cutover-state is live (setSiteCutoverState, merged #211): a global-admin gate on top of the owner/admin check, plus a compare-and-swap whose readback re-verifies the site on all four identity fields including deployment.appId. Its caller, Vivreal_Site_Migrator#46, merged 2026-09-09. APPROVED_CANONICAL_ORIGIN is hardcoded to https://vivreal.io.release/vX.Y is removed by the next cut-and-promote. Diff the release line against main by file content, not by PR number, before every promote.git show <line>:package.json for a service version, the consumer lockfile for a package pin, the release JSON endpoint (more than once) for the portal, and the registry for a published package. Every version this file used to name went stale inside two weeks, and a stale version reads exactly like a current one.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
27 skills in this plugin
/sentry-tracerUse when investigating what happened during a Vivreal user action across the stack, tracing an error end-to-end, validating a deploy, or doing tenant-scoped triage with Sentry. Teaches WHEN to trace cross-stack (frontend spans ↔ backend logs ↔ WebSocket events) and HOW (trace-ID propagation, the standard tag set, request_id fallback, service.* breadcrumbs). Triggers on: "what happened when I did X", "why did this error", trace this request, Sentry issue, deploy validation, "everything's broken for this group", crash, error timeline. For the full investigation agent with Sentry MCP tools wired in, dispatch the `sentry` agent / `/sentry-trace` (both in the `vivreal-sentry` plugin); this skill is the passively-loaded knowledge layer. Also covers the step from a Sentry error to the AWS and Atlas metric that confirms an infrastructure cause (502 with no backend event, Lambda timeout, Mongo connect-hang, throttling, OOM, stalled deploy)./vivreal-accounts-and-writesUse before filming, walking or capturing anything in the Vivreal portal or on vivreal.io, and before any write a capture or walk makes. Carries which login to use for which business (the demo account, the QA scratch owner, the owner session), the eight-step owner-approved write protocol (named approval, snapshot, write through the UI, fresh-process read-back, restore, manifest entry), the never-list (Post, Publish, Schedule, Connect and the rest), and the rules for stills that fill vivreal.io marketing slots (pair by what the slot says, no demo site has its own web address, mask comped plan figures). Shared by footage-recorder, tutorial-maker, help-page-producer, qa-walker and marketing-auditor. Triggers on: which login, demo account, QA scratch-2, test account, switch business, owner-approved write, write protocol, snapshot and restore, mutations, marketing still, screenshot swap, vivreal.io slot, walk harness, write guard, POST allow list, PRO badge./vivreal-admin-app-knowledgeUse when working on, walking, deploying or reasoning about the internal admin app (vivreal-hq packages/admin-app), the invite-only, sign-in-only staff hub that holds every staff surface since v7 (outreach CRM, sign-ups, monitoring, errors, tickets, flags, audit, usage, economics, deployed sites, team, staff push), covering where it lives, its own identity pool and session, how it calls the fleet with no active_ctx, the deploy by fast-forwarding deploy/admin-app, its two ops Lambdas, what each page reads, including the dark navy restyle and the Releases, Database, Marketing and Inbound pages. Source of truth: `vivreal-hq` `packages/admin-app/CLAUDE.md` (and the docs it links) at `origin/deploy/admin-app`./vivreal-agent-knowledgeUse when working on, writing about, or debugging Vivreal AI. The AI offering is connecting an AI agent through the Vivreal MCP server (VR-MCP-Server, plan flag mcpAccess, metered in mcpToolCalls), and nothing else: the in-app assistant is RETIRED (owner 2026-10-07, agentActions 0 on every tier; the global FAB, drawer and /agent page were deleted 2026-09-24) and only dead code survives in the portal (Studio AiRail, EditPlan) and VR_Secure_API's agent Lambda. Covers the copy rule ("AI agent", never assistant or a model name), the real gates, and the retired surface's archaeology. Triggers on: AI agent, MCP, connect an AI agent, AI assistant, AI assistant not showing, agentActions, aiActionsEnabled, aiSiteEditing, aiComponentGen, mcpAccess, mcpToolCalls, AiRail, useAgentAccess, EditPlan, proposeSiteEdits, agent/execute, agentProgress. Sources: VR-MCP-Server, Vivreal-Tier-Quotas src/tierQuotas.ts./vivreal-analytics-knowledgeUse when working on Vivreal's first-party analytics, VR_Analytics_API (the collect→store→rollup pipeline), the Templates SiteBeacon, or the per-site traffic dashboard (VR_Secure_API read route + portal AnalyticsPanel). Covers the CloudFront+WAF → Lambda Function URL ingest chain (X-Origin-Verify, bot filter, Joi, per-IP rate limit, daily-salt visitor hash), the analytics_rollup DynamoDB design, the daily rollup cron into mainDb.site_traffic_daily, the LIVE auto-deploy status (GitHub Actions → CloudFormation) plus the W4 CDN egress meter (runs unconditionally), and where increment 2 lives. Triggers on: analytics, site traffic, beacon, SiteBeacon, visitor stats, page views, unique visitors, analytics_rollup, site_traffic_daily, first-party analytics, per-site dashboard, collect.vivreal.io, visitor hash, rollup cron, CDN egress meter, VR_Analytics_API. Source of truth: `VR_Analytics_API` `CLAUDE.md` (and the docs it links) at `origin/main`./vivreal-blender-knowledgeUse when scripting or rendering in Blender for Vivreal, above all the Vivreal duck mascot in vivreal-hq/brand/mascot/model. Covers headless renders (blender -b -P script.py -- args, --factory-startup, --python-exit-code), bpy data versus ops, bmesh, depsgraph evaluated_get and new_from_object, mathutils transform gotchas, flat toon and NPR rendering in EEVEE (Emission plus the Standard view transform, exact sRGB hex, dither, filter size, transparent film, orthographic framing), outline methods compared (Freestyle, Grease Pencil Line Art, inverted hull, ID-pass edge inking), and the 4.2 to 5.2 API changes that break scripts (EEVEE engine id, blend_method, use_nodes, Grease Pencil v3). Triggers on: Blender, bpy, bmesh, headless render, background render, EEVEE, Workbench, Cycles, toon, cel, NPR, outline, inverted hull, Freestyle, Line Art, Grease Pencil, view transform, AgX, Filmic, mascot, the duck, duck.py, render.py, mascot-artist.npx claudepluginhub hillbombcreations/vivreal-skills --plugin vivreal-knowledge