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 | 256x 256x 93x 256x | /**
* Session Storage Types
*
* Interfaces for pluggable session storage backends.
* Supports in-memory, file-based, and database storage.
*/
import {
OAuthSession,
DeviceFlowState,
AuthCodeFlowState,
AuthorizationCode,
RegisteredOAuthClient,
GitLabTokenResponse,
} from '../types';
import type { AccountSettings, AccountSettingsRecord } from '../../configuration/types';
/** How long a session lives from its creation; cleanup removes it after that. */
export const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
/** Whether a session (not a linked account, which goes with it) is past its age limit. */
export function isPastAgeLimit(session: OAuthSession, now = Date.now()): boolean {
return session.createdAt + SESSION_MAX_AGE_MS < now;
}
/**
* Ends the GitLab grant of an auth code flow removed unfinished. Rejects when the grant
* could not be ended; the backend then keeps the flow, its only copy, for the next cleanup.
* Rotated credentials are durably kept through persistTokens for retries. If persistence
* is unavailable, the handler can finish only after successfully revoking the new grant.
*/
export type AbandonedFlowGrantHandler = (
flow: AuthCodeFlowState,
/** Durably replace rotated credentials while the backend still owns this flow. */
persistTokens: (tokens: GitLabTokenResponse) => Promise<void>,
/** Shared lease expiry; absent when local ownership cannot expire during the handler. */
leaseUntil?: number,
) => Promise<void>;
/** Removes a session that reached its age limit with its linked accounts, ending their grants. */
export type ExpiredSessionHandler = (session: OAuthSession) => Promise<void>;
/** Inputs to the single storage commit of a browser-verified account link. */
export interface LinkedAccountCommit {
/** Server-generated key of the unexpired connect flow, consumed only on success. */
internalState: string;
/** Exact primary-session lease claimed by this callback, in epoch milliseconds. */
primaryLeaseUntil: number;
/** New account record; on replacement only its grant and username are updated. */
account: OAuthSession & { linkedToSessionId: string };
/** Absent for insertion; replacement must still own this exact account grant and lease. */
existing?: { refreshToken: string; leaseUntil: number };
}
/**
* Session storage backend interface
*
* All storage backends must implement this interface for session persistence.
* Operations are async to support network-based storage (PostgreSQL, Redis).
*
* Methods returning a boolean report a missing record as `false`. A failed read or
* write rejects instead, so callers never mistake a storage outage for an absent record.
*/
export interface SessionStorageBackend {
/** Backend type identifier */
readonly type: 'memory' | 'file' | 'postgresql' | 'redis';
// Session operations
/** Store a new session; rejects when a session with its id exists. */
createSession(session: OAuthSession): Promise<void>;
getSession(sessionId: string): Promise<OAuthSession | undefined>;
getSessionByToken(token: string): Promise<OAuthSession | undefined>;
getSessionByRefreshToken(refreshToken: string): Promise<OAuthSession | undefined>;
updateSession(sessionId: string, updates: Partial<OAuthSession>): Promise<boolean>;
/** Delete a session together with the accounts linked to it. */
deleteSession(sessionId: string): Promise<boolean>;
getAllSessions(): Promise<OAuthSession[]>;
/** The GitLab accounts linked to a session, oldest first. */
getLinkedSessions(sessionId: string): Promise<OAuthSession[]>;
/**
* Atomically validate the primary lease, unspent/unexpired flow, any cached grant and (for a
* replacement) account lease/token, store the account and consume the flow. False means
* a precondition changed and nothing was written. Storage errors reject with no partial
* commit. Older external backends without this operation cannot safely link accounts.
*/
commitLinkedAccount?(commit: LinkedAccountCommit): Promise<boolean>;
/**
* Cache a grant only on its live, unclaimed link flow, without replacing a different
* cached grant. Return true when that flow holds these tokens. Otherwise retain them
* under an idempotent, callback-invisible cleanup key and return false. Retries must
* neither recreate the original state nor overwrite cleanup leases/rotated tokens.
*/
cacheLinkedFlowTokens?(flow: AuthCodeFlowState, tokens: GitLabTokenResponse): Promise<boolean>;
// Device flow operations
storeDeviceFlow(state: string, flow: DeviceFlowState): Promise<void>;
getDeviceFlow(state: string): Promise<DeviceFlowState | undefined>;
getDeviceFlowByDeviceCode(deviceCode: string): Promise<DeviceFlowState | undefined>;
deleteDeviceFlow(state: string): Promise<boolean>;
// Auth code flow operations
storeAuthCodeFlow(internalState: string, flow: AuthCodeFlowState): Promise<void>;
getAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined>;
deleteAuthCodeFlow(internalState: string): Promise<boolean>;
// Authorization code operations
storeAuthCode(code: AuthorizationCode): Promise<void>;
getAuthCode(code: string): Promise<AuthorizationCode | undefined>;
deleteAuthCode(code: string): Promise<boolean>;
// MCP session mapping
associateMcpSession(mcpSessionId: string, oauthSessionId: string): Promise<void>;
getSessionByMcpSessionId(mcpSessionId: string): Promise<OAuthSession | undefined>;
removeMcpSessionAssociation(mcpSessionId: string): Promise<boolean>;
// Registered OAuth clients (RFC 7591), shared by every replica
storeClient(client: RegisteredOAuthClient): Promise<void>;
getClient(clientId: string): Promise<RegisteredOAuthClient | undefined>;
/** Record that the client completed an authorization: its registration no longer expires. */
markClientUsed(clientId: string): Promise<void>;
/** How many clients `registeredFrom` registered at or after `since` (epoch ms), used or not. */
countClientsRegisteredSince(registeredFrom: string, since: number): Promise<number>;
// Single-use consumption: of concurrent callers on any replica, exactly one receives
// the record and the record is gone afterwards.
consumeAuthCode(code: string): Promise<AuthorizationCode | undefined>;
consumeAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined>;
consumeDeviceFlow(state: string): Promise<DeviceFlowState | undefined>;
/**
* Reserve the next GitLab poll of a device flow: when the flow exists and its
* `nextPollAt` is unset or not after `now`, set it to `nextPollAt` and return the flow;
* otherwise undefined. Of concurrent pollers on any replica, one wins each interval.
*/
claimDevicePoll(
state: string,
now: number,
nextPollAt: number,
): Promise<DeviceFlowState | undefined>;
/**
* Lease the session's GitLab refresh token for a refresh: succeeds only while the session
* still holds `expectedRefreshToken` and no other unexpired lease exists, and then holds
* the lease until `leaseUntil`. GitLab refresh tokens work once, so of concurrent
* refreshes on any replica only the lease holder may spend the token.
*/
claimGitLabRefresh(
sessionId: string,
expectedRefreshToken: string,
now: number,
leaseUntil: number,
): Promise<boolean>;
/**
* End the caller's GitLab refresh lease (after the refresh finished or failed), named by
* the `leaseUntil` it claimed. A lease claimed later by another caller is kept: a lease
* can only be claimed again after it expired, so a newer one always ends later.
*/
releaseGitLabRefresh(sessionId: string, leaseUntil: number): Promise<void>;
/**
* Apply `updates` only while the session still holds `expectedRefreshToken`
* (compare-and-set), so of concurrent refreshes exactly one rotates the tokens.
*/
rotateSession(
sessionId: string,
expectedRefreshToken: string,
updates: Partial<OAuthSession>,
): Promise<boolean>;
// Account settings, shared by every replica
getAccountSettings(accountKey: string): Promise<AccountSettingsRecord | undefined>;
/**
* Store an account's settings only while its stored version is still `expectedVersion`
* (0: none stored yet). Returns the stored record, or undefined when another write
* changed the settings first, so a stale edit never overwrites a newer one.
*/
putAccountSettings(
accountKey: string,
settings: AccountSettings,
expectedVersion: number,
): Promise<AccountSettingsRecord | undefined>;
// Lifecycle
initialize(): Promise<void>;
/** Remove expired sessions, flows, codes and expired never-used client registrations. */
cleanup(): Promise<void>;
/**
* Call `handler` for each expired auth code flow that holds GitLab tokens, taken out of
* its callback's reach: the callback exchanged the code but never finished, so the flow
* holds the only copy of that grant. The flow is removed once the handler resolves and
* kept for the next cleanup when it rejects. Absent in database packages older than this
* server.
*
* Register grant cleanup with a positive integer bound covering ownership checks, GitLab
* requests and token persistence. Shared backends lease each flow for this duration,
* fence token writes/deletion to that lease, and hide claimed flows from callbacks.
*/
onAbandonedFlowGrant?(handler: AbandonedFlowGrantHandler, leaseMs: number): void;
/**
* Hand each session cleanup expires (not an account linked to a session still stored) to
* `handler`, which removes it with its linked accounts and ends their GitLab grants;
* cleanup deletes whatever the handler left. Absent in database packages older than this
* server.
*/
onExpiredSession?(handler: ExpiredSessionHandler): void;
close(): Promise<void>;
// Statistics
getStats(): Promise<SessionStorageStats>;
}
/**
* Storage statistics
*/
export interface SessionStorageStats {
sessions: number;
deviceFlows: number;
authCodeFlows: number;
authCodes: number;
mcpSessionMappings?: number;
}
/**
* Storage configuration
*/
export interface StorageConfig {
/** Storage type: "memory", "file", "postgresql" */
type: 'memory' | 'file' | 'postgresql';
/** File storage options */
file?: {
/** Path to storage file */
path: string;
/** Auto-save interval in milliseconds (default: 30000) */
saveInterval?: number;
};
/** PostgreSQL storage options */
postgresql?: {
/** Connection string */
connectionString: string;
/** Table name prefix (default: "oauth_") */
tablePrefix?: string;
/** Enable SSL (default: true for production) */
ssl?: boolean;
};
}
/**
* Data export format for file storage
*/
export interface StorageData {
version: number;
exportedAt: number;
sessions: OAuthSession[];
deviceFlows: Array<{ state: string; flow: DeviceFlowState }>;
authCodeFlows: Array<{ internalState: string; flow: AuthCodeFlowState }>;
authCodes: AuthorizationCode[];
mcpSessionMappings: Array<{ mcpSessionId: string; oauthSessionId: string }>;
/** Registered OAuth clients; absent in files written before client persistence */
clients?: RegisteredOAuthClient[];
/** Account settings; absent in files written before settings persistence */
accountSettings?: AccountSettingsRecord[];
}
/** Current storage data format version */
export const STORAGE_DATA_VERSION = 1;
|