---
name: plugsky-security
slug: plugsky--plugsky-security
description: "Use when auditing or changing Plugsky security \u2014 login (password/OTP/2FA), sessions, API keys, rate limits, billing webhooks, admin gating, headers, RAG scoping. Contains the verified audit checklist, the security test harness, and the known pitfalls. WHEN: plugsky security, security audit, OTP login, one-time code, trusted devices, change password, brute force, login throttle, webhook signature, security headers, secrets, auth audit, harden, penetration."
collection: Plugsky
category: Platform Ops
license: Plugsky
source: https://plugsky.com/skills
install: "Download the Plugsky skills pack (see below)"
---

# plugsky-security

Use when auditing or changing Plugsky security — login (password/OTP/2FA), sessions, API keys, rate limits, billing webhooks, admin gating, headers, RAG scoping. Contains the verified audit checklist, the security test harness, and the known pitfalls. WHEN: plugsky security, security audit, OTP login, one-time code, trusted devices, change password, brute force, login throttle, webhook signature, security headers, secrets, auth audit, harden, penetration.

## Install

```bash
Download the Plugsky skills pack (see below)
```

## Skill

# Plugsky — security audit & auth operations

Last updated: **2026-11-06**. Full platform audit: `Plugsky/docs/ops/audit-skills.md` and `PLUGSKY-FULL-AUDIT-2026-10-27.md`.
Full security report: `Plugsky/docs/security/security-audit-2026-09-29.md`.
Harness: `Plugsky/tools/audit/security/` (`security-e2e.py`, `pin_code.sh`).

> 2026-10-27: no auth/session code changed in this round. The security-relevant changes were the privacy/subprocessor rewrite, the admin metric labels, and the concurrency override removal (see §5). Re-run the auth E2E before claiming a fresh security pass.

## 1. Auth architecture (know this)

- **Password login** `POST /api/auth/login` → JWT (+refresh) + `plugsky_session` cookie.
- **2FA (TOTP)** optional; when enabled login returns `two_factor_required` +
  challenge, completed via `POST /api/auth/login/2fa`.
- **Email OTP (device verification)** — on password login from an unknown
  device/browser the response is `{otp_required, challenge_id, email_hint}`
  (NO token); complete with `POST /api/auth/otp/verify {challenge_id, code}`.
  Trusted devices (30 days) skip it. Toggle per user: `users.otp_login_enabled`.
- Tables: `login_challenges` (code SHA-256, 10-min TTL, 6 attempts),
  `trusted_devices` (user+device hash, `trusted_until`).
- Device hash = `sha256(User-Agent + '|' + client IP)`; client IP = first
  `X-Forwarded-For` else `REMOTE_ADDR`.
