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