Manage 10-100 HubSpot portals for agency clients with credential isolation that prevents
cross-portal data contamination, per-portal audit trails for billing and GDPR/CCPA
attribution, and a scriptable bulk-onboarding workflow that eliminates one-at-a-time
credential setup. Use when onboarding new client portals, building a compliant per-client
API call log, rotating tokens across a full agency fleet, or generating per-client
compliance reports. Trigger with "hubspot agency", "multi-portal management",
"hubspot credential isolation", "per-portal audit log", "hubspot compliance report",
"bulk portal onboarding", "token rotation cascade", "hubspot client portals".
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Manage 10-100 HubSpot portals for agency clients with credential isolation that prevents
cross-portal data contamination, per-portal audit trails for billing and GDPR/CCPA
attribution, and a scriptable bulk-onboarding workflow that eliminates one-at-a-time
credential setup. Use when onboarding new client portals, building a compliant per-client
API call log, rotating tokens across a full agency fleet, or generating per-client
compliance reports. Trigger with "hubspot agency", "multi-portal management",
"hubspot credential isolation", "per-portal audit log", "hubspot compliance report",
"bulk portal onboarding", "token rotation cascade", "hubspot client portals".
Operate a fleet of HubSpot portals for agency clients without cross-portal contamination, attribution loss, or onboarding bottlenecks. This is not a getting-started guide โ it is the infrastructure your agency runs on day one with client one and scales to client one hundred without revisiting.
The six production failures this skill prevents:
Cross-portal credential contamination โ a shared HUBSPOT_ACCESS_TOKEN env var causes API writes intended for Client A to silently land in Client B's CRM. The HubSpot API does not reject the call; it accepts it. Data corruption is silent and may not be discovered for days. Per-portal credential isolation โ enforced in code, not convention โ is the only fix.
Audit trail gaps โ agency billing, SLA compliance, and GDPR/CCPA data-processing agreements all require proof of which API calls were made on behalf of which client. A shared token makes post-hoc attribution impossible. A per-portal structured audit log with portalId, clientSlug, operation, and timestamp makes attribution irrefutable.
Bulk onboarding bottleneck โ onboarding 50 new clients one-at-a-time requires 50 manual credential setups, 50 manual verifications, and 50 opportunities for human error. A scriptable bulk onboarding workflow reads a CSV of client names and tokens, validates each against the account-info endpoint, and seeds the credential store in one pass.
Token rotation cascade โ rotating one client's private-app token in HubSpot does not update any downstream system. With 50 portals, a partial rotation โ some systems updated, some not โ leaves stale tokens in production for undetermined periods. A per-portal rotation runbook with a cross-system checklist closes the gap.
Rate-limit aggregation confusion โ each portal has its own independent 500K/day quota. An agency analytics system reading all 50 portals is NOT limited to 500K calls total โ it has 500K per portal per day, but only if the token used for each portal belongs to that portal. A shared token collapses all quota attribution to one portal, causing artificial exhaustion and incorrect monitoring.
Compliance reporting ambiguity โ under GDPR Article 30 and CCPA, a data processor (the agency) must demonstrate which operations were performed on which controller's (client's) data and when. A shared token makes this demonstration impossible after the fact. Per-portal audit logs with structured fields make it a simple query.
Prerequisites
Node.js 18+ or Python 3.10+
One HubSpot private-app token per client portal (Settings โ Integrations โ Private Apps โ Create private app โ Auth tab)
A secret store the credential router can read at startup: AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, or for local development
pass
jq installed for CLI validation steps
python3 with standard library only for bulk onboarding script (no external deps required)
CSV file of client slugs and tokens for bulk onboarding (format: clientSlug,portalToken,portalId)
Instructions
Build in this order. Each section closes one production failure mode.
1. Credential store design (closes cross-portal contamination)
The credential store is a JSON map of clientSlug โ token. It lives in your secret manager, never in source code or environment variables. The key insight is that clientSlug is the primary key โ every operation starts by selecting a slug, which deterministically selects the token. There is no ambient credential and no fallback to a global env var.
// Shape of the credential store (stored in secret manager, NOT in git or env vars)interfacePortalCredentialStore {
version: number; // increment on every write; used for drift detectionportals: Record<string, PortalCredential>;
}
interfacePortalCredential {
token: string; // HubSpot private-app token: pat-na1-...portalId: number; // HubSpot portal ID โ verified via account-info on onboardclientSlug: string; // kebab-case client identifier: "acme-corp"addedAt: string; // ISO 8601 โ when this credential was seededlastRotatedAt: string; // ISO 8601 โ updated on every token rotationdatacenter: string; // "na1" | "eu1" | "au1" โ extracted from token prefix
}
// Load from secret manager at process startup โ never re-read per-requestasyncfunctionloadCredentialStore(): Promise<PortalCredentialStore> {
const raw = awaitreadSecret("hubspot/agency-portals");
conststore: PortalCredentialStore = JSON.parse(raw);
if (!store.portals || typeof store.portals !== "object") {
thrownewError("Credential store is malformed โ missing portals map");
}
return store;
}
The datacenter field matters: a pat-na1-* token sent to api.hubapi.com (which routes to na1) will work, but if HubSpot migrates the portal to eu1, the token prefix changes and calls to the wrong datacenter return 404. Storing the datacenter alongside the token surfaces this mismatch immediately.
2. Portal identity verification (confirm token points to expected portal)
Every token must be verified against the GET /account-info/v3/details endpoint before being admitted to the credential store. This endpoint returns the portalId for the token's portal โ which is the ground truth for "which portal does this token belong to."
interfacePortalDetails {
portalId: number;
timeZone: string;
currency: string;
portalType: string; // "STANDARD" | "DEVELOPER" | "SANDBOX" | "TRIAL"
}
asyncfunctionverifyPortalIdentity(token: string,
expectedPortalId?: number): Promise<PortalDetails> {
const res = awaitfetch("https://api.hubapi.com/account-info/v3/details", {
headers: { Authorization: `Bearer ${token}` },
});
if (res.status === 401) {
thrownewError("Token rejected (401) โ revoked, malformed, or wrong datacenter");
}
if (res.status === 403) {
thrownewError("Token lacks account-info scope โ re-create private app with account-info scope");
}
if (!res.ok) {
thrownewError(`account-info returned ${res.status}: ${await res.text()}`);
}
constdetails: PortalDetails = await res.json();
if (expectedPortalId !== undefined && details.portalId !== expectedPortalId) {
thrownewError(
`Portal ID mismatch โ token belongs to portal ${details.portalId}, ` +
`expected ${expectedPortalId}. Token is for the wrong client.`
);
}
return details;
}
Run verifyPortalIdentity during onboarding (to populate portalId in the credential store) and during rotation (to confirm the new token belongs to the same portal before committing it).
The client factory produces an HTTP client bound to a single portal's token. Every request made through this client is logged to the audit trail with a structured record. There is no way to make an unlogged HubSpot API call through this factory โ the audit middleware is non-optional.
The audit writer can be any function that accepts an AuditRecord โ write to stdout (structured JSON), append to a file, push to a database, or forward to a logging pipeline. The factory does not care.
4. Router class (ties credentials + audit + identity together)
Each portal's 500K daily quota is tracked independently by HubSpot โ but only if the token used for each portal belongs exclusively to that portal. A shared token collapses all quota into the token's home portal, making the remaining-quota header meaningless for any client except the token's owner.
Read the X-HubSpot-RateLimit-Daily-Remaining header from every response and log it with the clientSlug. When any portal's remaining quota drops below a threshold, throttle that portal's calls โ not the agency's calls globally.
The bulk onboarding script reads a CSV of client slugs, HubSpot tokens, and expected portal IDs. It validates each token against account-info/v3/details, confirms portal identity, and seeds the credential store. See references/implementation-guide.md for the full Python implementation.
Quick-verify a single portal from the CLI before seeding:
# Verify a token returns the expected portal ID
TOKEN="pat-na1-your-token-here"
EXPECTED_PORTAL_ID="12345678"
curl -s "https://api.hubapi.com/account-info/v3/details" \
-H "Authorization: Bearer $TOKEN" | \
jq --argjson expected "$EXPECTED_PORTAL_ID"'
if .portalId == $expected
then "OK โ portal \(.portalId) (\(.portalType))"
else "MISMATCH โ token belongs to portal \(.portalId), expected \($expected)"
end
'
7. Token rotation runbook (closes the cascade problem)
HubSpot does not offer an API for rotating private-app tokens. Rotation happens in the HubSpot Settings UI, which immediately revokes the old token and generates a new one. The cascade problem is that with 50 portals, any system that stored the old token (secret manager, CI secrets, staging environment, webhook receiver) must be updated before the old token is revoked โ or it will fail immediately.
Rotation order matters: update all consuming systems BEFORE revoking the old token in HubSpot.
See references/implementation-guide.md for the per-portal rotation runbook with a cross-system checklist.
Error Handling
HTTP Status
Error
Root Cause
Action
200 OK with wrong portalId
Identity mismatch on account-info
Token belongs to a different portal than expected
Reject the token; do not admit to credential store; flag for human review
401 UNAUTHORIZED
INVALID_AUTHENTICATION
Token revoked, malformed, or sent to wrong datacenter endpoint
Verify token format matches datacenter; check if a rotation left stale token in store
403 FORBIDDEN
MISSING_SCOPES
Private app does not have the required scope
Re-create private app with correct scopes; update token in credential store
403 FORBIDDEN
PORTAL_SUSPENDED
Client portal is suspended or deactivated
Contact client; stop all calls for this slug
404 NOT_FOUND
Resource does not exist
Object ID does not exist in this portal
Normal โ handle in application logic; log objectType and objectId for audit
429 TOO_MANY_REQUESTS
RATE_LIMIT
Portal's 500K daily quota exhausted
Back off with Retry-After; alert on daily-remaining; do NOT retry blind
429 TOO_MANY_REQUESTS
TEN_SECONDLY_ROLLING
100โ150 calls/10s burst limit hit
Exponential backoff with jitter; this is per-portal, not per-agency
503 SERVICE_UNAVAILABLE
HubSpot outage
HubSpot API unavailable
Back off with jitter; check status.hubspot.com; do not rotate credentials
Cross-portal contamination detection
If a write operation (POST/PATCH/DELETE) succeeds but the response body's portalId (available on some endpoints) does not match the expected portal, you have a contamination event. Stop immediately:
asyncfunctionassertPortalSafety(response: Response,
expectedPortalId: number,
clientSlug: string): Promise<void> {
const body = await response.clone().json().catch(() =>null);
if (body?.portalId && body.portalId !== expectedPortalId) {
thrownewError(
`CRITICAL: Cross-portal contamination detected. ` +
`Write intended for portal ${expectedPortalId} (${clientSlug}) ` +
`landed in portal ${body.portalId}. ` +
`Halt all operations and audit credential store immediately.`
);
}
}