agy-superpowers 5.0.6 → 5.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +23 -0
  2. package/package.json +1 -1
  3. package/template/agent/config.yml +9 -0
  4. package/template/agent/patches/skills-patches.md +74 -0
  5. package/template/agent/skills/api-design/SKILL.md +193 -0
  6. package/template/agent/skills/app-store-optimizer/SKILL.md +127 -0
  7. package/template/agent/skills/auth-and-identity/SKILL.md +167 -0
  8. package/template/agent/skills/backend-developer/SKILL.md +148 -0
  9. package/template/agent/skills/brainstorming/SKILL.md +3 -1
  10. package/template/agent/skills/community-manager/SKILL.md +115 -0
  11. package/template/agent/skills/content-marketer/SKILL.md +111 -0
  12. package/template/agent/skills/conversion-optimizer/SKILL.md +142 -0
  13. package/template/agent/skills/copywriter/SKILL.md +114 -0
  14. package/template/agent/skills/cto-architect/SKILL.md +133 -0
  15. package/template/agent/skills/customer-success-manager/SKILL.md +126 -0
  16. package/template/agent/skills/data-analyst/SKILL.md +147 -0
  17. package/template/agent/skills/devops-engineer/SKILL.md +117 -0
  18. package/template/agent/skills/email-infrastructure/SKILL.md +164 -0
  19. package/template/agent/skills/frontend-developer/SKILL.md +133 -0
  20. package/template/agent/skills/game-design/SKILL.md +194 -0
  21. package/template/agent/skills/game-developer/SKILL.md +175 -0
  22. package/template/agent/skills/growth-hacker/SKILL.md +122 -0
  23. package/template/agent/skills/i18n-localization/SKILL.md +126 -0
  24. package/template/agent/skills/influencer-marketer/SKILL.md +141 -0
  25. package/template/agent/skills/mobile-developer/SKILL.md +142 -0
  26. package/template/agent/skills/monetization-strategist/SKILL.md +119 -0
  27. package/template/agent/skills/paid-acquisition-specialist/SKILL.md +119 -0
  28. package/template/agent/skills/product-manager/SKILL.md +105 -0
  29. package/template/agent/skills/real-time-features/SKILL.md +194 -0
  30. package/template/agent/skills/retention-specialist/SKILL.md +123 -0
  31. package/template/agent/skills/saas-architect/SKILL.md +139 -0
  32. package/template/agent/skills/security-engineer/SKILL.md +133 -0
  33. package/template/agent/skills/seo-specialist/SKILL.md +130 -0
  34. package/template/agent/skills/subagent-driven-development/SKILL.md +7 -3
  35. package/template/agent/skills/subscription-billing/SKILL.md +179 -0
  36. package/template/agent/skills/ux-designer/SKILL.md +128 -0
  37. package/template/agent/workflows/update-superpowers.md +27 -8
package/README.md CHANGED
@@ -130,6 +130,29 @@ This workflow will:
130
130
 
131
131
  ---
132
132
 
133
+ ## Configuration
134
+
135
+ Per-project settings live in `.agent/config.yml`. Create or edit this file in your project's `.agent/` folder:
136
+
137
+ ```yaml
138
+ # .agent/config.yml
139
+
140
+ # auto_commit: true | false
141
+ # When true (default), Superpowers skills automatically commit after completing
142
+ # tasks and writing design docs.
143
+ # When false, all git commits and staging are skipped — files are left as
144
+ # modified for you to commit manually.
145
+ auto_commit: true
146
+ ```
147
+
148
+ | Setting | Default | Description |
149
+ |---|---|---|
150
+ | `auto_commit` | `true` | AI auto-commits after tasks and design docs. Set to `false` to skip all commits. |
151
+
152
+ This file is preserved across `/update-superpowers` runs.
153
+
154
+ ---
155
+
133
156
  ## Installation
134
157
 
135
158
  ### Using This Repo in Your Project
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-superpowers",
3
- "version": "5.0.6",
3
+ "version": "5.0.8",
4
4
  "description": "Superpowers skills library for Google Antigravity agent — scaffold .agent/ with one command",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,9 @@
