( request: Request, jwt: JwtBearerConfig | null = null, )
| 203 | * resolved (mirrored on first read) for its name and slug. |
| 204 | */ |
| 205 | export const resolveBearerAuth = ( |
| 206 | request: Request, |
| 207 | jwt: JwtBearerConfig | null = null, |
| 208 | ): Effect.Effect< |
| 209 | BearerAuth, |
| 210 | | Unauthorized |
| 211 | | NoOrganization |
| 212 | | Unavailable |
| 213 | | UserStoreError |
| 214 | | WorkOSError |
| 215 | | WorkOsMirrorError |
| 216 | | MemberDirectoryError, |
| 217 | WorkOSClient | ApiKeyService | UserStoreService | MemberDirectory | WorkOsMirror |
| 218 | > => |
| 219 | Effect.gen(function* () { |
| 220 | const authHeader = request.headers.get("authorization"); |
| 221 | if (!authHeader) return null; |
| 222 | |
| 223 | if (!authHeader.startsWith(BEARER_PREFIX)) { |
| 224 | return yield* new Unauthorized(INVALID_AUTHORIZATION_HEADER); |
| 225 | } |
| 226 | |
| 227 | const value = authHeader.slice(BEARER_PREFIX.length).trim(); |
| 228 | if (!value) return yield* new Unauthorized(INVALID_API_KEY); |
| 229 | |
| 230 | if (jwt && looksLikeJwt(value)) return yield* resolveJwtPrincipal(value, jwt); |
| 231 | |
| 232 | const apiKeys = yield* ApiKeyService; |
| 233 | const owner = yield* apiKeys |
| 234 | .validate(value) |
| 235 | .pipe( |
| 236 | Effect.catchTag("ApiKeyValidationError", () => |
| 237 | Effect.fail(new Unavailable(API_KEY_VALIDATION_UNAVAILABLE)), |
| 238 | ), |
| 239 | ); |
| 240 | |
| 241 | if (!owner) return yield* new Unauthorized(INVALID_API_KEY); |
| 242 | |
| 243 | if (owner.scope === "org") { |
| 244 | const org = yield* resolveOrganization(owner.organizationId); |
| 245 | // The key outlives the org until the purge removes it; an org marked |
| 246 | // deleted refuses it as it refuses every member's session. |
| 247 | if (org.deletedAt !== null) return yield* new NoOrganization(NO_ORGANIZATION_IN_API_KEY); |
| 248 | return { |
| 249 | kind: "platform", |
| 250 | organizationId: org.id, |
| 251 | organizationName: org.name, |
| 252 | ...(org.slug === undefined || org.slug === null ? {} : { organizationSlug: org.slug }), |
| 253 | keyId: owner.keyId, |
| 254 | } satisfies PlatformAuth; |
| 255 | } |
| 256 | |
| 257 | // A `"user"` key always carries an accountId (see `ownerFromApiKey`); the |
| 258 | // guard keeps the narrowing honest rather than asserting. |
| 259 | if (owner.accountId == null) return yield* new Unauthorized(INVALID_API_KEY); |
| 260 | |
| 261 | const org = yield* authorizeOrganization(owner.accountId, owner.organizationId); |
| 262 | if (!org) return yield* new NoOrganization(NO_ORGANIZATION_IN_API_KEY); |
no test coverage detected