The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | AuthSessionId, |
| 3 | AuthAdministrativeClientScopes, |
| 4 | AuthStandardClientScopes, |
| 5 | AuthEnvironmentScopes, |
| 6 | type AuthClientMetadata, |
| 7 | type AuthClientSession, |
| 8 | type AuthEnvironmentScope, |
| 9 | AuthWebSocketTicketUse, |
| 10 | RuntimeMode, |
| 11 | type ServerAuthSessionMethod, |
| 12 | } from "@t3tools/contracts"; |
| 13 | import * as Context from "effect/Context"; |
| 14 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 15 | import * as DateTime from "effect/DateTime"; |
| 16 | import * as Duration from "effect/Duration"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as PubSub from "effect/PubSub"; |
| 20 | import * as Ref from "effect/Ref"; |
| 21 | import * as Schema from "effect/Schema"; |
| 22 | import * as Stream from "effect/Stream"; |
| 23 | import * as Option from "effect/Option"; |
| 24 | |
| 25 | import * as ServerConfig from "../config.ts"; |
| 26 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 27 | import * as AuthSessions from "../persistence/AuthSessions.ts"; |
| 28 | import type { |
| 29 | ServerAuthInternalError, |
| 30 | ServerAuthInvalidCredentialError, |
| 31 | } from "./EnvironmentAuth.ts"; |
| 32 | import * as PayloadSigner from "./PayloadSigner.ts"; |
| 33 | import * as ServerSecretStore from "./ServerSecretStore.ts"; |
| 34 | import { |
| 35 | REUSABLE_DEV_SESSION_EXPIRES_AT, |
| 36 | REUSABLE_DEV_SESSION_PREFIX, |
| 37 | resolveReusableDevAuth, |
| 38 | } from "./ReusableDevAuth.ts"; |
| 39 | import { |
| 40 | base64UrlDecodeUtf8, |
| 41 | base64UrlEncode, |
| 42 | resolveLegacySessionCookieName, |
| 43 | resolveSessionCookieName, |
| 44 | } from "./utils.ts"; |
| 45 | |
| 46 | export interface IssuedSession { |
| 47 | readonly sessionId: AuthSessionId; |
| 48 | readonly token: string; |
| 49 | readonly method: ServerAuthSessionMethod; |
| 50 | readonly client: AuthClientMetadata; |
| 51 | readonly expiresAt: DateTime.DateTime; |
| 52 | readonly scopes: ReadonlyArray<AuthEnvironmentScope>; |
| 53 | readonly proofKeyThumbprint?: string; |
| 54 | } |
| 55 | |
| 56 | export interface VerifiedSession { |
| 57 | readonly sessionId: AuthSessionId; |
| 58 | readonly token: string; |
| 59 | readonly method: ServerAuthSessionMethod; |
| 60 | readonly client: AuthClientMetadata; |
| 61 | readonly expiresAt?: DateTime.DateTime; |
| 62 | readonly subject: string; |
| 63 | readonly scopes: ReadonlyArray<AuthEnvironmentScope>; |
| 64 | readonly proofKeyThumbprint?: string; |
| 65 | readonly runtimeModeCeiling?: RuntimeMode; |
| 66 | /** An MCP client that is another T3 Code environment's peer link. */ |
| 67 | readonly peerLink?: true; |
| 68 | } |
| 69 | |
| 70 | export interface VerifiedWebSocketTicket extends VerifiedSession { |
| 71 | readonly audience?: AuthWebSocketTicketUse; |
| 72 | } |
| 73 | |
| 74 | export type SessionCredentialChange = |
| 75 | | { |
| 76 | readonly type: "clientUpserted"; |
| 77 | readonly clientSession: AuthClientSession; |
| 78 | } |
| 79 | | { |
| 80 | readonly type: "clientRemoved"; |
| 81 | readonly sessionId: AuthSessionId; |
| 82 | }; |
| 83 | |
| 84 | export class MalformedSessionTokenError extends Schema.TaggedError<MalformedSessionTokenError>()( |
| 85 | "MalformedSessionTokenError", |
| 86 | {}, |
| 87 | ) { |
| 88 | override get message(): string { |
| 89 | return "Malformed session token."; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | export class InvalidSessionTokenSignatureError extends Schema.TaggedError<InvalidSessionTokenSignatureError>()( |
| 94 | "InvalidSessionTokenSignatureError", |
| 95 | {}, |
| 96 | ) { |
| 97 | override get message(): string { |
| 98 | return "Invalid session token signature."; |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | export class InvalidSessionTokenPayloadError extends Schema.TaggedError<InvalidSessionTokenPayloadError>()( |
| 103 | "InvalidSessionTokenPayloadError", |
| 104 | { |
| 105 | cause: Schema.Defect(), |
| 106 | }, |
| 107 | ) { |
| 108 | override get message(): string { |
| 109 | return "Invalid session token payload."; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | export class SessionTokenExpiredError extends Schema.TaggedError<SessionTokenExpiredError>()( |
| 114 | "SessionTokenExpiredError", |
| 115 | { |
| 116 | sessionId: AuthSessionId, |
| 117 | expiresAt: Schema.DateTimeUtc, |
| 118 | observedAt: Schema.DateTimeUtc, |
| 119 | }, |
| 120 | ) { |
| 121 | override get message(): string { |
| 122 | return "Session token expired."; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | export class UnknownSessionTokenError extends Schema.TaggedError<UnknownSessionTokenError>()( |
| 127 | "UnknownSessionTokenError", |
| 128 | { |
| 129 | sessionId: AuthSessionId, |
| 130 | }, |
| 131 | ) { |
| 132 | override get message(): string { |
| 133 | return "Unknown session token."; |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | export class SessionTokenNotRenewableError extends Schema.TaggedError<SessionTokenNotRenewableError>()( |
| 138 | "SessionTokenNotRenewableError", |
| 139 | { |
| 140 | sessionId: AuthSessionId, |
| 141 | }, |
| 142 | ) { |
| 143 | override get message(): string { |
| 144 | return "Session token cannot be renewed with this key."; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | export class SessionTokenRevokedError extends Schema.TaggedError<SessionTokenRevokedError>()( |
| 149 | "SessionTokenRevokedError", |
| 150 | { |
| 151 | sessionId: AuthSessionId, |
| 152 | revokedAt: Schema.DateTimeUtc, |
| 153 | }, |
| 154 | ) { |
| 155 | override get message(): string { |
| 156 | return "Session token revoked."; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | export class InvalidSessionExpirationClaimError extends Schema.TaggedError<InvalidSessionExpirationClaimError>()( |
| 161 | "InvalidSessionExpirationClaimError", |
| 162 | { |
| 163 | sessionId: AuthSessionId, |
| 164 | expirationClaim: Schema.Number, |
| 165 | }, |
| 166 | ) { |
| 167 | override get message(): string { |
| 168 | return "Invalid `exp` claim"; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | export class MalformedWebSocketTokenError extends Schema.TaggedError<MalformedWebSocketTokenError>()( |
| 173 | "MalformedWebSocketTokenError", |
| 174 | {}, |
| 175 | ) { |
| 176 | override get message(): string { |
| 177 | return "Malformed websocket token."; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | export class InvalidWebSocketTokenSignatureError extends Schema.TaggedError<InvalidWebSocketTokenSignatureError>()( |
| 182 | "InvalidWebSocketTokenSignatureError", |
| 183 | {}, |
| 184 | ) { |
| 185 | override get message(): string { |
| 186 | return "Invalid websocket token signature."; |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | export class InvalidWebSocketTokenPayloadError extends Schema.TaggedError<InvalidWebSocketTokenPayloadError>()( |
| 191 | "InvalidWebSocketTokenPayloadError", |
| 192 | { |
| 193 | cause: Schema.Defect(), |
| 194 | }, |
| 195 | ) { |
| 196 | override get message(): string { |
| 197 | return "Invalid websocket token payload."; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | export class WebSocketTokenExpiredError extends Schema.TaggedError<WebSocketTokenExpiredError>()( |
| 202 | "WebSocketTokenExpiredError", |
| 203 | { |
| 204 | sessionId: AuthSessionId, |
| 205 | expiresAt: Schema.DateTimeUtc, |
| 206 | observedAt: Schema.DateTimeUtc, |
| 207 | }, |
| 208 | ) { |
| 209 | override get message(): string { |
| 210 | return "Websocket token expired."; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | export class UnknownWebSocketSessionError extends Schema.TaggedError<UnknownWebSocketSessionError>()( |
| 215 | "UnknownWebSocketSessionError", |
| 216 | { |
| 217 | sessionId: AuthSessionId, |
| 218 | }, |
| 219 | ) { |
| 220 | override get message(): string { |
| 221 | return "Unknown websocket session."; |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | export class WebSocketSessionExpiredError extends Schema.TaggedError<WebSocketSessionExpiredError>()( |
| 226 | "WebSocketSessionExpiredError", |
| 227 | { |
| 228 | sessionId: AuthSessionId, |
| 229 | expiresAt: Schema.DateTimeUtc, |
| 230 | observedAt: Schema.DateTimeUtc, |
| 231 | }, |
| 232 | ) { |
| 233 | override get message(): string { |
| 234 | return "Websocket session expired."; |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | export class WebSocketSessionRevokedError extends Schema.TaggedError<WebSocketSessionRevokedError>()( |
| 239 | "WebSocketSessionRevokedError", |
| 240 | { |
| 241 | sessionId: AuthSessionId, |
| 242 | revokedAt: Schema.DateTimeUtc, |
| 243 | }, |
| 244 | ) { |
| 245 | override get message(): string { |
| 246 | return "Websocket session revoked."; |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | export const SessionCredentialInvalidError = Schema.Union([ |
| 251 | MalformedSessionTokenError, |
| 252 | InvalidSessionTokenSignatureError, |
| 253 | InvalidSessionTokenPayloadError, |
| 254 | SessionTokenExpiredError, |
| 255 | UnknownSessionTokenError, |
| 256 | SessionTokenRevokedError, |
| 257 | SessionTokenNotRenewableError, |
| 258 | InvalidSessionExpirationClaimError, |
| 259 | MalformedWebSocketTokenError, |
| 260 | InvalidWebSocketTokenSignatureError, |
| 261 | InvalidWebSocketTokenPayloadError, |
| 262 | WebSocketTokenExpiredError, |
| 263 | UnknownWebSocketSessionError, |
| 264 | WebSocketSessionExpiredError, |
| 265 | WebSocketSessionRevokedError, |
| 266 | ]); |
| 267 | export type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type; |
| 268 | export const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError); |
| 269 | |
| 270 | const sessionCredentialInternalErrorContext = { |
| 271 | cause: Schema.Defect(), |
| 272 | }; |
| 273 | |
| 274 | export class SessionClaimsEncodingError extends Schema.TaggedError<SessionClaimsEncodingError>()( |
| 275 | "SessionClaimsEncodingError", |
| 276 | { |
| 277 | sessionId: AuthSessionId, |
| 278 | operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]), |
| 279 | ...sessionCredentialInternalErrorContext, |
| 280 | }, |
| 281 | ) { |
| 282 | override get message(): string { |
| 283 | return "Failed to encode claims"; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | export class SessionCredentialIssueError extends Schema.TaggedError<SessionCredentialIssueError>()( |
| 288 | "SessionCredentialIssueError", |
| 289 | { |
| 290 | sessionId: Schema.optional(AuthSessionId), |
| 291 | ...sessionCredentialInternalErrorContext, |
| 292 | }, |
| 293 | ) { |
| 294 | override get message(): string { |
| 295 | return "Failed to issue session credential."; |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | export class SessionCredentialVerificationError extends Schema.TaggedError<SessionCredentialVerificationError>()( |
| 300 | "SessionCredentialVerificationError", |
| 301 | { |
| 302 | sessionId: AuthSessionId, |
| 303 | ...sessionCredentialInternalErrorContext, |
| 304 | }, |
| 305 | ) { |
| 306 | override get message(): string { |
| 307 | return "Failed to verify session credential."; |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | export class WebSocketTokenIssueError extends Schema.TaggedError<WebSocketTokenIssueError>()( |
| 312 | "WebSocketTokenIssueError", |
| 313 | { |
| 314 | sessionId: AuthSessionId, |
| 315 | ...sessionCredentialInternalErrorContext, |
| 316 | }, |
| 317 | ) { |
| 318 | override get message(): string { |
| 319 | return "Failed to issue websocket token."; |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | export class WebSocketTokenVerificationError extends Schema.TaggedError<WebSocketTokenVerificationError>()( |
| 324 | "WebSocketTokenVerificationError", |
| 325 | { |
| 326 | sessionId: AuthSessionId, |
| 327 | ...sessionCredentialInternalErrorContext, |
| 328 | }, |
| 329 | ) { |
| 330 | override get message(): string { |
| 331 | return "Failed to verify websocket token."; |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | export class ActiveSessionsListError extends Schema.TaggedError<ActiveSessionsListError>()( |
| 336 | "ActiveSessionsListError", |
| 337 | { |
| 338 | ...sessionCredentialInternalErrorContext, |
| 339 | }, |
| 340 | ) { |
| 341 | override get message(): string { |
| 342 | return "Failed to list active sessions."; |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | export class SessionRevocationError extends Schema.TaggedError<SessionRevocationError>()( |
| 347 | "SessionRevocationError", |
| 348 | { |
| 349 | sessionId: AuthSessionId, |
| 350 | ...sessionCredentialInternalErrorContext, |
| 351 | }, |
| 352 | ) { |
| 353 | override get message(): string { |
| 354 | return "Failed to revoke session."; |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | export class OtherSessionsRevocationError extends Schema.TaggedError<OtherSessionsRevocationError>()( |
| 359 | "OtherSessionsRevocationError", |
| 360 | { |
| 361 | currentSessionId: AuthSessionId, |
| 362 | ...sessionCredentialInternalErrorContext, |
| 363 | }, |
| 364 | ) { |
| 365 | override get message(): string { |
| 366 | return "Failed to revoke other sessions."; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | export class ProofKeySessionsError extends Schema.TaggedError<ProofKeySessionsError>()( |
| 371 | "ProofKeySessionsError", |
| 372 | { |
| 373 | operation: Schema.Literals(["lookup", "revoke"]), |
| 374 | ...sessionCredentialInternalErrorContext, |
| 375 | }, |
| 376 | ) { |
| 377 | override get message(): string { |
| 378 | return `Failed to ${this.operation} sessions by proof key.`; |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | export const SessionCredentialInternalError = Schema.Union([ |
| 383 | SessionClaimsEncodingError, |
| 384 | SessionCredentialIssueError, |
| 385 | SessionCredentialVerificationError, |
| 386 | WebSocketTokenIssueError, |
| 387 | WebSocketTokenVerificationError, |
| 388 | ActiveSessionsListError, |
| 389 | SessionRevocationError, |
| 390 | OtherSessionsRevocationError, |
| 391 | ProofKeySessionsError, |
| 392 | ]); |
| 393 | export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type; |
| 394 | |
| 395 | export const SessionCredentialError = Schema.Union([ |
| 396 | SessionCredentialInvalidError, |
| 397 | SessionCredentialInternalError, |
| 398 | ]); |
| 399 | export type SessionCredentialError = typeof SessionCredentialError.Type; |
| 400 | |
| 401 | export class SessionStore extends Context.Service< |
| 402 | SessionStore, |
| 403 | { |
| 404 | readonly cookieName: string; |
| 405 | readonly legacyCookieName: string | undefined; |
| 406 | readonly issue: (input?: { |
| 407 | readonly ttl?: Duration.Duration; |
| 408 | readonly subject?: string; |
| 409 | readonly method?: ServerAuthSessionMethod; |
| 410 | readonly scopes?: ReadonlyArray<AuthEnvironmentScope>; |
| 411 | readonly client?: AuthClientMetadata; |
| 412 | readonly proofKeyThumbprint?: string; |
| 413 | readonly runtimeModeCeiling?: RuntimeMode; |
| 414 | readonly peerLink?: boolean; |
| 415 | readonly replaceActiveForSubjectAndMethod?: boolean; |
| 416 | readonly replaceSessionId?: AuthSessionId; |
| 417 | /** Keeps the session alive this long past each renewal; `ttl` then bounds only the token. */ |
| 418 | readonly renewalWindow?: Duration.Duration; |
| 419 | }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>; |
| 420 | /** Trades a renewable token, even an expired one, for a fresh token on the same session. */ |
| 421 | readonly renew: ( |
| 422 | token: string, |
| 423 | input: { |
| 424 | readonly proofKeyThumbprint: string; |
| 425 | readonly ttl: Duration.Duration; |
| 426 | readonly renewalWindow: Duration.Duration; |
| 427 | readonly consumeProof: Effect.Effect< |
| 428 | void, |
| 429 | ServerAuthInvalidCredentialError | ServerAuthInternalError |
| 430 | >; |
| 431 | }, |
| 432 | ) => Effect.Effect< |
| 433 | IssuedSession, |
| 434 | SessionCredentialError | ServerAuthInvalidCredentialError | ServerAuthInternalError |
| 435 | >; |
| 436 | readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>; |
| 437 | /** |
| 438 | * Moves a live session's expiry to `expiresAt` unless it is already within `step` of it, and |
| 439 | * returns the expiry it now has. None when it is revoked, expired or missing. |
| 440 | */ |
| 441 | readonly extend: ( |
| 442 | sessionId: AuthSessionId, |
| 443 | expiresAt: DateTime.Utc, |
| 444 | step: Duration.Duration, |
| 445 | ) => Effect.Effect<Option.Option<DateTime.Utc>, SessionCredentialInternalError>; |
| 446 | readonly issueWebSocketToken: ( |
| 447 | sessionId: AuthSessionId, |
| 448 | input?: { |
| 449 | readonly ttl?: Duration.Duration; |
| 450 | readonly audience?: AuthWebSocketTicketUse; |
| 451 | readonly proofKeyThumbprint?: string; |
| 452 | }, |
| 453 | ) => Effect.Effect< |
| 454 | { |
| 455 | readonly token: string; |
| 456 | readonly expiresAt: DateTime.DateTime; |
| 457 | }, |
| 458 | SessionCredentialInternalError |
| 459 | >; |
| 460 | readonly verifyWebSocketToken: ( |
| 461 | token: string, |
| 462 | ) => Effect.Effect<VerifiedWebSocketTicket, SessionCredentialError>; |
| 463 | readonly listActive: () => Effect.Effect< |
| 464 | ReadonlyArray<AuthClientSession>, |
| 465 | SessionCredentialInternalError |
| 466 | >; |
| 467 | readonly streamChanges: Stream.Stream<SessionCredentialChange>; |
| 468 | /** Completes when a live socket's session is revoked or expires without a renewal for its DPoP key. */ |
| 469 | readonly awaitInvalidation: ( |
| 470 | sessionId: AuthSessionId, |
| 471 | proofKeyThumbprint?: string, |
| 472 | ) => Effect.Effect<void, SessionCredentialVerificationError>; |
| 473 | readonly revoke: ( |
| 474 | sessionId: AuthSessionId, |
| 475 | ) => Effect.Effect<boolean, SessionCredentialInternalError>; |
| 476 | readonly revokeAllExcept: ( |
| 477 | sessionId: AuthSessionId, |
| 478 | ) => Effect.Effect<number, SessionCredentialInternalError>; |
| 479 | readonly proofKeyThumbprintOf: ( |
| 480 | sessionId: AuthSessionId, |
| 481 | ) => Effect.Effect<Option.Option<string>, SessionCredentialInternalError>; |
| 482 | /** Revokes every session bound to this DPoP key, so a device it belongs to is cut off now. */ |
| 483 | readonly revokeByProofKey: ( |
| 484 | proofKeyThumbprint: string, |
| 485 | ) => Effect.Effect<number, SessionCredentialInternalError>; |
| 486 | readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>; |
| 487 | readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>; |
| 488 | } |
| 489 | >()("t3/auth/SessionStore") {} |
| 490 | |
| 491 | const SIGNING_SECRET_NAME = "server-signing-key"; |
| 492 | const DEFAULT_SESSION_TTL = Duration.days(30); |
| 493 | const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5); |
| 494 | |
| 495 | const SessionClaims = Schema.Struct({ |
| 496 | v: Schema.Literals([1, 2]), |
| 497 | kind: Schema.Literal("session"), |
| 498 | sid: AuthSessionId, |
| 499 | sub: Schema.String, |
| 500 | scopes: AuthEnvironmentScopes, |
| 501 | method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]), |
| 502 | jkt: Schema.optionalKey(Schema.String), |
| 503 | rtc: Schema.optionalKey(RuntimeMode), |
| 504 | /** Signed, so a client cannot shed its peer link's limits. */ |
| 505 | plk: Schema.optionalKey(Schema.Literal(1)), |
| 506 | /** Signed, so only sessions issued as renewable can renew. */ |
| 507 | rnw: Schema.optionalKey(Schema.Literal(1)), |
| 508 | iat: Schema.Number, |
| 509 | exp: Schema.Number, |
| 510 | }); |
| 511 | type SessionClaims = typeof SessionClaims.Type; |
| 512 | |
| 513 | const WebSocketClaims = Schema.Struct({ |
| 514 | v: Schema.Literal(1), |
| 515 | kind: Schema.Literal("websocket"), |
| 516 | sid: AuthSessionId, |
| 517 | aud: Schema.optionalKey(AuthWebSocketTicketUse), |
| 518 | jkt: Schema.optionalKey(Schema.String), |
| 519 | iat: Schema.Number, |
| 520 | exp: Schema.Number, |
| 521 | }); |
| 522 | type WebSocketClaims = typeof WebSocketClaims.Type; |
| 523 | |
| 524 | const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims)); |
| 525 | const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims)); |
| 526 | |
| 527 | function createDefaultClientMetadata(): AuthClientMetadata { |
| 528 | return { |
| 529 | deviceType: "unknown", |
| 530 | }; |
| 531 | } |
| 532 | |
| 533 | function toClientMetadata(record: { |
| 534 | readonly label: string | null; |
| 535 | readonly ipAddress: string | null; |
| 536 | readonly userAgent: string | null; |
| 537 | readonly deviceType: AuthClientMetadata["deviceType"]; |
| 538 | readonly os: string | null; |
| 539 | readonly browser: string | null; |
| 540 | }): AuthClientMetadata { |
| 541 | return { |
| 542 | ...(record.label ? { label: record.label } : {}), |
| 543 | ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}), |
| 544 | ...(record.userAgent ? { userAgent: record.userAgent } : {}), |
| 545 | deviceType: record.deviceType, |
| 546 | ...(record.os ? { os: record.os } : {}), |
| 547 | ...(record.browser ? { browser: record.browser } : {}), |
| 548 | }; |
| 549 | } |
| 550 | |
| 551 | function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession { |
| 552 | return { |
| 553 | ...input, |
| 554 | current: false, |
| 555 | }; |
| 556 | } |
| 557 | |
| 558 | const make = Effect.gen(function* () { |
| 559 | const random = yield* SecureRandom.SecureRandom; |
| 560 | const serverConfig = yield* ServerConfig.ServerConfig; |
| 561 | const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity; |
| 562 | const secretStore = yield* ServerSecretStore.ServerSecretStore; |
| 563 | const authSessions = yield* AuthSessions.AuthSessionRepository; |
| 564 | const signer = yield* PayloadSigner.fromSecret( |
| 565 | yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32), |
| 566 | ); |
| 567 | const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>()); |
| 568 | const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>(); |
| 569 | // Newest session per DPoP key. A live socket moves to it at expiry, so a |
| 570 | // client that renews its short-lived token keeps its socket. |
| 571 | const latestSessionByProofKey = new Map<string, AuthSessionId>(); |
| 572 | const cookieInput = { |
| 573 | mode: serverConfig.mode, |
| 574 | port: serverConfig.port, |
| 575 | host: serverConfig.host, |
| 576 | instanceKey: serverConfig.stateDir, |
| 577 | environmentId: yield* serverEnvironment.getEnvironmentId, |
| 578 | development: serverConfig.devUrl !== undefined, |
| 579 | } as const; |
| 580 | const cookieName = resolveSessionCookieName(cookieInput); |
| 581 | const legacyCookieName = resolveLegacySessionCookieName(cookieInput); |
| 582 | const devAuth = resolveReusableDevAuth(serverConfig); |
| 583 | if (devAuth) { |
| 584 | yield* authSessions |
| 585 | .createIfAbsent({ |
| 586 | sessionId: devAuth.sessionId, |
| 587 | subject: "reusable-dev-token", |
| 588 | scopes: AuthAdministrativeClientScopes, |
| 589 | method: "browser-session-cookie", |
| 590 | client: { |
| 591 | label: "Reusable dev token", |
| 592 | ipAddress: null, |
| 593 | userAgent: null, |
| 594 | deviceType: "unknown", |
| 595 | os: null, |
| 596 | browser: null, |
| 597 | }, |
| 598 | issuedAt: yield* DateTime.now, |
| 599 | expiresAt: REUSABLE_DEV_SESSION_EXPIRES_AT, |
| 600 | }) |
| 601 | .pipe( |
| 602 | Effect.mapError( |
| 603 | (cause) => new SessionCredentialIssueError({ sessionId: devAuth.sessionId, cause }), |
| 604 | ), |
| 605 | ); |
| 606 | } |
| 607 | |
| 608 | const emitUpsert = (clientSession: AuthClientSession) => |
| 609 | PubSub.publish(changesPubSub, { |
| 610 | type: "clientUpserted", |
| 611 | clientSession, |
| 612 | }).pipe(Effect.asVoid); |
| 613 | |
| 614 | const emitRemoved = (sessionId: AuthSessionId) => |
| 615 | PubSub.publish(changesPubSub, { |
| 616 | type: "clientRemoved", |
| 617 | sessionId, |
| 618 | }).pipe(Effect.asVoid); |
| 619 | |
| 620 | const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* ( |
| 621 | sessionId: AuthSessionId, |
| 622 | ) { |
| 623 | const row = yield* authSessions.getById({ sessionId }); |
| 624 | if (Option.isNone(row) || row.value.revokedAt !== null) { |
| 625 | return Option.none<AuthClientSession>(); |
| 626 | } |
| 627 | |
| 628 | const connectedSessions = yield* Ref.get(connectedSessionsRef); |
| 629 | const connected = connectedSessions.has(row.value.sessionId); |
| 630 | const now = yield* DateTime.now; |
| 631 | if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) { |
| 632 | return Option.none<AuthClientSession>(); |
| 633 | } |
| 634 | return Option.some( |
| 635 | toAuthClientSession({ |
| 636 | sessionId: row.value.sessionId, |
| 637 | subject: row.value.subject, |
| 638 | scopes: row.value.scopes, |
| 639 | method: row.value.method, |
| 640 | client: toClientMetadata(row.value.client), |
| 641 | issuedAt: row.value.issuedAt, |
| 642 | expiresAt: row.value.expiresAt, |
| 643 | lastConnectedAt: row.value.lastConnectedAt, |
| 644 | connected, |
| 645 | }), |
| 646 | ); |
| 647 | }); |
| 648 | |
| 649 | const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) => |
| 650 | Ref.modify(connectedSessionsRef, (current) => { |
| 651 | const next = new Map(current); |
| 652 | const wasDisconnected = !next.has(sessionId); |
| 653 | next.set(sessionId, (next.get(sessionId) ?? 0) + 1); |
| 654 | return [wasDisconnected, next] as const; |
| 655 | }).pipe( |
| 656 | Effect.flatMap((wasDisconnected) => |
| 657 | wasDisconnected |
| 658 | ? DateTime.now.pipe( |
| 659 | Effect.flatMap((lastConnectedAt) => |
| 660 | authSessions.setLastConnectedAt({ |
| 661 | sessionId, |
| 662 | lastConnectedAt, |
| 663 | }), |
| 664 | ), |
| 665 | ) |
| 666 | : Effect.void, |
| 667 | ), |
| 668 | Effect.flatMap(() => loadActiveSession(sessionId)), |
| 669 | Effect.flatMap((session) => |
| 670 | Option.isSome(session) ? emitUpsert(session.value) : Effect.void, |
| 671 | ), |
| 672 | Effect.catchCause((cause) => |
| 673 | Effect.logError("Failed to publish connected-session auth update.").pipe( |
| 674 | Effect.annotateLogs({ |
| 675 | sessionId, |
| 676 | cause, |
| 677 | }), |
| 678 | ), |
| 679 | ), |
| 680 | Effect.withSpan("SessionStore.markConnected"), |
| 681 | ); |
| 682 | |
| 683 | const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) => |
| 684 | Ref.update(connectedSessionsRef, (current) => { |
| 685 | const next = new Map(current); |
| 686 | const remaining = (next.get(sessionId) ?? 0) - 1; |
| 687 | if (remaining > 0) { |
| 688 | next.set(sessionId, remaining); |
| 689 | } else { |
| 690 | next.delete(sessionId); |
| 691 | } |
| 692 | return next; |
| 693 | }).pipe( |
| 694 | Effect.flatMap(() => loadActiveSession(sessionId)), |
| 695 | Effect.flatMap((session) => |
| 696 | Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId), |
| 697 | ), |
| 698 | Effect.catchCause((cause) => |
| 699 | Effect.logError("Failed to publish disconnected-session auth update.").pipe( |
| 700 | Effect.annotateLogs({ |
| 701 | sessionId, |
| 702 | cause, |
| 703 | }), |
| 704 | ), |
| 705 | ), |
| 706 | Effect.withSpan("SessionStore.markDisconnected"), |
| 707 | ); |
| 708 | |
| 709 | const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims)); |
| 710 | const signClaims = Effect.fnUntraced(function* (claims: SessionClaims) { |
| 711 | const encodedPayload = yield* encodeClaims(claims).pipe( |
| 712 | Effect.map(base64UrlEncode), |
| 713 | Effect.mapError( |
| 714 | (cause) => |
| 715 | new SessionCredentialIssueError({ |
| 716 | sessionId: claims.sid, |
| 717 | cause: new SessionClaimsEncodingError({ |
| 718 | sessionId: claims.sid, |
| 719 | operation: "encode_session_claims", |
| 720 | cause, |
| 721 | }), |
| 722 | }), |
| 723 | ), |
| 724 | ); |
| 725 | return `${encodedPayload}.${yield* signer.sign(encodedPayload)}`; |
| 726 | }); |
| 727 | const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")( |
| 728 | function* (input) { |
| 729 | const sessionId = AuthSessionId.make( |
| 730 | yield* random |
| 731 | .uuidV4() |
| 732 | .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))), |
| 733 | ); |
| 734 | const issuedAt = yield* DateTime.now; |
| 735 | const expiresAt = DateTime.add(issuedAt, { |
| 736 | milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), |
| 737 | }); |
| 738 | const sessionExpiresAt = input?.renewalWindow |
| 739 | ? DateTime.add(issuedAt, { milliseconds: Duration.toMillis(input.renewalWindow) }) |
| 740 | : expiresAt; |
| 741 | const claims: SessionClaims = { |
| 742 | v: 1, |
| 743 | kind: "session", |
| 744 | sid: sessionId, |
| 745 | sub: input?.subject ?? "browser", |
| 746 | scopes: input?.scopes ?? AuthStandardClientScopes, |
| 747 | method: input?.method ?? "browser-session-cookie", |
| 748 | ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}), |
| 749 | ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}), |
| 750 | ...(input?.peerLink === true ? { plk: 1 as const } : {}), |
| 751 | ...(input?.renewalWindow ? { rnw: 1 as const } : {}), |
| 752 | iat: issuedAt.epochMilliseconds, |
| 753 | exp: expiresAt.epochMilliseconds, |
| 754 | }; |
| 755 | |
| 756 | const token = yield* signClaims(claims); |
| 757 | const client = input?.client ?? createDefaultClientMetadata(); |
| 758 | const sessionRecord = { |
| 759 | sessionId, |
| 760 | subject: claims.sub, |
| 761 | scopes: claims.scopes, |
| 762 | method: claims.method, |
| 763 | client: { |
| 764 | label: client.label ?? null, |
| 765 | ipAddress: client.ipAddress ?? null, |
| 766 | userAgent: client.userAgent ?? null, |
| 767 | deviceType: client.deviceType, |
| 768 | os: client.os ?? null, |
| 769 | browser: client.browser ?? null, |
| 770 | }, |
| 771 | issuedAt, |
| 772 | expiresAt: sessionExpiresAt, |
| 773 | ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), |
| 774 | } satisfies AuthSessions.CreateAuthSessionInput; |
| 775 | const replacedSessionIds = yield* ( |
| 776 | input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod |
| 777 | ? authSessions.createReplacingActive({ |
| 778 | session: sessionRecord, |
| 779 | revokedAt: issuedAt, |
| 780 | ...(input.replaceSessionId !== undefined |
| 781 | ? { replaceSessionId: input.replaceSessionId } |
| 782 | : {}), |
| 783 | }) |
| 784 | : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>)) |
| 785 | ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause }))); |
| 786 | if (claims.jkt) latestSessionByProofKey.set(claims.jkt, sessionId); |
| 787 | if (replacedSessionIds.length > 0) { |
| 788 | yield* Ref.update(connectedSessionsRef, (current) => { |
| 789 | const next = new Map(current); |
| 790 | for (const replacedSessionId of replacedSessionIds) { |
| 791 | next.delete(replacedSessionId); |
| 792 | } |
| 793 | return next; |
| 794 | }); |
| 795 | yield* Effect.forEach(replacedSessionIds, emitRemoved, { |
| 796 | concurrency: "unbounded", |
| 797 | discard: true, |
| 798 | }); |
| 799 | } |
| 800 | yield* emitUpsert( |
| 801 | toAuthClientSession({ |
| 802 | sessionId, |
| 803 | subject: claims.sub, |
| 804 | scopes: claims.scopes, |
| 805 | method: claims.method, |
| 806 | client, |
| 807 | issuedAt, |
| 808 | expiresAt: sessionExpiresAt, |
| 809 | lastConnectedAt: null, |
| 810 | connected: false, |
| 811 | }), |
| 812 | ); |
| 813 | |
| 814 | return { |
| 815 | sessionId, |
| 816 | token, |
| 817 | method: claims.method, |
| 818 | client, |
| 819 | expiresAt: expiresAt, |
| 820 | scopes: claims.scopes, |
| 821 | ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), |
| 822 | } satisfies IssuedSession; |
| 823 | }, |
| 824 | ); |
| 825 | |
| 826 | const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")( |
| 827 | function* (token) { |
| 828 | if (devAuth?.matches(token)) { |
| 829 | const row = yield* authSessions |
| 830 | .getById({ sessionId: devAuth.sessionId }) |
| 831 | .pipe( |
| 832 | Effect.mapError( |
| 833 | (cause) => |
| 834 | new SessionCredentialVerificationError({ sessionId: devAuth.sessionId, cause }), |
| 835 | ), |
| 836 | ); |
| 837 | if (Option.isNone(row)) { |
| 838 | return yield* new UnknownSessionTokenError({ sessionId: devAuth.sessionId }); |
| 839 | } |
| 840 | if (row.value.revokedAt !== null) { |
| 841 | return yield* new SessionTokenRevokedError({ |
| 842 | sessionId: devAuth.sessionId, |
| 843 | revokedAt: row.value.revokedAt, |
| 844 | }); |
| 845 | } |
| 846 | const observedAt = yield* DateTime.now; |
| 847 | if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) { |
| 848 | return yield* new SessionTokenExpiredError({ |
| 849 | sessionId: devAuth.sessionId, |
| 850 | expiresAt: row.value.expiresAt, |
| 851 | observedAt, |
| 852 | }); |
| 853 | } |
| 854 | return { |
| 855 | sessionId: row.value.sessionId, |
| 856 | token, |
| 857 | method: row.value.method, |
| 858 | client: toClientMetadata(row.value.client), |
| 859 | expiresAt: row.value.expiresAt, |
| 860 | subject: row.value.subject, |
| 861 | scopes: row.value.scopes, |
| 862 | } satisfies VerifiedSession; |
| 863 | } |
| 864 | const [encodedPayload, signature] = token.split("."); |
| 865 | if (!encodedPayload || !signature) { |
| 866 | return yield* new MalformedSessionTokenError({}); |
| 867 | } |
| 868 | |
| 869 | if (!(yield* signer.verify(encodedPayload, signature))) { |
| 870 | return yield* new InvalidSessionTokenSignatureError({}); |
| 871 | } |
| 872 | |
| 873 | const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( |
| 874 | Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })), |
| 875 | ); |
| 876 | |
| 877 | const observedAt = yield* DateTime.now; |
| 878 | const expiresAt = DateTime.make(claims.exp); |
| 879 | if (Option.isNone(expiresAt)) { |
| 880 | return yield* new InvalidSessionExpirationClaimError({ |
| 881 | sessionId: claims.sid, |
| 882 | expirationClaim: claims.exp, |
| 883 | }); |
| 884 | } |
| 885 | // A peer link's session renews while it is used and its token is never |
| 886 | // reissued, so the session row holds its deadline, not the token. |
| 887 | const rowHoldsDeadline = claims.plk === 1; |
| 888 | if (!rowHoldsDeadline && claims.exp <= observedAt.epochMilliseconds) { |
| 889 | return yield* new SessionTokenExpiredError({ |
| 890 | sessionId: claims.sid, |
| 891 | expiresAt: expiresAt.value, |
| 892 | observedAt, |
| 893 | }); |
| 894 | } |
| 895 | |
| 896 | const row = yield* authSessions |
| 897 | .getById({ sessionId: claims.sid }) |
| 898 | .pipe( |
| 899 | Effect.mapError( |
| 900 | (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }), |
| 901 | ), |
| 902 | ); |
| 903 | if (Option.isNone(row)) { |
| 904 | return yield* new UnknownSessionTokenError({ sessionId: claims.sid }); |
| 905 | } |
| 906 | if (row.value.revokedAt !== null) { |
| 907 | return yield* new SessionTokenRevokedError({ |
| 908 | sessionId: claims.sid, |
| 909 | revokedAt: row.value.revokedAt, |
| 910 | }); |
| 911 | } |
| 912 | if ( |
| 913 | rowHoldsDeadline && |
| 914 | row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds |
| 915 | ) { |
| 916 | return yield* new SessionTokenExpiredError({ |
| 917 | sessionId: claims.sid, |
| 918 | expiresAt: row.value.expiresAt, |
| 919 | observedAt, |
| 920 | }); |
| 921 | } |
| 922 | |
| 923 | return { |
| 924 | sessionId: claims.sid, |
| 925 | token, |
| 926 | method: claims.method, |
| 927 | client: toClientMetadata(row.value.client), |
| 928 | expiresAt: rowHoldsDeadline ? row.value.expiresAt : expiresAt.value, |
| 929 | subject: claims.sub, |
| 930 | scopes: row.value.scopes, |
| 931 | ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), |
| 932 | ...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}), |
| 933 | ...(claims.plk === 1 ? { peerLink: true as const } : {}), |
| 934 | } satisfies VerifiedSession; |
| 935 | }, |
| 936 | ); |
| 937 | |
| 938 | const extend: SessionStore["Service"]["extend"] = Effect.fn("SessionStore.extend")( |
| 939 | function* (sessionId, expiresAt, step) { |
| 940 | const now = yield* DateTime.now; |
| 941 | // The step is checked in the update, so of two uses that read the same expiry one writes. |
| 942 | const extended = yield* authSessions.extend({ |
| 943 | sessionId, |
| 944 | expiresAt, |
| 945 | now, |
| 946 | onlyIfExpiresBy: DateTime.subtract(expiresAt, { milliseconds: Duration.toMillis(step) }), |
| 947 | }); |
| 948 | if (!extended) { |
| 949 | const row = yield* authSessions.getById({ sessionId }); |
| 950 | return Option.filter( |
| 951 | Option.map(row, (current) => current.expiresAt), |
| 952 | (current) => |
| 953 | Option.exists(row, (session) => session.revokedAt === null) && |
| 954 | DateTime.isGreaterThan(current, now), |
| 955 | ); |
| 956 | } |
| 957 | const session = yield* loadActiveSession(sessionId); |
| 958 | if (Option.isSome(session)) yield* emitUpsert(session.value); |
| 959 | return Option.some(expiresAt); |
| 960 | }, |
| 961 | (effect, sessionId) => |
| 962 | Effect.mapError( |
| 963 | effect, |
| 964 | (cause) => new SessionCredentialVerificationError({ sessionId, cause }), |
| 965 | ), |
| 966 | ); |
| 967 | |
| 968 | const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")( |
| 969 | function* (token, input) { |
| 970 | const [encodedPayload, signature] = token.split("."); |
| 971 | if (!encodedPayload || !signature) { |
| 972 | return yield* new MalformedSessionTokenError({}); |
| 973 | } |
| 974 | if (!(yield* signer.verify(encodedPayload, signature))) { |
| 975 | return yield* new InvalidSessionTokenSignatureError({}); |
| 976 | } |
| 977 | const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( |
| 978 | Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })), |
| 979 | ); |
| 980 | // The token's own expiry is ignored here: the session row's expiry is the renewal window. |
| 981 | if (claims.rnw !== 1 || claims.jkt !== input.proofKeyThumbprint) { |
| 982 | return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid }); |
| 983 | } |
| 984 | const row = yield* authSessions |
| 985 | .getById({ sessionId: claims.sid }) |
| 986 | .pipe( |
| 987 | Effect.mapError( |
| 988 | (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }), |
| 989 | ), |
| 990 | ); |
| 991 | if (Option.isNone(row)) { |
| 992 | return yield* new UnknownSessionTokenError({ sessionId: claims.sid }); |
| 993 | } |
| 994 | if (row.value.revokedAt !== null) { |
| 995 | return yield* new SessionTokenRevokedError({ |
| 996 | sessionId: claims.sid, |
| 997 | revokedAt: row.value.revokedAt, |
| 998 | }); |
| 999 | } |
| 1000 | const now = yield* DateTime.now; |
| 1001 | if (row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) { |
| 1002 | return yield* new SessionTokenExpiredError({ |
| 1003 | sessionId: claims.sid, |
| 1004 | expiresAt: row.value.expiresAt, |
| 1005 | observedAt: now, |
| 1006 | }); |
| 1007 | } |
| 1008 | yield* input.consumeProof; |
| 1009 | const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(input.ttl) }); |
| 1010 | const extended = yield* authSessions |
| 1011 | .extend({ |
| 1012 | sessionId: claims.sid, |
| 1013 | expiresAt: DateTime.add(now, { milliseconds: Duration.toMillis(input.renewalWindow) }), |
| 1014 | now, |
| 1015 | }) |
| 1016 | .pipe( |
| 1017 | Effect.mapError( |
| 1018 | (cause) => new SessionCredentialIssueError({ sessionId: claims.sid, cause }), |
| 1019 | ), |
| 1020 | ); |
| 1021 | // A revoke can land between the read above and the update. |
| 1022 | if (!extended) { |
| 1023 | return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid }); |
| 1024 | } |
| 1025 | const renewedToken = yield* signClaims({ |
| 1026 | ...claims, |
| 1027 | iat: now.epochMilliseconds, |
| 1028 | exp: expiresAt.epochMilliseconds, |
| 1029 | }); |
| 1030 | const session = yield* loadActiveSession(claims.sid).pipe( |
| 1031 | Effect.mapError( |
| 1032 | (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }), |
| 1033 | ), |
| 1034 | ); |
| 1035 | if (Option.isSome(session)) yield* emitUpsert(session.value); |
| 1036 | return { |
| 1037 | sessionId: claims.sid, |
| 1038 | token: renewedToken, |
| 1039 | method: claims.method, |
| 1040 | client: toClientMetadata(row.value.client), |
| 1041 | expiresAt, |
| 1042 | scopes: row.value.scopes, |
| 1043 | proofKeyThumbprint: input.proofKeyThumbprint, |
| 1044 | } satisfies IssuedSession; |
| 1045 | }, |
| 1046 | ); |
| 1047 | |
| 1048 | const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims)); |
| 1049 | const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn( |
| 1050 | "SessionStore.issueWebSocketToken", |
| 1051 | )(function* (sessionId, input) { |
| 1052 | const issuedAt = yield* DateTime.now; |
| 1053 | const expiresAt = DateTime.add(issuedAt, { |
| 1054 | milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL), |
| 1055 | }); |
| 1056 | const claims: WebSocketClaims = { |
| 1057 | v: 1, |
| 1058 | kind: "websocket", |
| 1059 | sid: sessionId, |
| 1060 | ...(input?.audience ? { aud: input.audience } : {}), |
| 1061 | ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}), |
| 1062 | iat: issuedAt.epochMilliseconds, |
| 1063 | exp: expiresAt.epochMilliseconds, |
| 1064 | }; |
| 1065 | const encodedPayload = yield* encodeWsClaims(claims).pipe( |
| 1066 | Effect.map(base64UrlEncode), |
| 1067 | Effect.mapError( |
| 1068 | (cause) => |
| 1069 | new WebSocketTokenIssueError({ |
| 1070 | sessionId, |
| 1071 | cause: new SessionClaimsEncodingError({ |
| 1072 | sessionId, |
| 1073 | operation: "encode_websocket_claims", |
| 1074 | cause, |
| 1075 | }), |
| 1076 | }), |
| 1077 | ), |
| 1078 | ); |
| 1079 | const signature = yield* signer.sign(encodedPayload); |
| 1080 | return { |
| 1081 | token: `${encodedPayload}.${signature}`, |
| 1082 | expiresAt, |
| 1083 | }; |
| 1084 | }); |
| 1085 | |
| 1086 | const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn( |
| 1087 | "SessionStore.verifyWebSocketToken", |
| 1088 | )(function* (token) { |
| 1089 | const [encodedPayload, signature] = token.split("."); |
| 1090 | if (!encodedPayload || !signature) { |
| 1091 | return yield* new MalformedWebSocketTokenError({}); |
| 1092 | } |
| 1093 | |
| 1094 | if (!(yield* signer.verify(encodedPayload, signature))) { |
| 1095 | return yield* new InvalidWebSocketTokenSignatureError({}); |
| 1096 | } |
| 1097 | |
| 1098 | const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( |
| 1099 | Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })), |
| 1100 | ); |
| 1101 | if (claims.sid.startsWith(REUSABLE_DEV_SESSION_PREFIX) && claims.sid !== devAuth?.sessionId) { |
| 1102 | return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid }); |
| 1103 | } |
| 1104 | |
| 1105 | const observedAt = yield* DateTime.now; |
| 1106 | const expiresAt = DateTime.make(claims.exp); |
| 1107 | if (Option.isNone(expiresAt)) { |
| 1108 | return yield* new InvalidSessionExpirationClaimError({ |
| 1109 | sessionId: claims.sid, |
| 1110 | expirationClaim: claims.exp, |
| 1111 | }); |
| 1112 | } |
| 1113 | if (claims.exp <= observedAt.epochMilliseconds) { |
| 1114 | return yield* new WebSocketTokenExpiredError({ |
| 1115 | sessionId: claims.sid, |
| 1116 | expiresAt: expiresAt.value, |
| 1117 | observedAt, |
| 1118 | }); |
| 1119 | } |
| 1120 | |
| 1121 | const row = yield* authSessions |
| 1122 | .getById({ sessionId: claims.sid }) |
| 1123 | .pipe( |
| 1124 | Effect.mapError( |
| 1125 | (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }), |
| 1126 | ), |
| 1127 | ); |
| 1128 | if (Option.isNone(row)) { |
| 1129 | return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid }); |
| 1130 | } |
| 1131 | if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) { |
| 1132 | return yield* new WebSocketSessionExpiredError({ |
| 1133 | sessionId: claims.sid, |
| 1134 | expiresAt: row.value.expiresAt, |
| 1135 | observedAt, |
| 1136 | }); |
| 1137 | } |
| 1138 | if (row.value.revokedAt !== null) { |
| 1139 | return yield* new WebSocketSessionRevokedError({ |
| 1140 | sessionId: claims.sid, |
| 1141 | revokedAt: row.value.revokedAt, |
| 1142 | }); |
| 1143 | } |
| 1144 | |
| 1145 | return { |
| 1146 | sessionId: row.value.sessionId, |
| 1147 | token, |
| 1148 | method: row.value.method, |
| 1149 | client: toClientMetadata(row.value.client), |
| 1150 | expiresAt: row.value.expiresAt, |
| 1151 | subject: row.value.subject, |
| 1152 | scopes: row.value.scopes, |
| 1153 | ...(claims.aud ? { audience: claims.aud } : {}), |
| 1154 | ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), |
| 1155 | } satisfies VerifiedWebSocketTicket; |
| 1156 | }); |
| 1157 | |
| 1158 | const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")( |
| 1159 | function* () { |
| 1160 | const now = yield* DateTime.now; |
| 1161 | const connectedSessions = yield* Ref.get(connectedSessionsRef); |
| 1162 | const rows = yield* authSessions.listActive({ |
| 1163 | now, |
| 1164 | connectedSessionIds: Array.from(connectedSessions.keys()), |
| 1165 | }); |
| 1166 | |
| 1167 | return rows.map((row) => |
| 1168 | toAuthClientSession({ |
| 1169 | sessionId: row.sessionId, |
| 1170 | subject: row.subject, |
| 1171 | scopes: row.scopes, |
| 1172 | method: row.method, |
| 1173 | client: toClientMetadata(row.client), |
| 1174 | issuedAt: row.issuedAt, |
| 1175 | expiresAt: row.expiresAt, |
| 1176 | lastConnectedAt: row.lastConnectedAt, |
| 1177 | connected: connectedSessions.has(row.sessionId), |
| 1178 | }), |
| 1179 | ); |
| 1180 | }, |
| 1181 | Effect.mapError((cause) => new ActiveSessionsListError({ cause })), |
| 1182 | ); |
| 1183 | |
| 1184 | const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")( |
| 1185 | function* (sessionId) { |
| 1186 | const revokedAt = yield* DateTime.now; |
| 1187 | const revoked = yield* authSessions |
| 1188 | .revoke({ |
| 1189 | sessionId, |
| 1190 | revokedAt, |
| 1191 | }) |
| 1192 | .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause }))); |
| 1193 | if (revoked) { |
| 1194 | yield* Ref.update(connectedSessionsRef, (current) => { |
| 1195 | const next = new Map(current); |
| 1196 | next.delete(sessionId); |
| 1197 | return next; |
| 1198 | }); |
| 1199 | yield* emitRemoved(sessionId); |
| 1200 | } |
| 1201 | return revoked; |
| 1202 | }, |
| 1203 | ); |
| 1204 | |
| 1205 | const proofKeyThumbprintOf: SessionStore["Service"]["proofKeyThumbprintOf"] = (sessionId) => |
| 1206 | authSessions |
| 1207 | .getProofKeyThumbprint({ sessionId }) |
| 1208 | .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "lookup", cause }))); |
| 1209 | |
| 1210 | const revokeByProofKey: SessionStore["Service"]["revokeByProofKey"] = Effect.fn( |
| 1211 | "SessionStore.revokeByProofKey", |
| 1212 | )(function* (proofKeyThumbprint) { |
| 1213 | const revokedAt = yield* DateTime.now; |
| 1214 | const revokedSessionIds = yield* authSessions |
| 1215 | .revokeByProofKey({ proofKeyThumbprint, revokedAt }) |
| 1216 | .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "revoke", cause }))); |
| 1217 | yield* Ref.update(connectedSessionsRef, (current) => { |
| 1218 | const next = new Map(current); |
| 1219 | for (const revokedSessionId of revokedSessionIds) next.delete(revokedSessionId); |
| 1220 | return next; |
| 1221 | }); |
| 1222 | yield* Effect.forEach(revokedSessionIds, emitRemoved, { discard: true }); |
| 1223 | return revokedSessionIds.length; |
| 1224 | }); |
| 1225 | |
| 1226 | const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn( |
| 1227 | "SessionStore.revokeAllExcept", |
| 1228 | )(function* (sessionId) { |
| 1229 | const revokedAt = yield* DateTime.now; |
| 1230 | const revokedSessionIds = yield* authSessions |
| 1231 | .revokeAllExcept({ |
| 1232 | currentSessionId: sessionId, |
| 1233 | revokedAt, |
| 1234 | }) |
| 1235 | .pipe( |
| 1236 | Effect.mapError( |
| 1237 | (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }), |
| 1238 | ), |
| 1239 | ); |
| 1240 | if (revokedSessionIds.length > 0) { |
| 1241 | yield* Ref.update(connectedSessionsRef, (current) => { |
| 1242 | const next = new Map(current); |
| 1243 | for (const revokedSessionId of revokedSessionIds) { |
| 1244 | next.delete(revokedSessionId); |
| 1245 | } |
| 1246 | return next; |
| 1247 | }); |
| 1248 | yield* Effect.forEach( |
| 1249 | revokedSessionIds, |
| 1250 | (revokedSessionId) => emitRemoved(revokedSessionId), |
| 1251 | { |
| 1252 | concurrency: "unbounded", |
| 1253 | discard: true, |
| 1254 | }, |
| 1255 | ); |
| 1256 | } |
| 1257 | return revokedSessionIds.length; |
| 1258 | }); |
| 1259 | |
| 1260 | const awaitInvalidation = Effect.fn(function* ( |
| 1261 | sessionId: AuthSessionId, |
| 1262 | proofKeyThumbprint?: string, |
| 1263 | ) { |
| 1264 | return yield* Effect.scoped( |
| 1265 | Effect.gen(function* () { |
| 1266 | // Subscribe before reading: revocation can race with the WebSocket upgrade. |
| 1267 | const subscription = yield* PubSub.subscribe(changesPubSub); |
| 1268 | const readRow = (id: AuthSessionId) => |
| 1269 | authSessions |
| 1270 | .getById({ sessionId: id }) |
| 1271 | .pipe( |
| 1272 | Effect.mapError( |
| 1273 | (cause) => new SessionCredentialVerificationError({ sessionId: id, cause }), |
| 1274 | ), |
| 1275 | ); |
| 1276 | const original = yield* readRow(sessionId); |
| 1277 | if (Option.isNone(original)) return; |
| 1278 | // Media tickets carry no proof key, so their streams follow the session's own. |
| 1279 | const renewalKey = |
| 1280 | proofKeyThumbprint ?? |
| 1281 | Option.getOrUndefined( |
| 1282 | yield* authSessions |
| 1283 | .getProofKeyThumbprint({ sessionId }) |
| 1284 | .pipe( |
| 1285 | Effect.mapError( |
| 1286 | (cause) => new SessionCredentialVerificationError({ sessionId, cause }), |
| 1287 | ), |
| 1288 | ), |
| 1289 | ); |
| 1290 | // Revoking any session the socket has used closes it. Events only wake this loop |
| 1291 | // and the rows decide: revocations are written before they are published, and |
| 1292 | // clientRemoved also reports an expired session losing its last socket. |
| 1293 | const chain = [sessionId]; |
| 1294 | const nextRemoval = Effect.gen(function* () { |
| 1295 | while (true) { |
| 1296 | const change = yield* PubSub.take(subscription); |
| 1297 | if (change.type === "clientRemoved" && chain.includes(change.sessionId)) return; |
| 1298 | } |
| 1299 | }); |
| 1300 | let current = original.value; |
| 1301 | while (true) { |
| 1302 | const rows = yield* Effect.forEach(chain, readRow); |
| 1303 | if (rows.some((row) => Option.isNone(row) || row.value.revokedAt !== null)) return; |
| 1304 | // Renewal moves a session's expiry in place, so the snapshot can be stale. |
| 1305 | const currentRow = rows.at(-1); |
| 1306 | if (currentRow !== undefined && Option.isSome(currentRow)) current = currentRow.value; |
| 1307 | const now = yield* DateTime.now; |
| 1308 | const remaining = current.expiresAt.epochMilliseconds - now.epochMilliseconds; |
| 1309 | if (remaining > 0) { |
| 1310 | yield* Effect.raceFirst(nextRemoval, Effect.sleep(Duration.millis(remaining))); |
| 1311 | continue; |
| 1312 | } |
| 1313 | // A renewal can land between the read above and the clock sample. |
| 1314 | const latest = yield* readRow(current.sessionId); |
| 1315 | if ( |
| 1316 | Option.isSome(latest) && |
| 1317 | latest.value.expiresAt.epochMilliseconds > current.expiresAt.epochMilliseconds |
| 1318 | ) { |
| 1319 | current = latest.value; |
| 1320 | continue; |
| 1321 | } |
| 1322 | const successorId = |
| 1323 | renewalKey === undefined ? undefined : latestSessionByProofKey.get(renewalKey); |
| 1324 | if (successorId === undefined || successorId === current.sessionId) return; |
| 1325 | const successor = yield* readRow(successorId); |
| 1326 | // The socket keeps its original scopes, so the renewal must still grant all of them. |
| 1327 | if ( |
| 1328 | Option.isNone(successor) || |
| 1329 | successor.value.subject !== original.value.subject || |
| 1330 | !original.value.scopes.every((scope) => successor.value.scopes.includes(scope)) |
| 1331 | ) { |
| 1332 | return; |
| 1333 | } |
| 1334 | chain.push(successorId); |
| 1335 | current = successor.value; |
| 1336 | } |
| 1337 | }), |
| 1338 | ); |
| 1339 | }); |
| 1340 | |
| 1341 | return SessionStore.of({ |
| 1342 | cookieName, |
| 1343 | legacyCookieName, |
| 1344 | issue, |
| 1345 | renew, |
| 1346 | extend, |
| 1347 | verify, |
| 1348 | issueWebSocketToken, |
| 1349 | verifyWebSocketToken, |
| 1350 | listActive, |
| 1351 | awaitInvalidation, |
| 1352 | get streamChanges() { |
| 1353 | return Stream.fromPubSub(changesPubSub); |
| 1354 | }, |
| 1355 | revoke, |
| 1356 | revokeAllExcept, |
| 1357 | proofKeyThumbprintOf, |
| 1358 | revokeByProofKey, |
| 1359 | markConnected, |
| 1360 | markDisconnected, |
| 1361 | }); |
| 1362 | }); |
| 1363 | |
| 1364 | export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer)); |