1
+ # Antigravity Superpowers — Project Config
2
+ #
3
+ # Configure per-project behavior by editing this file.
4
+ # Skills read this file to determine how to behave in this project.
5
+
6
+ # auto_commit: true | false
7
+ # When true (default), AI automatically commits after completing tasks and writing design docs.
8
+ # When false, all git commits and staging are skipped; files are left as modified for manual commit.
9
+ auto_commit: false
@@ -0,0 +1,74 @@
1
+ # Skill Patches
2
+
3
+ Patches applied by AI during the `update-superpowers` workflow (Phase 2, Step 7).
4
+ Each patch describes the *intent* of the change — AI finds the relevant section and rewrites it.
5
+ Do not match text literally. Understand intent and adapt to current upstream wording.
6
+
7
+ ---
8
+
9
+ ## Patch: Platform Adaptation — using-superpowers
10
+
11
+ **File:** `using-superpowers/SKILL.md`
12
+ **Intent:** Remove all references to Claude Code, Gemini CLI, and Codex. Replace with a single
13
+ Antigravity block: skills are read using `view_file` on `.agent/skills/<name>/SKILL.md`.
14
+ Reference `references/antigravity-tools.md` for tool name mappings.
15
+ The Platform Adaptation section should say this package is configured for Google Antigravity,
16
+ with tool name equivalents in `references/antigravity-tools.md`.
17
+
18
+ ---
19
+
20
+ ## Patch: Platform mentions — executing-plans
21
+
22
+ **File:** `executing-plans/SKILL.md`
23
+ **Intent:** Replace any mentions of "Claude Code", "Codex", or other non-Antigravity platforms
24
+ with "Antigravity". Example: "(such as Claude Code or Codex)" → "(such as Antigravity)".
25
+
26
+ ---
27
+
28
+ ## Patch: Skills path — writing-skills
29
+
30
+ **File:** `writing-skills/SKILL.md`
31
+ **Intent:** Replace platform-specific personal skill paths (`~/.claude/skills` for Claude Code,
32
+ `~/.agents/skills/` for Codex) with the Antigravity path: `~/.agent/skills`.
33
+
34
+ ---
35
+
36
+ ## Patch: Visual companion platform blocks — brainstorming
37
+
38
+ **File:** `brainstorming/visual-companion.md`
39
+ **Intent:** Remove the Codex-specific server block. Replace Claude Code and Gemini CLI
40
+ server startup blocks with a single Antigravity block:
41
+ ```bash
42
+ # Launch the server normally
43
+ scripts/start-server.sh --project-dir /path/to/project
44
+ ```
45
+
46
+ ---
47
+
48
+ ## Patch: Platform comment — dispatching-parallel-agents
49
+
50
+ **File:** `dispatching-parallel-agents/SKILL.md`
51
+ **Intent:** Remove the comment `// In Claude Code / AI environment` (or similar platform-specific
52
+ inline comments). The code should work without platform-specific annotations.
53
+
54
+ ---
55
+
56
+ ## Patch: auto_commit flag — brainstorming
57
+
58
+ **File:** `brainstorming/SKILL.md`
59
+ **Intent:** Make the step that commits the design document to git conditional on `.agent/config.yml`:
60
+ - Read `.agent/config.yml` before committing
61
+ - If `auto_commit: true` (default): commit normally with `git add <path> && git commit -m "docs: add <topic> design spec"`
62
+ - If `auto_commit: false`: skip commit and staging entirely. Print: "Skipping commit (auto_commit: false in .agent/config.yml). File is ready for manual commit."
63
+
64
+ ---
65
+
66
+ ## Patch: auto_commit flag — subagent-driven-development
67
+
68
+ **File:** `subagent-driven-development/SKILL.md`
69
+ **Intent:** Make the implementer subagent commit step conditional on `.agent/config.yml`:
70
+ - Read `.agent/config.yml` before committing
71
+ - If `auto_commit: true` (default): commit normally with `git add` + `git commit`
72
+ - If `auto_commit: false`: skip commit and staging entirely. Print: "Skipping commit (auto_commit: false in .agent/config.yml). Files left as modified for manual commit."
73
+ Update any diagram labels that mention "commits" to reflect this conditionality
74
+ (e.g. "commits (if auto_commit: true)").
@@ -0,0 +1,193 @@
1
+ ---
2
+ name: api-design
3
+ description: Use when designing REST or GraphQL APIs, defining versioning strategy, implementing rate limiting, pagination, or writing API documentation
4
+ ---
5
+
6
+ # API Design Lens
7
+
8
+ > **Philosophy:** An API is a contract. Breaking it breaks your users' production systems.
9
+ > Design APIs for the client's needs, not the server's convenience.
10
+
11
+ ---
12
+
13
+ ## Core Instincts
14
+
15
+ - **API contracts are forever** — breaking changes in v1 are unforgivable; version aggressively
16
+ - **Design for the consumer** — the client's workflow, not the server's data model, drives resource design
17
+ - **Idempotency is non-negotiable** — safe to retry = safe to build reliable systems on top of
18
+ - **Errors must be informative** — vague errors waste developer hours
19
+ - **Consistency over cleverness** — a boring, predictable API is a beloved API
20
+
21
+ ---
22
+
23
+ ## REST Resource Design Rules
24
+
25
+ ```
26
+ Resource naming:
27
+ ✅ /users/{id}/projects (noun, plural, hierarchical)
28
+ ❌ /getProjectsForUser/{id} (verb, confusing)
29
+ ❌ /user-projects/{userId} (mixed conventions)
30
+
31
+ HTTP verbs:
32
+ GET /resources → list (paginated)
33
+ GET /resources/{id} → get one
34
+ POST /resources → create
35
+ PUT /resources/{id} → full replace (idempotent)
36
+ PATCH /resources/{id} → partial update
37
+ DELETE /resources/{id} → delete (idempotent)
38
+
39
+ Idempotency:
40
+ GET, PUT, DELETE = always idempotent
41
+ POST = not idempotent by default → use Idempotency-Key header
42
+ ```
43
+
44
+ ---
45
+
46
+ ## HTTP Status Codes (Precise Usage)
47
+
48
+ | Status | Use when | Body |
49
+ |--------|----------|------|
50
+ | 200 | Success, returns data | Resource |
51
+ | 201 | Created | Resource + `Location` header |
52
+ | 204 | Success, no body | Empty |
53
+ | 400 | Malformed request / validation failure | Error with field details |
54
+ | 401 | Missing or invalid auth | Error |
55
+ | 403 | Auth valid, no permission | Error (don't reveal resource existence) |
56
+ | 404 | Resource not found | Error |
57
+ | 409 | Conflict (duplicate, state clash) | Error with conflict detail |
58
+ | 422 | Valid format, business rule violation | Error with reason |
59
+ | 429 | Rate limited | Error + `Retry-After` header |
60
+ | 500 | Unexpected server error | Generic error (log full details server-side) |
61
+
62
+ ---
63
+
64
+ ## Error Response Standard (RFC 7807 / Problem Details)
65
+
66
+ ```json
67
+ {
68
+ "type": "https://docs.myapp.com/errors/validation-failed",
69
+ "title": "Validation Failed",
70
+ "status": 422,
71
+ "detail": "One or more fields are invalid",
72
+ "errors": [
73
+ { "field": "email", "message": "Must be a valid email address" },
74
+ { "field": "name", "message": "Required" }
75
+ ],
76
+ "requestId": "01HX7Y3Z..."
77
+ }
78
+ ```
79
+
80
+ **Always include `requestId`** — allows support to find logs immediately.
81
+
82
+ ---
83
+
84
+ ## Pagination
85
+
86
+ ```
87
+ Offset-based (simple, less scalable):
88
+ GET /users?page=2&limit=20
89
+ ✅ Good for: admin UIs, small datasets
90
+ ❌ Bad for: large datasets (OFFSET N scans N rows)
91
+
92
+ Cursor-based (scalable, real-time safe):
93
+ GET /users?cursor=eyJpZCI6MTIzfQ&limit=20
94
+ Response: { data: [...], nextCursor: "eyJpZCI6MTQzfQ", hasMore: true }
95
+ ✅ Good for: feeds, large datasets, infinite scroll
96
+ ❌ Bad for: jump-to-page UI
97
+
98
+ Default recommendation: Cursor-based with opaque base64 cursors.
99
+ Expose total count only when necessary (expensive for large tables).
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Rate Limiting
105
+
106
+ ```
107
+ Strategy: Token bucket or sliding window
108
+
109
+ Headers to include:
110
+ X-RateLimit-Limit: 1000 (max requests per window)
111
+ X-RateLimit-Remaining: 847 (requests left)
112
+ X-RateLimit-Reset: 1711234567 (Unix timestamp when window resets)
113
+ Retry-After: 60 (seconds to wait, on 429 only)
114
+
115
+ Recommended limits for SaaS APIs:
116
+ Authenticated: 1000 req/min per user
117
+ Unauthenticated: 60 req/min per IP
118
+ Sensitive (auth endpoints): 5 req/15min per IP
119
+ ```
120
+
121
+ ---
122
+
123
+ ## API Versioning
124
+
125
+ ```
126
+ Strategy options:
127
+ URL versioning: /v1/users ← RECOMMENDED (explicit, cacheable)
128
+ Header versioning: Accept: application/vnd.myapp.v1+json (less visible)
129
+ Query param: /users?version=1 (ugly, cache issues)
130
+
131
+ Breaking vs non-breaking changes:
132
+ Non-breaking (safe without versioning):
133
+ ✅ Adding new optional fields to response
134
+ ✅ Adding new optional request parameters
135
+ ✅ Adding new endpoints
136
+
137
+ Breaking (requires new version):
138
+ ❌ Removing fields from response
139
+ ❌ Changing field types
140
+ ❌ Changing endpoint behavior
141
+ ❌ Renaming fields
142
+ ```
143
+
144
+ ---
145
+
146
+ ## ❌ Anti-Patterns to Avoid
147
+
148
+ | ❌ NEVER DO | Why | ✅ DO INSTEAD |
149
+ |------------|-----|--------------|
150
+ | Return 200 for errors | Clients parse status codes; 200 failure = broken integrations | Use correct status codes |
151
+ | Expose internal IDs (auto-increment integers) | Enumerable, leaks count of records | UUIDs always |
152
+ | Breaking changes without versioning | Clients' production breaks silently | `/v2/` or deprecation period |
153
+ | Unbounded list endpoints | OOM at scale | Always paginate; default limit 20, max 100 |
154
+ | Verbose errors in production | Leaks internals to attackers | Generic message to client; details in server logs only |
155
+ | Synchronous long-running operations | Timeout at 30s+, bad UX | Accept → 202 Accepted → polling or webhook |
156
+
157
+ ---
158
+
159
+ ## Questions You Always Ask
160
+
161
+ **When designing a new endpoint:**
162
+ - Is this resource name a noun (not a verb)?
163
+ - What's the idempotency story? Can the client safely retry?
164
+ - What's the pagination strategy? What's the max page size?
165
+ - Is this a breaking change to existing consumers?
166
+
167
+ ---
168
+
169
+ ## Red Flags
170
+
171
+ **Must fix:**
172
+ - [ ] `200 OK` returned for error responses
173
+ - [ ] No pagination on list endpoints
174
+ - [ ] Auto-increment integer IDs exposed
175
+ - [ ] Breaking API change without version bump
176
+
177
+ **Should fix:**
178
+ - [ ] No rate limiting on public endpoints
179
+ - [ ] Error responses without field-level details
180
+ - [ ] No `requestId` in error responses (prevents support lookup)
181
+ - [ ] No OpenAPI/Swagger spec
182
+
183
+ ---
184
+
185
+ ## Who to Pair With
186
+ - `backend-developer` — for implementation of API patterns
187
+ - `auth-and-identity` — for auth design on API endpoints
188
+ - `saas-architect` — for multi-tenant API context
189
+
190
+ ---
191
+
192
+ ## Tools
193
+ OpenAPI / Swagger (spec) · Scalar / Stoplight (docs) · Hono / Fastify / Express (Node.js) · Zod / Joi (validation) · `express-rate-limit` / Upstash Rate Limit · Postman / Insomnia (testing)
@@ -0,0 +1,127 @@
1
+ ---
2
+ name: app-store-optimizer
3
+ description: Use when working on App Store / Google Play listing optimization, keyword strategy, screenshots, ratings, or app store A/B testing
4
+ ---
5
+
6
+ # App Store Optimizer Lens
7
+
8
+ > **Philosophy:** ASO is SEO for app stores. Discoverability + conversion = downloads.
9
+ > Most apps lose 60%+ of potential downloads to a weak listing, not a weak product.
10
+
11
+ ---
12
+
13
+ ## Core Instincts
14
+
15
+ - **Title keyword is the highest-ranking signal** — include your primary keyword in the title
16
+ - **First 3 screenshots convert or kill** — most users never scroll past them
17
+ - **Ratings velocity > average rating** — a burst of fresh 5-stars beats a stale 4.8
18
+ - **Keyword field is invisible to users but critical to ranking** — use every character
19
+ - **Localize for top markets** — EN + your top 3 markets = 80% of opportunity
20
+
21
+ ---
22
+
23
+ ## Platform Limits (Know These Cold)
24
+
25
+ ### iOS App Store
26
+ | Field | Limit | Notes |
27
+ |-------|-------|-------|
28
+ | Title | **30 chars** | Primary keyword weight = 2× |
29
+ | Subtitle | **30 chars** | Secondary keyword, benefit-focused |
30
+ | Keywords | **100 chars** | Comma-separated, no spaces, no repeats from title |
31
+ | Description | **4000 chars** | First **255 chars** shown before "more" |
32
+ | Promo text | **170 chars** | Updates without review; use for time-limited offers |
33
+ | Screenshots | Up to **10** | Sizes vary by device; first 3 drive 80% of conversion |
34
+ | Preview video | **15–30 seconds** | First 3 seconds must hook without sound |
35
+
36
+ ### Google Play
37
+ | Field | Limit | Notes |
38
+ |-------|-------|-------|
39
+ | Title | **30 chars** | Keyword-rich |
40
+ | Short description | **80 chars** | Shown in search; make it scannable |
41
+ | Long description | **4000 chars** | First 167 chars auto-expanded; repeat keyword 3–5× |
42
+ | Screenshots | Up to **8** | 16:9 or 9:16 preferred |
43
+ | Feature graphic | **1024 × 500px** | Shown in featured slots |
44
+
45
+ ---
46
+
47
+ ## ❌ Anti-Patterns to Avoid
48
+
49
+ | ❌ NEVER DO | Why | ✅ DO INSTEAD |
50
+ |------------|-----|--------------|
51
+ | Title = just the brand name | Zero keyword signal | Brand + primary keyword (e.g., "Todoist: To-Do List & Tasks") |
52
+ | Leave keywords field blank (iOS) | 100 chars of free ranking wasted | Fill every character with non-title keywords |
53
+ | First screenshot = app logo splash | Users bounce, no context | First screenshot = core value prop as hero text |
54
+ | Ask for review on first open | Users hate it, Apple rejects manipulative prompts | Ask after a success action (task completed, streak hit) |
55
+ | Ignore 1-star reviews | Review responses shown publicly; silence = neglect | Respond within 48h; apologize + explain fix |
56
+ | Use keywords that appear in title (iOS) | Apple ignores duplicates | Every keyword field word must be unique |
57
+ | Generic description | No differentiation, no keywords | Keyword-rich first paragraph, benefit bullets |
58
+
59
+ ---
60
+
61
+ ## Keyword Research Process
62
+
63
+ 1. **Seed keywords** — brainstorm 20–30 relevant terms
64
+ 2. **Competitor analysis** — check top 5 competitor titles/subtitles
65
+ 3. **Volume + difficulty** — use Sensor Tower / AppTweak / AppFollow to score
66
+ 4. **Priority matrix** — High volume + Low difficulty = target first
67
+ 5. **Long-tail focus** — easier to rank for "meditation app for anxiety" than "meditation"
68
+ 6. **Update every 60–90 days** — track rank changes, iterate
69
+
70
+ ---
71
+
72
+ ## Ratings Strategy
73
+
74
+ **When to prompt:** After user completes a meaningful success action, NOT on launch.
75
+ - Good triggers: completed task, reached streak, finished session, saved something
76
+ - Bad triggers: app open, screen view, after onboarding
77
+
78
+ **Target benchmarks:**
79
+ | Metric | Floor | Target |
80
+ |--------|-------|--------|
81
+ | Average rating | > 4.0 | > 4.5 |
82
+ | Review count (for featuring) | > 100 | > 500 |
83
+ | Response rate to 1-star | — | > 80% within 48h |
84
+
85
+ **Recovering from bad ratings:** Respond to every 1-star, release fix quickly, request updated review from resolved users.
86
+
87
+ ---
88
+
89
+ ## Questions You Always Ask
90
+
91
+ **When auditing a listing:**
92
+ - Is the primary keyword in the title?
93
+ - Do the first 3 screenshots tell a complete story without reading any text?
94
+ - Is the keyword field 100% utilized (iOS)?
95
+ - What's the current conversion rate from impression to download? (Benchmark: 3–7%)
96
+
97
+ **When planning ASO strategy:**
98
+ - Which markets are we localizing for?
99
+ - What keywords are competitors ranking for that we're missing?
100
+ - When was the last time we A/B tested screenshots?
101
+
102
+ ---
103
+
104
+ ## Red Flags
105
+
106
+ **Must fix:**
107
+ - [ ] Title is brand name only (no keyword)
108
+ - [ ] iOS keyword field < 90 characters used
109
+ - [ ] First screenshot is a splash screen or abstract illustration
110
+ - [ ] No response to 1-star reviews
111
+
112
+ **Should fix:**
113
+ - [ ] Description first 255 chars (iOS) / 167 chars (Play) not benefit-focused
114
+ - [ ] No preview video
115
+ - [ ] Listing not localized for top 3 markets
116
+
117
+ ---
118
+
119
+ ## Who to Pair With
120
+ - `copywriter` — for listing copy strategy
121
+ - `growth-hacker` — for launch burst strategy (ratings velocity)
122
+ - `conversion-optimizer` — for screenshot A/B testing
123
+
124
+ ---
125
+
126
+ ## Tools
127
+ AppFollow · Sensor Tower · AppTweak · AppFigures · MobileAction · Apple Search Ads Intelligence
@@ -0,0 +1,167 @@
1
+ ---
2
+ name: auth-and-identity
3
+ description: Use when implementing authentication, authorization, SSO/SAML/OIDC, multi-tenant identity, session management, or role-based access control for a SaaS product
4
+ ---
5
+
6
+ # Auth & Identity Lens
7
+
8
+ > **Philosophy:** Authentication proves who you are. Authorization proves what you can do.
9
+ > Mixing them up is the most common source of privilege escalation bugs.
10
+
11
+ ---
12
+
13
+ ## Core Instincts
14
+
15
+ - **AuthN ≠ AuthZ** — always handle them as separate concerns
16
+ - **Every request must be authenticated AND authorized** — auth middleware is not authorization
17
+ - **Tenant context must be established on every request** — after AuthN, before any DB query
18
+ - **Fail closed** — when in doubt, deny; never default to permissive
19
+ - **Never roll your own crypto** — use proven libraries and protocols
20
+
21
+ ---
22
+
23
+ ## Multi-Tenant Auth Flow
24
+
25
+ ```
26
+ Request arrives →
27
+ 1. Verify token/session (AuthN) → get user_id
28
+ 2. Load user + tenant membership → get tenant_id, role
29
+ 3. Set tenant context (RLS / app context)
30
+ 4. Check permission for this route/resource (AuthZ)
31
+ 5. Execute request
32
+ ```
33
+
34
+ **Order matters:** If you skip step 3, RLS doesn't know which tenant. If you skip step 4, any authenticated user can do anything.
35
+
36
+ ---
37
+
38
+ ## Auth Strategy Selection
39
+
40
+ | Method | Best for | Not for |
41
+ |--------|----------|---------|
42
+ | **JWT (stateless)** | Stateless APIs, microservices | When you need instant revocation |
43
+ | **Session cookie** | Web apps, SSR | Mobile-first or API-only |
44
+ | **API key** | Machine-to-machine, developer APIs | User-facing login |
45
+ | **SAML 2.0** | Enterprise SSO (Okta, Azure AD) | Consumer apps |
46
+ | **OIDC / OAuth 2.0** | Social login, federated identity | Internal-only systems |
47
+
48
+ **Indie hacker default:** Session cookies for web (HttpOnly, Secure, SameSite=Strict) + JWT for API endpoints.
49
+
50
+ ---
51
+
52
+ ## JWT Rules
53
+
54
+ ```
55
+ Access token:
56
+ - Expiry: 15 minutes (short-lived; compromised → limited damage window)
57
+ - Payload: user_id, tenant_id, role, exp — NO sensitive data
58
+ - Store: Memory (never localStorage) or HttpOnly cookie
59
+
60
+ Refresh token:
61
+ - Expiry: 7–30 days
62
+ - Store: HttpOnly cookie ONLY
63
+ - Rotate on every use (refresh token rotation)
64
+ - Invalidate all refresh tokens on password change/logout all
65
+
66
+ Signing:
67
+ - Algorithm: RS256 (asymmetric, allows public verification) or HS256 (simpler, shared secret)
68
+ - Secret: ≥ 32 random bytes; rotate if compromised (support multiple valid secrets during rotation)
69
+ ```
70
+
71
+ ---
72
+
73
+ ## RBAC Pattern (Role-Based Access Control)
74
+
75
+ ```typescript
76
+ // Roles per tenant membership (not global)
77
+ type TenantRole = 'owner' | 'admin' | 'member' | 'viewer';
78
+
79
+ // Permissions defined as capability strings
80
+ const PERMISSIONS = {
81
+ owner: ['billing:manage', 'members:manage', 'data:delete', 'data:write', 'data:read'],
82
+ admin: ['members:manage', 'data:write', 'data:read'],
83
+ member: ['data:write', 'data:read'],
84
+ viewer: ['data:read'],
85
+ } satisfies Record<TenantRole, string[]>;
86
+
87
+ // Check at every protected route/action
88
+ function can(user: User, permission: string): boolean {
89
+ return PERMISSIONS[user.tenantRole]?.includes(permission) ?? false;
90
+ }
91
+ ```
92
+
93
+ ---
94
+
95
+ ## SSO / SAML Integration (Enterprise)
96
+
97
+ ```
98
+ When to build SAML:
99
+ - Enterprise customers require it (Okta, Azure AD, Google Workspace)
100
+ - Single "SAML" request in a deal is worth building immediately
101
+
102
+ Implementation options for indie hackers:
103
+ 1. WorkOS — $0 to start, pay per enterprise connection; fastest path
104
+ 2. Auth0 / Clerk — SAML add-on; higher cost at scale
105
+ 3. Roll your own — samlify / passport-saml; significant complexity
106
+
107
+ SAML Flow:
108
+ User → Your SP (Service Provider) → IdP (Okta/AzureAD) → SAML assertion → SP → Session
109
+ ```
110
+
111
+ ---
112
+
113
+ ## ❌ Anti-Patterns to Avoid
114
+
115
+ | ❌ NEVER DO | Why | ✅ DO INSTEAD |
116
+ |------------|-----|--------------|
117
+ | JWT in `localStorage` | XSS attack steals token, unlimited access | `HttpOnly` cookie |
118
+ | Long-lived access tokens (> 1 hour) | Compromised token = long exposure window | 15 min expiry + refresh token rotation |
119
+ | Storing passwords as anything but bcrypt/argon2id | Rainbow table crack in seconds | bcrypt cost ≥12 or argon2id |
120
+ | Checking auth at route level only | Bypassed by internal calls | Check permissions at the service/data layer |
121
+ | Global admin role without per-tenant scope | One compromised admin = all tenants affected | Admin role always scoped to a tenant |
122
+ | No rate limiting on auth endpoints | Brute force, credential stuffing | Max 5 attempts / 15 min per IP |
123
+ | Email as unique identifier across tenants | Same email in multiple tenants = collision | `(email, tenant_id)` composite unique |
124
+
125
+ ---
126
+
127
+ ## Questions You Always Ask
128
+
129
+ **When designing auth:**
130
+ - Is tenant context established before any DB query happens?
131
+ - Does AuthZ happen at the service layer, not just route middleware?
132
+ - Are refresh tokens rotated on every use?
133
+ - What's the logout flow? Does it invalidate server-side session/refresh token?
134
+
135
+ **When adding a new role or permission:**
136
+ - Is this the least privilege needed for this action?
137
+ - Have we tested that a lower-privileged role cannot access this?
138
+
139
+ ---
140
+
141
+ ## Red Flags
142
+
143
+ **Must fix:**
144
+ - [ ] JWT stored in `localStorage`
145
+ - [ ] No tenant_id in auth context (tenant isolation can't work)
146
+ - [ ] Authorization only checked at route level (not service/data layer)
147
+ - [ ] No rate limiting on `/login`, `/forgot-password`, `/reset-password`
148
+
149
+ **Should fix:**
150
+ - [ ] Refresh tokens not rotated on use
151
+ - [ ] No MFA option for admin/owner roles
152
+ - [ ] Email uniqueness checked globally (not per-tenant)
153
+
154
+ ---
155
+
156
+ ## Who to Pair With
157
+ - `saas-architect` — for tenant context in data model
158
+ - `security-engineer` — for token storage and auth security audit
159
+ - `backend-developer` — for middleware and session management
160
+
161
+ ---
162
+
163
+ ## Tools
164
+ **Hosted auth:** Clerk · Auth0 · Supabase Auth · Firebase Auth
165
+ **Self-hosted:** NextAuth.js / Auth.js · Lucia · Better Auth
166
+ **Enterprise SSO:** WorkOS · Boxyhq (open source)
167
+ **Libraries:** `jose` (JWT) · `bcrypt` / `argon2` (passwords) · `samlify` (SAML)