forcedotcom/sf-skills / skills/dx-apexguru-scan
dx-apexguru-scan
VerifiedRun an ApexGuru performance scan on a Salesforce Apex project via the ApexGuru SFAP Scan API. Zips the project's Apex (any layout), submits it, polls to completion, decodes the base64 report, and presents performance antipattern violations (SOQL in loop, DML in loop, Schema.getGlobalDescribe(), SOQL without WHERE/LIMIT, unused SOQL fields) grouped by rule with severity, file:line, and suggested fixes — clearly attributed as 'Static only' or 'Production insights'. TRIGGER when the user says 'run ApexGuru', 'ApexGuru scan', 'check Apex performance', 'find governor-limit / performance antipatterns', 'SOQL in loop', 'scan my Apex for performance', or 'ApexGuru performance insights'. DO NOT TRIGGER for general static analysis or security scans (use dx-code-analyzer-run), for fixing code without scanning, or for onboarding an org to ApexGuru.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 20.4 KB |
| examples/README.md | markdown | 2.8 KB |
| examples/sample-decoded-summary.json | config | 4.3 KB |
| examples/sample-full-no-runtime-response.json | config | 27.6 KB |
| examples/sample-succeeded-response.json | config | 1.7 KB |
| references/api-reference.md | markdown | 2.5 KB |
| references/authentication.md | markdown | 7.1 KB |
| references/error-handling.md | markdown | 3.7 KB |
| references/violation-catalog.md | markdown | 2.1 KB |
| scripts/build-zip.shexecutable | script | 3.8 KB |
| scripts/decode-report.jsexecutable | script | 19.4 KB |
| scripts/resolve-token.shexecutable | script | 9.8 KB |
| scripts/run-scan.shexecutable | script | 6.5 KB |
| scripts/scan.shexecutable | script | 3.7 KB |
| scripts/validate-token.js | script | 5.5 KB |
scripts/validate-token.js
View on GitHub#!/usr/bin/env node
// Locally sanity-check an SFAP JWT *before* any network call, so a bad token
// fails fast with a clear reason instead of a bare HTTP 401 deep in the poll
// loop. This does NOT verify the signature (only the server can) — it decodes
// the freely-readable header/body claims to catch the two things that cause
// almost every 401: missing sfap_api scope, or expired.
//
// The token's environment (prod/stage/dev) is detected from its tnk claim and
// reported as detectedEnv so the caller can route to the matching endpoint.
//
// The token is read from STDIN (never argv) so it does not leak into the
// process list. Usage:
// printf '%s' "$JWT" | node validate-token.js [--now <epoch>]
//
// Output (stdout, single-line JSON):
// pass: {"ok":true,"tnk":"...","detectedEnv":"prod|stage|dev|null","expiresInSeconds":N,"warnings":[...]}
// fail: {"ok":false,"error":"...","hint":"..."} (exit 1)
// A "fail" only happens for things we can PROVE wrong (expired / missing scope).
// Anything we cannot read is a warning, not a block.
function out(obj, code) {
console.log(JSON.stringify(obj));
process.exit(code);
}
const args = process.argv.slice(2);
let now = Math.floor(Date.now() / 1000);
for (let i = 0; i < args.length; i++) {
if (args[i] === "--now") now = parseInt(args[++i], 10) || now;
}
// Read the token from stdin (keeps it out of argv / process list).
let token = "";
try {
token = require("fs").readFileSync(0, "utf8").trim();
} catch {
token = "";
}
if (!token) out({ ok: false, error: "no token on stdin", hint: "resolve the token before validating" }, 1);
// A JWT is header.body.signature, each a base64url-encoded chunk.
function decodeSegment(seg) {
const b64 = seg.replace(/-/g, "+").replace(/_/g, "/");
const pad = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
return JSON.parse(Buffer.from(pad, "base64").toString("utf8"));
}
const parts = token.split(".");
if (parts.length < 2) {
// Not a JWT we can read — don't block (token may be an opaque format).
out({ ok: true, tnk: null, detectedEnv: null, expiresInSeconds: null, warnings: ["token is not a readable JWT — skipping local checks"] }, 0);
}
let header, body;
try {
header = decodeSegment(parts[0]);
body = decodeSegment(parts[1]);
} catch {
out({ ok: true, tnk: null, detectedEnv: null, expiresInSeconds: null, warnings: ["could not decode JWT claims — skipping local checks"] }, 0);
}
const warnings = [];
// --- 1. tnk / environment. Per the SFAP contract, tnk lives on the HEADER and
// looks like core/<instance>/<orgId> (e.g. core/prod/00D..., core/stagecomstg2/...,
// core/falcondeva/...). The environment marker lives ONLY in the <instance>
// segment — the trailing <orgId> (00D...) is an opaque id that must NOT be
// scanned for substrings, or a prod org whose id happens to contain "dev"/"stg"
// would be wrongly rejected. So we match markers against the instance segment
// only, never the whole claim string or the iss host. The detected env is
// reported (not rejected) so the caller can route to the matching endpoint. ---
const tnk = header.tnk || body.tnk || null;
// tnk instance segment = the middle of core/<instance>/<orgId>; fall back to the
// whole tnk only if it isn't in that 3-part shape.
const tnkParts = tnk ? String(tnk).split("/") : [];
const tnkInstance = tnkParts.length >= 3 ? tnkParts[1] : tnk || "";
// The tnk instance segment is the authoritative environment signal. The iss host is
// NOT used: it is the customer org's own hostname, which can contain "dev" or "stage"
// even for a production-hosted org. Matching it routed such production tokens to the
// dev API host, which rejects them with HTTP 401.
const envHay = String(tnkInstance).toLowerCase();
const looksDev = /falcondeva|falcondev|falcontest|deva|(^|[^a-z])dev([^a-z]|$)/.test(envHay);
const looksStage = /stg|stage/.test(envHay);
// Env inferred from the token's tnk claim (null when we can't tell). Production
// instances carry no stg/dev marker, so a readable tnk with neither signal is prod.
const detectedEnv = !tnk
? null
: looksStage && !looksDev
? "stage"
: looksDev && !looksStage
? "dev"
: !looksStage && !looksDev
? "prod"
: null;
if (!tnk) warnings.push("no tnk claim found: could not detect the token's environment; set APEXGURU_ENV=prod|stage|dev explicitly");
// --- 2. scope must include sfap_api. Scope may be a space-delimited string
// (scp/scope) or an array. Only fail if we can read it AND sfap_api is absent. ---
const scopeRaw = body.scp ?? body.scope ?? null;
if (scopeRaw != null) {
const scopes = Array.isArray(scopeRaw) ? scopeRaw : String(scopeRaw).split(/\s+/);
if (!scopes.includes("sfap_api")) {
out({ ok: false, error: "token scope does not include sfap_api",
hint: "Re-mint the token with the sfap_api scope. See references/authentication.md." }, 1);
}
} else {
warnings.push("no scope claim found — could not confirm sfap_api scope");
}
// --- 3. expiry. exp is epoch seconds. Fail if already past. ---
let expiresInSeconds = null;
if (typeof body.exp === "number") {
expiresInSeconds = body.exp - now;
if (expiresInSeconds <= 0) {
out({ ok: false, error: `token expired ${Math.abs(expiresInSeconds)}s ago`,
hint: "Re-mint a fresh SFAP token and retry." }, 1);
}
if (expiresInSeconds < 60) warnings.push(`token expires in ${expiresInSeconds}s — it may lapse mid-scan`);
} else {
warnings.push("no exp claim found — could not confirm the token is unexpired");
}
out({ ok: true, tnk, detectedEnv, expiresInSeconds, warnings }, 0);
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |