@krak-stack/auth 0.2.31 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +175 -1
  3. package/dist/access.d.ts +3 -1
  4. package/dist/admin/api.group.d.ts +41 -41
  5. package/dist/admin/schema.d.ts +23 -23
  6. package/dist/admin/schema.js +21 -19
  7. package/dist/api.d.ts +141 -81
  8. package/dist/auth/api.group.d.ts +37 -19
  9. package/dist/auth/api.group.js +17 -1
  10. package/dist/auth/schema.d.ts +61 -33
  11. package/dist/auth/schema.js +30 -18
  12. package/dist/components/account-deletion-request.d.ts +5 -0
  13. package/dist/components/account-deletion-request.js +7 -0
  14. package/dist/components/account-deletion.d.ts +8 -0
  15. package/dist/components/account-deletion.js +59 -0
  16. package/dist/components/admin-organization-form.js +2 -2
  17. package/dist/components/admin-organizations.js +9 -7
  18. package/dist/components/admin-users.js +6 -6
  19. package/dist/components/api-key-edit-form.js +19 -11
  20. package/dist/components/associated-projects-notice.d.ts +2 -1
  21. package/dist/components/associated-projects-notice.js +7 -3
  22. package/dist/components/auth-atoms.js +1 -2
  23. package/dist/components/auth-client-api.d.ts +94 -61
  24. package/dist/components/auth-forms.d.ts +1 -0
  25. package/dist/components/auth-forms.js +41 -56
  26. package/dist/components/auth-provider.d.ts +3 -1
  27. package/dist/components/deletion-visibility.d.ts +1 -0
  28. package/dist/components/deletion-visibility.js +3 -0
  29. package/dist/components/hooks.d.ts +2 -0
  30. package/dist/components/hooks.js +13 -6
  31. package/dist/components/index.d.ts +3 -0
  32. package/dist/components/index.js +2 -0
  33. package/dist/components/member-required.js +3 -5
  34. package/dist/components/oauth-consent.d.ts +22 -0
  35. package/dist/components/oauth-consent.js +79 -0
  36. package/dist/components/organization-deletion-request.d.ts +17 -0
  37. package/dist/components/organization-deletion-request.js +9 -0
  38. package/dist/components/organization-switcher.d.ts +1 -1
  39. package/dist/components/organization-switcher.js +113 -55
  40. package/dist/components/project-card-list.d.ts +6 -0
  41. package/dist/components/project-card-list.js +4 -0
  42. package/dist/components/user-button.d.ts +29 -1
  43. package/dist/components/user-button.js +145 -47
  44. package/dist/extra/api.group.d.ts +13 -1
  45. package/dist/extra/api.group.js +5 -1
  46. package/dist/extra/schema.d.ts +16 -1
  47. package/dist/extra/schema.js +13 -0
  48. package/dist/oauth/authorization.d.ts +3 -0
  49. package/dist/oauth/authorization.js +39 -0
  50. package/dist/oauth/schema.d.ts +24 -0
  51. package/dist/oauth/schema.js +12 -0
  52. package/dist/oauth/verify.d.ts +13 -0
  53. package/dist/oauth/verify.js +67 -0
  54. package/dist/schema.d.ts +35 -0
  55. package/dist/schema.js +26 -1
  56. package/dist/server/actor.js +2 -4
  57. package/dist/server/index.d.ts +4 -1
  58. package/dist/server/index.js +2 -0
  59. package/dist/server/mcp.d.ts +20 -0
  60. package/dist/server/mcp.js +66 -0
  61. package/dist/server/middleware.d.ts +15 -7
  62. package/dist/server/middleware.js +19 -6
  63. package/dist/server/webhook-layer.d.ts +6 -0
  64. package/dist/server/webhook-layer.js +41 -0
  65. package/dist/server/webhooks.d.ts +44 -0
  66. package/dist/server/webhooks.js +39 -0
  67. package/dist/service.d.ts +118 -46
  68. package/dist/service.js +56 -9
  69. package/package.json +8 -3
package/dist/schema.d.ts CHANGED
@@ -1,4 +1,39 @@
1
1
  import { Schema } from "effect";
