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