Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | // Core authentication and authorization utilities for Snapback // Wraps Better Auth with additional security layers import { apiKeys, apiUsage, db } from "@snapback/platform"; import { and, avg, count, eq, gte, lt, lte } from "drizzle-orm"; // Import and re-export auth from auth.ts // Auth has proper plugin API types (createApiKey, verifyApiKey, etc.) export { auth, type SnapBackAuthAPI } from "./auth"; // Re-export business logic functions export { checkOrgMembership, getUserOrgIds, getUserPermissions, getUserPlan, hasPermission, type SubscriptionPlan, } from "./business/index"; // ============================================================================ // TYPES // ============================================================================ export interface User { id: string; email: string; name?: string; subscriptionTier: "free" | "pro" | "team" | "enterprise"; organizationId?: string; } export interface ApiKey { id: string; userId: string; key?: string; // Only returned on creation keyHash: string; keyPreview: string; name: string; lastUsedAt?: Date | null; createdAt: Date; expiresAt?: Date | null; revokedAt?: Date | null; scopes: string[]; rateLimit: number; } export interface RateLimitResult { allowed: boolean; remaining: number; resetAt: Date; retryAfter?: number; } export interface UsageRecord { userId: string; apiKeyId: string; endpoint: string; timestamp: Date; statusCode: number; responseTime: number; } export interface SubscriptionLimits { snapshotsPerMonth: number; storageRetentionDays: number; protectedFiles: number; teamSeats: number; apiRateLimit: number; } export interface CreateApiKeyParams { userId: string; name: string; scopes?: string[]; rateLimit?: number; expiresAt?: Date; } export interface ValidationResult { valid: boolean; user?: User; scopes?: string[]; error?: string; } // ============================================================================ // API KEY MANAGEMENT - REMOVED // ✅ All API key operations now go through Better Auth apiKey() plugin. // See: packages/auth/src/auth.ts for the canonical implementation // // Usage: // import { auth } from "@snapback/auth"; // await auth.api.createApiKey({ body: { name, userId, permissions } }); // await auth.api.verifyApiKey({ body: { key, permissions } }); // await auth.api.deleteApiKey({ body: { keyId } }); // ============================================================================ // ============================================================================ // RATE LIMITING // ============================================================================ /** * In-memory rate limiter (for development/small scale) */ export class InMemoryRateLimiter { private store = new Map<string, { count: number; resetAt: number }>(); async checkLimit(key: string, limit: number, windowMs: number): Promise<RateLimitResult> { const now = Date.now(); const record = this.store.get(key); // No previous record or window expired if (!record || record.resetAt < now) { const resetAt = new Date(now + windowMs); this.store.set(key, { count: 1, resetAt: resetAt.getTime(), }); return { allowed: true, remaining: limit - 1, resetAt, }; } // Within window if (record.count < limit) { record.count++; this.store.set(key, record); return { allowed: true, remaining: limit - record.count, resetAt: new Date(record.resetAt), }; } // Limit exceeded const retryAfter = Math.ceil((record.resetAt - now) / 1000); return { allowed: false, remaining: 0, resetAt: new Date(record.resetAt), retryAfter, }; } clear() { this.store.clear(); } // Cleanup expired entries (call periodically) cleanup() { const now = Date.now(); for (const [key, record] of this.store.entries()) { if (record.resetAt < now) { this.store.delete(key); } } } } /** * Redis-backed rate limiter (for production) */ export class RedisRateLimiter { constructor(private redis: any) {} // biome-ignore lint/suspicious/noExplicitAny: Redis client type varies by implementation async checkLimit(key: string, limit: number, windowMs: number): Promise<RateLimitResult> { const redisKey = `ratelimit:${key}`; const windowSeconds = Math.ceil(windowMs / 1000); try { // Get current count const current = await this.redis.get(redisKey); if (!current) { // First request in window await this.redis.set(redisKey, "1", "EX", windowSeconds); return { allowed: true, remaining: limit - 1, resetAt: new Date(Date.now() + windowMs), }; } const count = Number.parseInt(current, 10); if (count < limit) { // Increment counter await this.redis.incr(redisKey); // Get TTL for reset time const ttl = await this.redis.ttl(redisKey); return { allowed: true, remaining: limit - count - 1, resetAt: new Date(Date.now() + ttl * 1000), }; } // Limit exceeded const ttl = await this.redis.ttl(redisKey); return { allowed: false, remaining: 0, resetAt: new Date(Date.now() + ttl * 1000), retryAfter: ttl, }; } catch (_error) { // Fail open - allow request if Redis is down return { allowed: true, remaining: limit, resetAt: new Date(Date.now() + windowMs), }; } } } /** * Get rate limits based on subscription tier */ export function getRateLimitByTier(tier: string): SubscriptionLimits { const limits: Record<string, SubscriptionLimits> = { free: { snapshotsPerMonth: 1000, storageRetentionDays: 7, protectedFiles: 5, teamSeats: 1, apiRateLimit: 10, // 10 req/min }, pro: { snapshotsPerMonth: 5000, storageRetentionDays: 30, protectedFiles: 25, teamSeats: 1, apiRateLimit: 50, // 50 req/min }, team: { snapshotsPerMonth: 100000, storageRetentionDays: 365, protectedFiles: 500, teamSeats: 10, apiRateLimit: 500, // 500 req/min }, enterprise: { snapshotsPerMonth: -1, // Unlimited storageRetentionDays: -1, // Custom protectedFiles: -1, // Unlimited teamSeats: -1, // Unlimited apiRateLimit: 5000, // 5000 req/min }, }; const result = limits[tier] ?? limits.free; return result as SubscriptionLimits; } // ============================================================================ // USAGE TRACKING // ============================================================================ /** * Track API usage */ export async function trackUsage(usage: UsageRecord): Promise<void> { if (!db) { throw new Error("Database not initialized"); } await db.insert(apiUsage).values({ apiKeyId: usage.apiKeyId, endpoint: usage.endpoint, method: "GET", // Default for now statusCode: usage.statusCode, metadata: {}, timestamp: usage.timestamp, }); } /** * Get usage statistics for a time period */ export async function getUsageStats(userId: string, startDate: Date, endDate: Date) { if (!db) { throw new Error("Database not initialized"); } // Get total requests const totalRequestsResult = await db .select({ count: count() }) .from(apiUsage) .innerJoin(apiKeys, eq(apiKeys.id, apiUsage.apiKeyId)) .where(and(eq(apiKeys.userId, userId), gte(apiUsage.timestamp, startDate), lte(apiUsage.timestamp, endDate))); const totalRequests = totalRequestsResult[0]?.count || 0; // Get successful requests (2xx status codes) const successfulRequestsResult = await db .select({ count: count() }) .from(apiUsage) .innerJoin(apiKeys, eq(apiKeys.id, apiUsage.apiKeyId)) .where( and( eq(apiKeys.userId, userId), gte(apiUsage.timestamp, startDate), lte(apiUsage.timestamp, endDate), gte(apiUsage.statusCode, 200), lt(apiUsage.statusCode, 300), ), ); const successfulRequests = successfulRequestsResult[0]?.count || 0; // Get average response time const avgResponseResult = await db .select({ avg: avg(apiUsage.id) }) // Simplified for now .from(apiUsage) .innerJoin(apiKeys, eq(apiKeys.id, apiUsage.apiKeyId)) .where(and(eq(apiKeys.userId, userId), gte(apiUsage.timestamp, startDate), lte(apiUsage.timestamp, endDate))); const avgResponseTime = avgResponseResult[0]?.avg || 0; return { totalRequests, successfulRequests, successRate: totalRequests > 0 ? successfulRequests / totalRequests : 0, avgResponseTime, }; } /** * Check if user is within usage limits */ export async function checkUsageLimits(userId: string, tier: string) { const limits = getRateLimitByTier(tier); // Unlimited for enterprise if (limits.snapshotsPerMonth === -1) { return { allowed: true, remaining: -1, percentUsed: 0, }; } // Get current month usage const startOfMonth = new Date(); startOfMonth.setDate(1); startOfMonth.setHours(0, 0, 0, 0); if (!db) { throw new Error("Database not initialized"); } const usageResult = await db .select({ count: count() }) .from(apiUsage) .innerJoin(apiKeys, eq(apiKeys.id, apiUsage.apiKeyId)) .where(and(eq(apiKeys.userId, userId), gte(apiUsage.timestamp, startOfMonth))); const usage = usageResult[0]?.count || 0; const remaining = Math.max(0, limits.snapshotsPerMonth - usage); const percentUsed = (usage / limits.snapshotsPerMonth) * 100; return { allowed: usage < limits.snapshotsPerMonth, remaining, percentUsed, warning: percentUsed >= 80, upgradeRequired: usage >= limits.snapshotsPerMonth, }; } // ============================================================================ // TEAM DETECTION // ============================================================================ const CONSUMER_EMAIL_DOMAINS = ["gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "icloud.com", "protonmail.com"]; /** * Detect if user is part of a potential team */ export async function detectPotentialTeam( db: any, // biome-ignore lint/suspicious/noExplicitAny: Database client type varies by implementation userId: string, email: string, metadata?: any, // biome-ignore lint/suspicious/noExplicitAny: Metadata structure is dynamic ): Promise<{ isTeam: boolean; teamMembers?: any[]; confidence?: string; suggestedAction?: string; reason?: string | null; }> { const domain = email.split("@")[1]; // Skip consumer email domains if (domain && CONSUMER_EMAIL_DOMAINS.includes(domain)) { return { isTeam: false, reason: "Consumer email domain", }; } // Find other users with same domain const sameOrgUsers = await db.user.findMany({ where: { email: { endsWith: `@${domain}`, }, id: { not: userId, }, }, }); if (sameOrgUsers.length >= 2) { return { isTeam: true, teamMembers: sameOrgUsers, confidence: "high", suggestedAction: "upgrade_to_team", }; } // Check for shared project patterns if (metadata?.repositoryUrl) { const sharedRepoUsers = await db.user.findMany({ where: { // This would need a proper schema field // metadata: { contains: metadata.repositoryUrl } }, }); if (sharedRepoUsers.length >= 1) { return { isTeam: true, teamMembers: sharedRepoUsers, confidence: "medium", suggestedAction: "upgrade_to_team", }; } } return { isTeam: false, reason: "Insufficient team indicators", }; } /** * Calculate team upgrade recommendation */ export function suggestTeamUpgrade(individualUsers: number) { const individualCost = individualUsers * 19; // $19/mo per Solo user const teamCost = individualUsers * 49; // $49/mo per Team seat return { currentCost: individualCost, teamCost, monthlySavings: Math.max(0, individualCost - teamCost), recommended: individualUsers >= 3, breakEvenUsers: 3, features: [ "Shared snapshots", "Team analytics", "Centralized billing", "Role-based access", "Priority support", ], }; } // ============================================================================ // SUBSCRIPTION VALIDATION // ============================================================================ /** * Validate user's subscription status */ export async function validateSubscription( db: any, // biome-ignore lint/suspicious/noExplicitAny: Database client type varies by implementation userId: string, ): Promise<{ valid: boolean; tier: string; expiresAt?: Date; gracePeriod?: boolean; daysRemaining?: number; reason?: string; }> { const subscription = await db.purchase.findFirst({ where: { userId, status: { in: ["active", "trialing", "past_due", "canceled"], }, }, orderBy: { createdAt: "desc", }, }); if (!subscription) { return { valid: true, tier: "free", }; } const now = new Date(); const periodEnd = subscription.currentPeriodEnd; // Subscription is valid until period end, even if canceled if (periodEnd && periodEnd > now) { const daysRemaining = Math.ceil((periodEnd.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)); return { valid: true, tier: subscription.tier, expiresAt: periodEnd, gracePeriod: subscription.status === "canceled", daysRemaining, }; } // Expired return { valid: false, tier: subscription.tier, reason: "Subscription expired", }; } /** * Check if user has access to a specific feature */ export function checkFeatureAccess(tier: string, feature: string) { const featureMap: Record<string, string> = { api_access: "pro", team_collaboration: "team", sso: "enterprise", audit_logs: "enterprise", custom_retention: "enterprise", advanced_analytics: "team", priority_support: "pro", }; const requiredTier = featureMap[feature]; if (!requiredTier) { return { allowed: true }; // Feature doesn't exist or is free } const tierHierarchy = ["free", "pro", "team", "enterprise"]; const userTierIndex = tierHierarchy.indexOf(tier); const requiredTierIndex = tierHierarchy.indexOf(requiredTier); if (userTierIndex >= requiredTierIndex) { return { allowed: true }; } return { allowed: false, requiredTier, upgradeUrl: `/upgrade?plan=${requiredTier}`, }; } // ============================================================================ // MIDDLEWARE HELPERS // ============================================================================ /** * Express/Next.js middleware to validate API key */ interface ApiRequest { headers: Record<string, string | string[] | undefined>; connection?: { remoteAddress?: string }; socket?: { remoteAddress?: string }; user?: unknown; scopes?: string[]; } interface ApiResponse { status(code: number): this; json(data: unknown): this; setHeader(name: string, value: string | number): this; } type NextFunction = () => void; /** * Express/Next.js middleware to validate API key using Better Auth * * NOTE: Better Auth has built-in rate limiting via apiKey() plugin. * The rateLimiter parameter is kept for backwards compatibility but * Better Auth's rate limiting should be preferred. */ export function requireApiKey(_rateLimiter?: RedisRateLimiter) { return async (req: ApiRequest, res: ApiResponse, next: NextFunction) => { const authHeader = req.headers.authorization; const apiKey = Array.isArray(authHeader) ? authHeader[0]?.replace("Bearer ", "") : authHeader?.replace("Bearer ", ""); if (!apiKey) { return res.status(401).json({ error: "API key required" }); } // Import auth lazily to avoid circular dependencies const { auth } = await import("./auth"); // Type assertion for Better Auth plugin API (see better-auth-adapter.ts for details) const api = auth.api as typeof auth.api & { verifyApiKey?: (params: { body: { key: string } }) => Promise<any>; }; try { // Use Better Auth's verifyApiKey - handles: // - Hash verification (Argon2) // - Expiration checking // - Revocation status // - Rate limiting (built-in) // - Permission validation if (!api.verifyApiKey) { return res.status(500).json({ error: "API key verification not configured" }); } const result = await api.verifyApiKey({ body: { key: apiKey, }, }); if (!result.valid) { return res.status(401).json({ error: result.error?.message || "Invalid API key" }); } // Attach user info to request req.user = { id: result.key?.userId, // Additional user info can be fetched if needed }; // Extract scopes from permissions req.scopes = result.key?.permissions ? Object.keys(result.key.permissions) : []; // Set rate limit headers from Better Auth response if (result.key?.rateLimitEnabled) { const limits = getRateLimitByTier("pro"); // Default to pro limits res.setHeader("X-RateLimit-Limit", result.key.rateLimitMax || limits.apiRateLimit); res.setHeader("X-RateLimit-Remaining", result.key.remaining || 0); if (result.key.lastRefillAt) { res.setHeader("X-RateLimit-Reset", new Date(result.key.lastRefillAt).toISOString()); } } next(); return; } catch (error) { console.error("[requireApiKey] Better Auth error:", error); return res.status(500).json({ error: "Authentication service unavailable" }); } }; } export { AuthError, InsufficientRoleError, InsufficientScopesError, } from "./errors"; // Extension JWT authentication export type { ExtensionAccessTokenPayload, ExtensionAuthContext, } from "./lib/extension-jwt"; export { decodeExtensionAccessToken, signExtensionAccessToken, verifyExtensionAccessToken, } from "./lib/extension-jwt"; export type { PlanPermissions } from "./plan"; export { getPlanPermissions, mapUserToPlan } from "./plan"; export type { PlanId, SnapbackAuth, SnapbackAuthContext, UserRole, } from "./shared-auth"; export { snapbackAuth } from "./shared-auth-impl"; // ============================================================================ // WORKSPACE SESSION MANAGEMENT // ============================================================================ // NOTE: Workspace storage functions with keytar (native module) are in a separate // entry point to avoid bundling issues in web builds. // For CLI/Extension, use: import { ... } from "@snapback/auth/workspace" // Types are safe to export (no keytar dependency) export type { AuthMethod, SessionTokens, SessionUserInfo, WorkspaceSession, WorkspaceSessionEntry, WorkspaceSessionInfo, WorkspaceSessionRegistry, } from "./workspace-session"; // Pure functions without keytar are safe to export export { credentialsToWorkspaceSession, generateWorkspaceId, getExpiresIn, isSessionExpired, WorkspaceAuthError, WorkspaceAuthErrorCode, workspaceSessionToCredentials, } from "./workspace-session"; // Workspace session manager types only (implementation in ./workspace) export type { WorkspaceSessionManagerOptions } from "./workspace-session-manager"; |