- **Change password**: `POST /api/account/password {current_password,new_password}`.
  Bumps `users.token_version` → **every other session is invalidated** (access + refresh
  rejected with 401 "Session ended after a password change"). The response returns fresh
  `access_token`/`refresh_token` (+ cookie) so the current browser stays signed in.
  Verified E2E 2026-10-05 (two logins → change on A → B 401 on access and refresh → A' 200).
- **Session versioning**: JWT access/refresh carry a `ver` claim; `AuthMiddleware` and
  `RefreshController` compare it with `users.token_version`. Missing `ver` = 0 (legacy).
  If you add a new token-issuing path, pass `$this->users->tokenVersion($user->id)`.
- **Security prefs**: `GET/DELETE /api/security/devices`, `POST /api/security/devices/revoke-all`,
  `GET/POST /api/security/otp`.
- **Throttles**: login = per-IP + per-email Redis window (`LOGIN_RPM_LIMIT`, default 12;
  observed lock-out at 10/min for the base `ip` scope); OTP verify = `OTP_VERIFY_RPM_LIMIT` (20).

## 2. Re-run the audit (fast path)

```bash
# email-OTP + password + device-trust E2E (creates a temp user; clean it up after)
scp tools/audit/security/security-e2e.py VPS:/tmp/ && ssh VPS 'python3 /tmp/security_e2e.py'

# pin a challenge to a known code for UI tests (after a login creates one)
ssh VPS 'bash /tmp/pin_code.sh user@example.com 123456'

# webhook signature must be enforced
curl -s -o /dev/null -w '%{http_code}\n' -X POST https://plugsky.com/api/webhooks/stripe \
  -H 'Stripe-Signature: t=1,v1=deadbeef' -H 'Content-Type: application/json' -d '{}'   # expect 400

# brute-force throttle
for i in $(seq 1 12); do curl -s -o /dev/null -w '%{http_code} ' -X POST https://plugsky.com/api/auth/login \
  -H 'Content-Type: application/json' -d '{"email":"x@x.com","password":"bad"}'; done; echo  # …401 401 429
```

Then walk `docs/security/security-audit-2026-09-29.md` §1 and re-verify each row.

## 3. Known pitfalls (learned the hard way)

- **Never `fetchColumn()` a boolean column** — PDO returns `false` for both “no row”
  and boolean-false. Fetch the row and cast (`DeviceVerificationService::isEnabled` bug).
- **Global middleware can’t see auth attributes** — the request is cloned inside the
  auth middleware. Use `Plugsky\Support\RequestContext::setUser()` / `userId()`.
- **Guard placement matters**: plan-drift guard must run AFTER the workspace id is
  resolved in `AuthMiddleware` (a misplaced guard 500’d every dashboard API).
- **Stripe return URLs**: success/cancel point at
  `https://plugsky.com/dashboard?billing=success|cancel` (the legacy `/billing` 301s there).
- Rate-limit scopes: arbitrary names work (`login_ip`, `login_email`, `otp_verify_ip`);
  admin overrides live at `plugsky:rl:override:<scope>:<id>`.

## 4. Privacy, data deletion, and subprocessors (2026-10-27)

- **Data deletion** is available in **Settings → Privacy**; account deletion removes API keys, RAG data, and configuration, and leaves only anonymized usage metadata for billing integrity.
- **PLG-126 evidence:** account **1826** was deleted/anonymized; the customer re-signed up as **5789** (free), paid **$5.60** on Oct 23, and canceled Oct 26 20:07 UTC. No refund was issued; the customer retests first. Keep the GDPR evidence package.
- **`frontend/legal/privacy.html` is now v1.1.** The subprocessor table lists the real inference/failover set: NVIDIA, OpenCode (Zen/Go), OpenRouter, BytePlus ModelArk, Groq, Cloudflare Workers AI, Google Gemini, TokenHarbor, LLM7, Ollama Cloud, FreeLLMAPI (self-hosted), GPU Share operators, Stripe, PostgreSQL, certbot.
- **Do not claim blanket no-retention.** Plugsky stores 0 days of request/response bodies, but free-tier upstreams may retain short-lived abuse logs. They are not permitted to train. Paid/Enterprise routes use no-training terms where available. Legal review of v1.1 is still pending.
- **GPU Share** jobs run on independent operator hardware; operator terms prohibit retention and training, and Enterprise can exclude GPU Share routing.
- **Admin metric definitions:** “Unresolved tickets” = open + awaiting customer (currently **0 open + 11 awaiting**), and “Alias routes serving” is 40 public aliases, separate from 11 engine rows. Do not label the 51-row table as 51 chat models.

## 5. Hardening backlog (do when touching security)

- Session invalidation on password change — **done 2026-10-05** (`users.token_version`, JWT `ver` claim).
  Optional follow-up if the owner wants a global logout: `UPDATE users SET token_version = token_version + 1`
  (forces every existing session to re-login).
- Add `Retry-After` header to auth 429s (body already explains).
- Configure **DKIM** (OTP deliverability) — owner action in Hostinger hPanel.
- Consider requiring device trust after TOTP logins too.
- SIEM/audit export for enterprise; consider an external pen-test before large deals.

## 2026-11-06 — security incident lessons (mandatory gate)

**Incident:** A Cyprus IP `84.46.131.36` used a disposable `@fldubai.com` trial account, then authenticated as **user 1 (admin@plugsky.com)** and called `/api/playground/browser` 14 times. The same IP used the live Stripe key for `GET /v1/payouts` at 16:32 UTC. The root-run Playwright service accepted arbitrary `session_id` + `evaluate` with no ownership check, `--no-sandbox`, and `--disable-web-security`; `.env` was root-readable. Treat this class of endpoint as a remote browser/file/SSRF surface, not a toy.

### New automated security skill

```bash
cd /var/www/plugsky/backend
bash bin/skills/skill-security.sh
# expected after containment: PASS=27 WARN=2 FAIL=0 of 29
# WARN: TOTP 2FA not enrolled; live Stripe key awaiting post-incident rotation.
```

It checks:

- Active admins have a password hash, email OTP enabled, and post-rotation `token_version`.
- No active admin API keys; no unrestricted admin keys; no trusted admin devices.
- No active `@fldubai.com` accounts; user 29811 suspended.
- Playground browser service inactive; no `/opt/plugsky-browser/server.js`; sudo wrapper and binary absent; MCP auth-prefix logs absent.
- `/v1/payouts` is **404** (it is Stripe, not a Plugsky endpoint).
- `/api/playground/browser` returns 403/404/503, never 200.
- `/mcp` `tools/call` without auth is 401/403; admin/auth/keys endpoints without auth are rejected.
- `GET /mcp` is a **public server card by design** (200, discovery metadata only). Do not treat the 200 as an auth bypass; verify the body has no secret fields and that only `POST` carries auth middleware.
- `.env` and `storage/.env` never serve secret fields; `/api/status` has no secret fields.
- `.env` is 640/600; `JWT_SECRET` >=32; Stripe live-key warning; paid-lane policy.

### Non-negotiable controls after this incident

1. **Never re-enable `/api/playground/browser`** until it is rebuilt: non-root, no `--no-sandbox`, no `--disable-web-security`, no `file://`, private-IP/metadata blocking, per-user session IDs, ownership checks, no tenant `evaluate`/`exec`, egress allowlist, read-only container.
2. **Never store admin passwords in Git.** The recovery file is `0600` outside the repo; use a password manager. `OUTAGE_FALLBACK_KEYS.md` already contains provider secrets — move them out of Git and rotate.
3. Admin accounts must have **TOTP 2FA**, not only email OTP. Email OTP is device verification; trusted devices can skip it. Google sign-in can bypass app OTP unless Google 2FA is enabled or Google login is disabled for admin.
4. Admin API keys need expiry, IP allowlists, and least-privilege scopes. After compromise, revoke all admin keys (`UPDATE api_keys SET revoked_at=now() ...`) and rotate JWT.
5. A live Stripe key is a financial credential. `GET /v1/payouts` is read-only; still roll the key and webhook secret, pause payouts, review Stripe logs for the request ID/IP, and check bank/external-account/refund events.
6. SSH: restrict 22 to known IPs, review every `authorized_keys` fingerprint, disable password auth, enable fail2ban. The incident was application-level, not SSH, but the same server hosts the payment and admin surfaces.
7. `error-watch` must not count 429 as success. Track `success_rate`, `rate_limit_rate`, and 429 reasons separately; the 2026-11-06 dashboard reported 14,323 “ok” while 11,061 requests were 429.

## Notes

Listed by Plugsky. Skill text and behaviour belong to the upstream author.
If you redistribute it, keep the upstream license and attribution.
