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 | /** * Workspace Session Management * * Provides workspace-scoped authentication sessions with automatic refresh. * Integrates with existing secure credentials system. * * Storage Architecture: * - ~/.snapback/workspaces.json - Workspace session registry (non-sensitive metadata) * - OS Keychain / Encrypted file - Session tokens (sensitive data) * * @module workspace-session */ import { z } from "zod"; // ============================================================================= // ZOD SCHEMAS (Runtime validation) // ============================================================================= export const SessionTokensSchema = z.object({ accessToken: z.string(), refreshToken: z.string(), expiresAt: z.string(), // ISO 8601 sessionId: z.string(), }); export const SessionUserInfoSchema = z.object({ id: z.string(), email: z.string(), name: z.string().optional(), tier: z.enum(["free", "pro", "team", "enterprise"]), organizationId: z.string().optional(), }); export const WorkspaceSessionEntrySchema = z.object({ workspacePath: z.string(), workspaceId: z.string(), session: SessionTokensSchema, user: SessionUserInfoSchema, authMethod: z.enum(["oauth", "device-code", "api-key", "global-fallback"]), createdAt: z.string(), updatedAt: z.string(), lastUsedAt: z.string(), apiKey: z.string().optional(), }); export const WorkspaceSessionRegistrySchema = z.object({ version: z.literal(1), lastCleanupAt: z.string(), workspaces: z.record(z.string(), WorkspaceSessionEntrySchema), global: z .object({ session: SessionTokensSchema, user: SessionUserInfoSchema, authMethod: z.enum(["oauth", "device-code", "api-key", "global-fallback"]), apiKey: z.string().optional(), }) .optional(), }); // ============================================================================= // TYPE DEFINITIONS // ============================================================================= export interface SessionTokens { accessToken: string; refreshToken: string; expiresAt: string; // ISO 8601 sessionId: string; } export interface SessionUserInfo { id: string; email: string; name?: string; tier: "free" | "pro" | "team" | "enterprise"; organizationId?: string; } export interface WorkspaceSessionEntry { workspacePath: string; workspaceId: string; session: SessionTokens; user: SessionUserInfo; authMethod: AuthMethod; createdAt: string; updatedAt: string; lastUsedAt: string; apiKey?: string; } export interface WorkspaceSessionRegistry { version: 1; lastCleanupAt: string; workspaces: Record<string, WorkspaceSessionEntry>; global?: { session: SessionTokens; user: SessionUserInfo; authMethod: AuthMethod; apiKey?: string; }; } export interface WorkspaceSession { workspaceId: string; workspacePath: string; tokens: SessionTokens; user: SessionUserInfo; authMethod: AuthMethod; isValid: boolean; expiresIn: number; // seconds } export interface WorkspaceSessionInfo { workspaceId: string; workspacePath: string; userEmail: string; tier: string; authMethod: AuthMethod; expiresAt: string; lastUsedAt: string; } export type AuthMethod = "oauth" | "device-code" | "api-key" | "global-fallback"; // ============================================================================= // ERROR TYPES // ============================================================================= export class WorkspaceAuthError extends Error { constructor( message: string, public code: WorkspaceAuthErrorCode, public workspaceId?: string, ) { super(message); this.name = "WorkspaceAuthError"; } } export enum WorkspaceAuthErrorCode { SESSION_EXPIRED = "SESSION_EXPIRED", SESSION_REVOKED = "SESSION_REVOKED", REFRESH_FAILED = "REFRESH_FAILED", WORKSPACE_NOT_FOUND = "WORKSPACE_NOT_FOUND", INVALID_WORKSPACE = "INVALID_WORKSPACE", INVALID_CREDENTIALS = "INVALID_CREDENTIALS", NETWORK_ERROR = "NETWORK_ERROR", STORAGE_ERROR = "STORAGE_ERROR", } // ============================================================================= // UTILITY FUNCTIONS // ============================================================================= /** * Generate a stable workspace ID from a path * Uses hash of absolute path for consistency */ export function generateWorkspaceId(workspacePath: string): string { // Simple hash for workspace identification let hash = 0; const str = workspacePath.toLowerCase(); for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32bit integer } return `ws_${Math.abs(hash).toString(36)}`; } /** * Check if session is expired (with optional buffer) */ export function isSessionExpired(expiresAt: string, bufferSeconds = 60): boolean { const expiry = new Date(expiresAt); const buffer = bufferSeconds * 1000; return Date.now() > expiry.getTime() - buffer; } /** * Calculate seconds until expiry */ export function getExpiresIn(expiresAt: string): number { const expiry = new Date(expiresAt); const remaining = expiry.getTime() - Date.now(); return Math.max(0, Math.floor(remaining / 1000)); } /** * Validate workspace session registry */ export function validateRegistry(data: unknown): WorkspaceSessionRegistry | null { const result = WorkspaceSessionRegistrySchema.safeParse(data); return result.success ? result.data : null; } /** * Create empty workspace session registry */ export function createEmptyRegistry(): WorkspaceSessionRegistry { return { version: 1, lastCleanupAt: new Date().toISOString(), workspaces: {}, }; } // ============================================================================= // SESSION CONVERSION HELPERS // ============================================================================= /** * Convert workspace session to legacy GlobalCredentials format * For backwards compatibility with existing code */ export function workspaceSessionToCredentials(session: WorkspaceSessionEntry): { accessToken: string; refreshToken?: string; email: string; tier: "free" | "pro"; expiresAt?: string; } { return { accessToken: session.session.accessToken, refreshToken: session.session.refreshToken, email: session.user.email, tier: session.user.tier === "free" ? "free" : "pro", expiresAt: session.session.expiresAt, }; } /** * Create workspace session from legacy credentials */ export function credentialsToWorkspaceSession( workspacePath: string, credentials: { accessToken: string; refreshToken?: string; email: string; tier: "free" | "pro"; expiresAt?: string; }, authMethod: AuthMethod = "device-code", ): WorkspaceSessionEntry { const workspaceId = generateWorkspaceId(workspacePath); const now = new Date().toISOString(); return { workspacePath, workspaceId, session: { accessToken: credentials.accessToken, refreshToken: credentials.refreshToken || credentials.accessToken, expiresAt: credentials.expiresAt || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), sessionId: `sess_${workspaceId}`, }, user: { id: credentials.email, email: credentials.email, tier: credentials.tier === "free" ? "free" : "pro", }, authMethod, createdAt: now, updatedAt: now, lastUsedAt: now, }; } |