2
+ export declare const AuthWebhookData: Schema.StructWithRest<Schema.Struct<{
3
+ readonly projectId: Schema.NonEmptyString;
4
+ }>, readonly [Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
5
+ export declare const AuthWebhook: Schema.Struct<{
6
+ readonly event: Schema.NonEmptyString;
7
+ readonly data: Schema.StructWithRest<Schema.Struct<{
8
+ readonly projectId: Schema.NonEmptyString;
9
+ }>, readonly [Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
10
+ }>;
11
+ export declare const AccountDeletionData: Schema.Struct<{
12
+ readonly projectId: Schema.NonEmptyString;
13
+ readonly userId: Schema.NonEmptyString;
14
+ readonly scope: Schema.Literal<"account">;
15
+ }>;
16
+ export declare const AccountDeletionWebhook: Schema.Struct<{
17
+ readonly event: Schema.Literal<"user.deletion_requested">;
18
+ readonly data: Schema.Struct<{
19
+ readonly projectId: Schema.NonEmptyString;
20
+ readonly userId: Schema.NonEmptyString;
21
+ readonly scope: Schema.Literal<"account">;
22
+ }>;
23
+ }>;
24
+ export declare const OrganizationDeletionData: Schema.Struct<{
25
+ readonly projectId: Schema.NonEmptyString;
26
+ readonly organizationId: Schema.NonEmptyString;
27
+ readonly scope: Schema.Literal<"organization">;
28
+ }>;
29
+ export declare const OrganizationDeletionWebhook: Schema.Struct<{
30
+ readonly event: Schema.Literal<"organization.deletion_requested">;
31
+ readonly data: Schema.Struct<{
32
+ readonly projectId: Schema.NonEmptyString;
33
+ readonly organizationId: Schema.NonEmptyString;
34
+ readonly scope: Schema.Literal<"organization">;
35
+ }>;
36
+ }>;
2
37
  export declare const Session: Schema.Struct<{
3
38
  readonly id: Schema.String;
4
39
  readonly expiresAt: Schema.Date;
package/dist/schema.js CHANGED
@@ -1,4 +1,29 @@
1
1
  import { Option, Schema, SchemaGetter } from "effect";
2
+ export const AuthWebhookData = Schema.StructWithRest(Schema.Struct({
3
+ projectId: Schema.NonEmptyString,
4
+ }), [Schema.Record(Schema.String, Schema.Json)]).annotate({ identifier: "AuthWebhookData" });
5
+ export const AuthWebhook = Schema.Struct({
6
+ event: Schema.NonEmptyString,
7
+ data: AuthWebhookData,
8
+ }).annotate({ identifier: "AuthWebhook" });
9
+ export const AccountDeletionData = Schema.Struct({
10
+ projectId: Schema.NonEmptyString,
11
+ userId: Schema.NonEmptyString,
12
+ scope: Schema.Literal("account"),
13
+ }).annotate({ identifier: "AccountDeletionData" });
14
+ export const AccountDeletionWebhook = Schema.Struct({
15
+ event: Schema.Literal("user.deletion_requested"),
16
+ data: AccountDeletionData,
17
+ }).annotate({ identifier: "AccountDeletionWebhook" });
18
+ export const OrganizationDeletionData = Schema.Struct({
19
+ projectId: Schema.NonEmptyString,
20
+ organizationId: Schema.NonEmptyString,
21
+ scope: Schema.Literal("organization"),
22
+ }).annotate({ identifier: "OrganizationDeletionData" });
23
+ export const OrganizationDeletionWebhook = Schema.Struct({
24
+ event: Schema.Literal("organization.deletion_requested"),
25
+ data: OrganizationDeletionData,
26
+ }).annotate({ identifier: "OrganizationDeletionWebhook" });
2
27
  export const Session = Schema.Struct({
3
28
  id: Schema.String,
4
29
  expiresAt: Schema.Date,
@@ -202,7 +227,7 @@ export const decodeUserMetadata = (metadata) => {
202
227
  metadataValue = { ...metadataValue, websites: websites.value };
203
228
  if (Option.isSome(socials))
204
229
  metadataValue = { ...metadataValue, socials: socials.value };
205
- return Option.getOrElse(Schema.decodeUnknownOption(UserMetadata)(metadataValue), () => ({}));
230
+ return Option.getOrElse(Schema.decodeOption(UserMetadata)(metadataValue), () => ({}));
206
231
  };
207
232
  export const UserMetadataStandard = Schema.toStandardSchemaV1(UserMetadata);
208
233
  const CompatibleUserMetadata = Schema.Unknown.pipe(Schema.decodeTo(UserMetadata, {
@@ -15,7 +15,7 @@ const resolveCurrentActor = (access) => Effect.gen(function* () {
15
15
  const session = yield* auth.requireSession();
16
16
  if (session.authMethod.type === "apiKey") {
17
17
  const apiKey = session.authMethod.apiKey;
18
- const grant = yield* Schema.decodeUnknownEffect(ApiKeyPermissionGrant)(apiKey.permissions ?? {}).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
18
+ const grant = yield* Schema.decodeEffect(ApiKeyPermissionGrant)(apiKey.permissions ?? {}).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
19
19
  const organizationId = session.session.activeOrganizationId;
20
20
  if (!organizationId)
21
21
  return yield* new HttpApiError.Unauthorized({});
@@ -107,9 +107,7 @@ const matchesConstraint = (actor, constraint) => {
107
107
  return (actor.actor.type === "apiKey" &&
108
108
  (!constraint.ownerType || actor.actor.owner.type === constraint.ownerType));
109
109
  };
110
- const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.flatMap((actor) => matchesConstraint(actor, constraint)
111
- ? Effect.succeed(actor)
112
- : Effect.fail(new HttpApiError.Forbidden({}))));
110
+ const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.filterOrFail((actor) => matchesConstraint(actor, constraint), () => new HttpApiError.Forbidden({})));
113
111
  const withCurrentActor = (httpEffect, actor) => {
114
112
  const roles = actor.actor.type === "user"
115
113
  ? actor.actor.roles
@@ -1,4 +1,7 @@
1
1
  export { AuthService } from "../service.js";
2
+ export type { OAuthResourceOptions } from "../oauth/schema.js";
3
+ export { McpAuth } from "./mcp.js";
4
+ export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
2
5
  export type { AuthSession, AuthSessionWithOrganization, AuthSessionWithUser, AuthSessionWithUserAndOrganization, } from "../service.js";
3
6
  export { AuthClientConfig } from "../config.js";
4
7
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group.js";
@@ -8,7 +11,7 @@ export { AuthProxyError, authProxyKeyHeader, proxyOriginHeaders, readProxyOrigin
8
11
  export { ActorRequired } from "./actor.js";
9
12
  export type { ActorConstraint } from "./actor.js";
10
13
  export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware.js";
11
- export type { AuthenticationLiveOptions, AuthRouterOptions, } from "./middleware.js";
14
+ export type { AuthMiddlewareOptions, AuthenticationLiveOptions, AuthRouterOptions, } from "./middleware.js";
12
15
  export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema.js";
13
16
  export type { Member, Organization, OrganizationMetadata, User, } from "../schema.js";
14
17
  export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access.js";
@@ -1,4 +1,6 @@
1
1
  export { AuthService } from "../service.js";
2
+ export { McpAuth } from "./mcp.js";
3
+ export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
2
4
  export { AuthClientConfig } from "../config.js";
3
5
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group.js";
4
6
  export { proxyAuthHttpEffect, proxyAuthRequest, proxyAuthRequestEffect, } from "./proxy.js";
@@ -0,0 +1,20 @@
1
+ import { Layer } from "effect";
2
+ import { HttpRouter } from "effect/http";
3
+ import type { OAuthResourceOptions } from "../oauth/schema.js";
4
+ declare const metadataPath: (resource: string) => `/${string}`;
5
+ /** OAuth discovery and authentication for an existing MCP transport. */
6
+ export declare const McpAuth: {
7
+ metadataPath: typeof metadataPath;
8
+ /** Forward public discovery through the consumer's existing auth proxy. */
9
+ discoveryRequest: (request: Request, options: OAuthResourceOptions) => Request | undefined;
10
+ metadataLayer: (options: OAuthResourceOptions) => Layer.Layer<never, never, HttpRouter.HttpRouter>;
11
+ middleware: (options: OAuthResourceOptions) => HttpRouter.Middleware<{
12
+ provides: never;
13
+ handles: never;
14
+ error: never;
15
+ requires: never;
16
+ layerError: never;
17
+ layerRequires: never;
18
+ }>;
19
+ };
20
+ export {};
@@ -0,0 +1,66 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse, } from "effect/http";
3
+ import { verifyOAuthAccessToken } from "../oauth/verify.js";
4
+ const metadataPath = (resource) => `/.well-known/oauth-protected-resource${new URL(resource).pathname.replace(/\/$/, "")}`;
5
+ const challenge = (options, insufficientScope = false) => {
6
+ const metadataUrl = new URL(metadataPath(options.resource), options.resource)
7
+ .href;
8
+ const scopes = insufficientScope
9
+ ? options.requiredScopes
10
+ : (options.challengeScopes ?? options.requiredScopes);
11
+ return `Bearer resource_metadata="${metadataUrl}"${insufficientScope ? ', error="insufficient_scope"' : ""}, scope="${scopes.join(" ")}"`;
12
+ };
13
+ /** OAuth discovery and authentication for an existing MCP transport. */
14
+ export const McpAuth = {
15
+ metadataPath,
16
+ /** Forward public discovery through the consumer's existing auth proxy. */
17
+ discoveryRequest: (request, options) => {
18
+ const url = new URL(request.url);
19
+ const issuer = new URL(options.issuer);
20
+ if (url.pathname ===
21
+ `/.well-known/oauth-authorization-server${issuer.pathname.replace(/\/$/, "")}`) {
22
+ url.pathname = `${issuer.pathname.replace(/\/$/, "")}/.well-known/oauth-authorization-server`;
23
+ return new Request(url, request);
24
+ }
25
+ if (url.pathname === "/.well-known/oauth-protected-resource" ||
26
+ url.pathname === metadataPath(options.resource))
27
+ return request;
28
+ return undefined;
29
+ },
30
+ metadataLayer: (options) => {
31
+ const response = HttpServerResponse.jsonUnsafe({
32
+ resource: options.resource,
33
+ authorization_servers: [options.issuer],
34
+ scopes_supported: options.scopesSupported ?? options.requiredScopes,
35
+ bearer_methods_supported: ["header"],
36
+ }, { headers: { "access-control-allow-origin": "*" } });
37
+ return Layer.mergeAll(HttpRouter.add("GET", metadataPath(options.resource), Effect.succeed(response)), HttpRouter.add("GET", "/.well-known/oauth-protected-resource", Effect.succeed(response)));
38
+ },
39
+ middleware: (options) => HttpRouter.middleware((httpEffect) => Effect.gen(function* () {
40
+ const request = yield* HttpServerRequest.HttpServerRequest;
41
+ const authorization = request.headers.authorization;
42
+ // Preserve explicitly supplied API keys for existing integrations. Their
43
+ // normal API authorization remains authoritative for tool execution.
44
+ if (authorization === undefined && request.headers["x-api-key"])
45
+ return yield* httpEffect;
46
+ const match = authorization?.match(/^Bearer ([^\s]+)$/i);
47
+ if (!match?.[1])
48
+ return HttpServerResponse.empty({
49
+ status: 401,
50
+ headers: { "www-authenticate": challenge(options) },
51
+ });
52
+ const result = yield* verifyOAuthAccessToken(match[1], options).pipe(Effect.provide(FetchHttpClient.layer), Effect.result);
53
+ if (result._tag === "Failure") {
54
+ if (result.failure._tag === "ServiceUnavailable")
55
+ return HttpServerResponse.empty({ status: 503 });
56
+ const insufficientScope = result.failure._tag === "Forbidden";
57
+ return HttpServerResponse.empty({
58
+ status: insufficientScope ? 403 : 401,
59
+ headers: {
60
+ "www-authenticate": challenge(options, insufficientScope),
61
+ },
62
+ });
63
+ }
64
+ return yield* httpEffect;
65
+ })),
66
+ };
@@ -1,7 +1,8 @@
1
- import { Layer } from "effect";
1
+ import { Effect, Layer, Redacted } from "effect";
2
2
  import { HttpRouter, HttpServerRequest } from "effect/http";
3
3
  import { HttpApiError, HttpApiMiddleware, HttpApiSecurity } from "effect/http-api";
4
4
  import { AuthService, type AuthServiceLayerOptions } from "../service.js";
5
+ import type { AccountDeletionData, OrganizationDeletionData, AuthWebhook } from "../schema.js";
5
6
  export declare const ApiKeySecurity: HttpApiSecurity.ApiKey;
6
7
  declare const AuthMiddleware_base: HttpApiMiddleware.ServiceClass<AuthMiddleware, "@krak-stack/auth/AuthMiddleware", {
7
8
  requires: never;
@@ -16,20 +17,27 @@ declare const AuthMiddleware_base: HttpApiMiddleware.ServiceClass<AuthMiddleware
16
17
  readonly apiKey: HttpApiSecurity.ApiKey;
17
18
  }, AuthService, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden, typeof HttpApiError.ServiceUnavailable], never>>;
18
19
  export declare class AuthMiddleware extends AuthMiddleware_base {
19
- static readonly layer: (options?: AuthenticationLiveOptions | Layer.Layer<AuthService, unknown>) => Layer.Layer<AuthMiddleware, never, never>;
20
+ static readonly layer: <E, R>(options: AuthMiddlewareOptions<E, R>) => Layer.Layer<AuthMiddleware, import("./webhooks.js").AuthWebhookConfigurationError | import("effect/Config").ConfigError | import("effect/sql/Migrator").MigrationError | import("effect/Schema").SchemaError | import("effect/sql/SqlError").SqlError, HttpRouter.HttpRouter | import("effect/sql/SqlClient").SqlClient | Exclude<Exclude<R, import("effect/Scope").Scope>, import("@krak-stack/registry/webhooks").WebhooksReceiver>>;
20
21
  /** The same optional authentication and attribution for plain HttpRouter routes. */
21
- static readonly routerLayer: (options?: AuthRouterOptions) => Layer.Layer<never, import("effect/Config").ConfigError, HttpRouter.Request<"Error", HttpApiError.Forbidden> | HttpRouter.Request<"Error", HttpApiError.ServiceUnavailable>>;
22
+ static readonly routerLayer: <E>(options?: AuthRouterOptions<E>) => Layer.Layer<never, import("effect/Config").ConfigError, HttpRouter.Request<"Error", HttpApiError.Forbidden> | HttpRouter.Request<"Error", HttpApiError.ServiceUnavailable>>;
22
23
  }
23
- export type AuthenticationLiveOptions = AuthServiceLayerOptions & {
24
+ export type AuthenticationLiveOptions<E = unknown> = AuthServiceLayerOptions & {
24
25
  readonly allowedOrganizationImpersonationRoutes?: readonly {
25
26
  readonly method: string;
26
27
  readonly path: string;
27
28
  }[];
28
- readonly authLayer?: Layer.Layer<AuthService, unknown, HttpServerRequest.HttpServerRequest>;
29
+ readonly authLayer?: Layer.Layer<AuthService, E, HttpServerRequest.HttpServerRequest>;
29
30
  };
30
- export type AuthRouterOptions = AuthenticationLiveOptions & {
31
+ export type AuthMiddlewareOptions<E, R> = AuthenticationLiveOptions & {
32
+ readonly projectId?: string;
33
+ readonly webhookSecret?: Redacted.Redacted<string>;
34
+ readonly onDeleteUser: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
35
+ readonly onDeleteOrganization: (data: typeof OrganizationDeletionData.Type) => Effect.Effect<void, E, R>;
36
+ readonly onWebhook?: (webhook: typeof AuthWebhook.Type) => Effect.Effect<void, E, R>;
37
+ };
38
+ export type AuthRouterOptions<E = unknown> = AuthenticationLiveOptions<E> & {
31
39
  /** Resolve auth only for these exact URL pathnames. Defaults to every route in scope. */
32
40
  readonly paths?: readonly string[];
33
41
  };
34
- export declare const makeAuthenticationLive: (options?: AuthenticationLiveOptions | Layer.Layer<AuthService, unknown>) => Layer.Layer<AuthMiddleware, never, never>;
42
+ export declare const makeAuthenticationLive: <E>(options?: AuthenticationLiveOptions<E> | Layer.Layer<AuthService, E>) => Layer.Layer<AuthMiddleware, never, never>;
35
43
  export {};
@@ -18,7 +18,10 @@ export class AuthMiddleware extends HttpApiMiddleware.Service()("@krak-stack/aut
18
18
  apiKey: ApiKeySecurity,
19
19
  },
20
20
  }) {
21
- static layer = (options = {}) => makeAuthenticationLive(options);
21
+ static layer = (options) => Layer.merge(makeAuthenticationLive(options), Layer.unwrap(
22
+ // API contracts also import this class in the browser. Load persistence
23
+ // only when the server acquires its implementation layer.
24
+ Effect.promise(() => import("./webhook-layer.js")).pipe(Effect.map(({ makeAuthWebhookLayer }) => makeAuthWebhookLayer(options)))));
22
25
  /** The same optional authentication and attribution for plain HttpRouter routes. */
23
26
  static routerLayer = (options = {}) => HttpRouter.middleware(Effect.gen(function* () {
24
27
  const config = options.authLayer
@@ -48,16 +51,22 @@ export const makeAuthenticationLive = (options = {}) => {
48
51
  };
49
52
  const authenticateRequest = Effect.fnUntraced(function* (options, authLayer, apiKey) {
50
53
  const request = yield* HttpServerRequest.HttpServerRequest;
51
- const auth = yield* AuthService.pipe(Effect.provide(authLayer ??
54
+ const resolvedAuthLayer = authLayer ??
52
55
  AuthService.layer({
53
56
  ...options,
54
57
  headers: apiKey
55
58
  ? { ...request.headers, "x-api-key": apiKey }
56
59
  : request.headers,
57
- })), Effect.tapCause((cause) => Effect.logError("Authentication rejected: auth client initialization failed", Cause.pretty(cause))), Effect.mapError(() => new HttpApiError.ServiceUnavailable({})));
60
+ });
61
+ const auth = yield* AuthService.pipe(Effect.provide(resolvedAuthLayer), Effect.tapCause((cause) => Effect.logError("Authentication rejected: auth client initialization failed", Cause.pretty(cause))), Effect.mapError(() => new HttpApiError.ServiceUnavailable({})));
58
62
  const session = yield* auth
59
63
  .getSession()
60
64
  .pipe(Effect.catchTag("Unauthorized", () => Effect.succeed(null)));
65
+ if (session?.authMethod.type === "oauth" &&
66
+ (!(options.oauth?.allowedMethods ?? ["GET", "HEAD"]).includes(request.method) ||
67
+ (!["GET", "HEAD"].includes(request.method) &&
68
+ !session.authMethod.scopes.includes(options.oauth?.writeScope ?? "mcp:write"))))
69
+ return yield* new HttpApiError.Forbidden({});
61
70
  if (session?.session.impersonatedByOrganizationId &&
62
71
  !isAllowedRoute(options.allowedOrganizationImpersonationRoutes ?? [], request)) {
63
72
  return yield* new HttpApiError.Forbidden({});
@@ -69,7 +78,7 @@ const sessionAnnotations = (session) => {
69
78
  if (!session)
70
79
  return attributes;
71
80
  if (session.user &&
72
- (session.authMethod.type === "cookie" ||
81
+ (session.authMethod.type !== "apiKey" ||
73
82
  session.authMethod.apiKey.configId === "user")) {
74
83
  attributes["user.id"] = session.user.id;
75
84
  attributes["user.full_name"] = session.user.name;
@@ -78,10 +87,14 @@ const sessionAnnotations = (session) => {
78
87
  if (session.session.activeOrganizationId) {
79
88
  attributes["organization.id"] = session.session.activeOrganizationId;
80
89
  }
81
- if (session.authMethod.type === "cookie" && session.user) {
90
+ if (session.authMethod.type !== "apiKey" && session.user) {
82
91
  attributes["app.actor.type"] = "user";
83
92
  attributes["app.actor.id"] = session.user.id;
84
- attributes["app.auth.method"] = "session";
93
+ attributes["app.auth.method"] =
94
+ session.authMethod.type === "oauth" ? "oauth" : "session";
95
+ if (session.authMethod.type === "oauth") {
96
+ attributes["app.auth.client.id"] = session.authMethod.clientId;
97
+ }
85
98
  if (session.session.impersonatedBy) {
86
99
  attributes["app.auth.impersonator.id"] = session.session.impersonatedBy;
87
100
  }
@@ -0,0 +1,6 @@
1
+ import { Config, Layer, Schema } from "effect";
2
+ import { HttpRouter } from "effect/http";
3
+ import { WebhooksReceiver } from "@krak-stack/registry/webhooks";
4
+ import type { AuthMiddlewareOptions } from "./middleware.js";
5
+ import { AuthWebhookConfigurationError } from "./webhooks.js";
6
+ export declare const makeAuthWebhookLayer: <E, R>(options: AuthMiddlewareOptions<E, R>) => Layer.Layer<never, AuthWebhookConfigurationError | Config.ConfigError | import("effect/sql/Migrator").MigrationError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, HttpRouter.HttpRouter | import("effect/sql/SqlClient").SqlClient | Exclude<Exclude<R, import("effect/Scope").Scope>, WebhooksReceiver>>;
@@ -0,0 +1,41 @@
1
+ import { ByteSize, Config, Effect, Layer, Redacted, Schema } from "effect";
2
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
+ import { WebhooksReceiver } from "@krak-stack/registry/webhooks";
4
+ import { AuthWebhookCleanupError, AuthWebhookConfigurationError, receiveAuthWebhook, } from "./webhooks.js";
5
+ export const makeAuthWebhookLayer = (options) => Layer.unwrap(Effect.gen(function* () {
6
+ const receiver = yield* WebhooksReceiver;
7
+ const services = yield* Effect.context();
8
+ const projectId = yield* Schema.decodeEffect(Schema.NonEmptyString)(options.projectId ??
9
+ (yield* Config.NonEmptyString("VITE_KRAKSTACK_AUTH_PROJECT_ID")));
10
+ const secret = options.webhookSecret ??
11
+ (yield* Config.Redacted("KRAKSTACK_AUTH_WEBHOOK_SECRET"));
12
+ if (!Schema.is(Schema.String.check(Schema.isMinLength(32)))(Redacted.value(secret))) {
13
+ return yield* new AuthWebhookConfigurationError({
14
+ message: "The auth webhook signing secret must contain at least 32 characters",
15
+ });
16
+ }
17
+ const onWebhook = options.onWebhook;
18
+ const handle = Effect.gen(function* () {
19
+ const request = yield* HttpServerRequest.HttpServerRequest;
20
+ const body = yield* request.text;
21
+ yield* receiveAuthWebhook({
22
+ projectId,
23
+ secret,
24
+ body,
25
+ headers: request.headers,
26
+ onDeleteUser: (data) => options.onDeleteUser(data).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({}))),
27
+ onDeleteOrganization: (data) => options.onDeleteOrganization(data).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({}))),
28
+ onWebhook: onWebhook
29
+ ? (webhook) => onWebhook(webhook).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({})))
30
+ : undefined,
31
+ }).pipe(Effect.provideService(WebhooksReceiver, receiver));
32
+ return HttpServerResponse.empty({ status: 204 });
33
+ }).pipe(Effect.provideService(HttpServerRequest.MaxBodySize, ByteSize.kibibytes(16)), Effect.catchTags({
34
+ WebhookVerificationError: (error) => Effect.succeed(HttpServerResponse.empty({
35
+ status: error.reason === "payload" ? 400 : 401,
36
+ })),
37
+ WebhookReceiptConflict: () => Effect.succeed(HttpServerResponse.empty({ status: 409 })),
38
+ UnsupportedAuthWebhook: () => Effect.succeed(HttpServerResponse.empty({ status: 400 })),
39
+ }), Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500 })));
40
+ return HttpRouter.add("POST", "/api/webhooks/auth", handle);
41
+ })).pipe(Layer.provide(WebhooksReceiver.layer));
@@ -0,0 +1,44 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { WebhooksReceiver, WebhookVerificationError } from "@krak-stack/registry/webhooks";
3
+ import { AccountDeletionData, OrganizationDeletionData, AuthWebhook } from "../schema.js";
4
+ export { AccountDeletionData, AccountDeletionWebhook } from "../schema.js";
5
+ export { OrganizationDeletionData, OrganizationDeletionWebhook, } from "../schema.js";
6
+ export { AuthWebhook, AuthWebhookData } from "../schema.js";
7
+ declare const AuthWebhookConfigurationError_base: Schema.Class<AuthWebhookConfigurationError, Schema.TaggedStruct<"AuthWebhookConfigurationError", {
8
+ readonly message: Schema.String;
9
+ }>, import("effect/Cause").YieldableError & {
10
+ readonly brand: unique symbol;
11
+ }>;
12
+ export declare class AuthWebhookConfigurationError extends AuthWebhookConfigurationError_base {
13
+ }
14
+ declare const AuthWebhookCleanupError_base: Schema.Class<AuthWebhookCleanupError, Schema.TaggedStruct<"AuthWebhookCleanupError", {}>, import("effect/Cause").YieldableError & {
15
+ readonly brand: unique symbol;
16
+ }>;
17
+ export declare class AuthWebhookCleanupError extends AuthWebhookCleanupError_base {
18
+ }
19
+ declare const UnsupportedAuthWebhook_base: Schema.Class<UnsupportedAuthWebhook, Schema.TaggedStruct<"UnsupportedAuthWebhook", {}>, import("effect/Cause").YieldableError & {
20
+ readonly brand: unique symbol;
21
+ }>;
22
+ export declare class UnsupportedAuthWebhook extends UnsupportedAuthWebhook_base {
23
+ }
24
+ /** Acknowledge only after the app's same-database cleanup has committed. */
25
+ export declare const receiveAuthWebhook: <E, R>(input: {
26
+ readonly projectId: string;
27
+ readonly secret: Redacted.Redacted<string>;
28
+ readonly headers: Readonly<Record<string, string | undefined>>;
29
+ readonly body: string;
30
+ readonly onDeleteUser: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
31
+ readonly onDeleteOrganization: (data: typeof OrganizationDeletionData.Type) => Effect.Effect<void, E, R>;
32
+ readonly onWebhook?: ((webhook: typeof AuthWebhook.Type) => Effect.Effect<void, E, R>) | undefined;
33
+ }) => Effect.Effect<{
34
+ duplicate: boolean;
35
+ }, E | import("effect/crypto/CryptoError").CryptoError | import("effect/Cause").NoSuchElementError | Schema.SchemaError | import("effect/sql/SqlError").SqlError | UnsupportedAuthWebhook | import("@krak-stack/registry/webhooks").WebhookReceiptConflict | WebhookVerificationError, R | WebhooksReceiver>;
36
+ export declare const receiveAccountDeletion: <E, R>(input: {
37
+ readonly projectId: string;
38
+ readonly secret: Redacted.Redacted<string>;
39
+ readonly headers: Readonly<Record<string, string | undefined>>;
40
+ readonly body: string;
41
+ readonly handle: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
42
+ }) => Effect.Effect<{
43
+ duplicate: boolean;
44
+ }, E | import("effect/crypto/CryptoError").CryptoError | import("effect/Cause").NoSuchElementError | Schema.SchemaError | import("effect/sql/SqlError").SqlError | UnsupportedAuthWebhook | import("@krak-stack/registry/webhooks").WebhookReceiptConflict | WebhookVerificationError, R | WebhooksReceiver>;
@@ -0,0 +1,39 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { WebhooksReceiver, WebhookVerificationError, } from "@krak-stack/registry/webhooks";
3
+ import { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, AuthWebhook, OrganizationDeletionWebhook, } from "../schema.js";
4
+ export { AccountDeletionData, AccountDeletionWebhook } from "../schema.js";
5
+ export { OrganizationDeletionData, OrganizationDeletionWebhook, } from "../schema.js";
6
+ export { AuthWebhook, AuthWebhookData } from "../schema.js";
7
+ export class AuthWebhookConfigurationError extends Schema.TaggedError()("AuthWebhookConfigurationError", {
8
+ message: Schema.String,
9
+ }) {
10
+ }
11
+ export class AuthWebhookCleanupError extends Schema.TaggedError()("AuthWebhookCleanupError", {}) {
12
+ }
13
+ export class UnsupportedAuthWebhook extends Schema.TaggedError()("UnsupportedAuthWebhook", {}) {
14
+ }
15
+ /** Acknowledge only after the app's same-database cleanup has committed. */
16
+ export const receiveAuthWebhook = Effect.fn("Auth.receiveAuthWebhook")(function* (input) {
17
+ const receiver = yield* WebhooksReceiver;
18
+ return yield* receiver.receive({
19
+ receiver: `krakstack-auth:${input.projectId}`,
20
+ secret: input.secret,
21
+ headers: input.headers,
22
+ body: input.body,
23
+ schema: AuthWebhook.check(Schema.makeFilter((payload) => payload.data.projectId === input.projectId, { expected: "the configured auth project" })),
24
+ handle: (webhook) => {
25
+ if (webhook.event === "user.deletion_requested")
26
+ return Schema.decodeUnknownEffect(AccountDeletionWebhook)(webhook).pipe(Effect.mapError(() => new WebhookVerificationError({ reason: "payload" })), Effect.flatMap(({ data }) => input.onDeleteUser(data)));
27
+ if (webhook.event === "organization.deletion_requested")
28
+ return Schema.decodeUnknownEffect(OrganizationDeletionWebhook)(webhook).pipe(Effect.mapError(() => new WebhookVerificationError({ reason: "payload" })), Effect.flatMap(({ data }) => input.onDeleteOrganization(data)));
29
+ return input.onWebhook
30
+ ? input.onWebhook(webhook)
31
+ : Effect.fail(new UnsupportedAuthWebhook({}));
32
+ },
33
+ });
34
+ });
35
+ export const receiveAccountDeletion = (input) => receiveAuthWebhook({
36
+ ...input,
37
+ onDeleteUser: input.handle,
38
+ onDeleteOrganization: () => Effect.fail(new UnsupportedAuthWebhook({})),
39
+ });