@krak-stack/auth 0.1.59 → 0.1.60

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.
package/dist/access.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Context, Effect, Schema } from "effect";
2
2
  export declare const ApiKeyPermissionGrant: Schema.$Record<Schema.String, Schema.$Array<Schema.String>>;
3
3
  export type ApiKeyPermissionGrant = typeof ApiKeyPermissionGrant.Type;
4
- export type UserPrincipal = {
4
+ export type UserActor = {
5
5
  readonly type: "user";
6
6
  readonly userId: string;
7
7
  readonly organizationId: string | null;
@@ -19,29 +19,30 @@ export type ApiKeyOwner = {
19
19
  readonly type: "service";
20
20
  readonly serviceId: string;
21
21
  };
22
- export type ApiKeyPrincipal = {
22
+ export type ApiKeyActor = {
23
23
  readonly type: "apiKey";
24
24
  readonly apiKeyId: string;
25
25
  readonly owner: ApiKeyOwner;
26
26
  };
27
- export type Principal = UserPrincipal | ApiKeyPrincipal;
28
- export type CurrentPrincipal = {
29
- readonly principal: Principal;
27
+ export type Actor = UserActor | ApiKeyActor;
28
+ export type CurrentActor = {
29
+ readonly actor: Actor;
30
30
  readonly organizationId: string | null;
31
31
  readonly permissions: ReadonlySet<string>;
32
32
  };
33
- export declare const CurrentPrincipal: Context.Service<CurrentPrincipal, CurrentPrincipal>;
33
+ export declare const CurrentActor: Context.Service<CurrentActor, CurrentActor>;
34
34
  declare const Forbidden_base: Schema.Class<Forbidden, Schema.Struct<{
35
35
  readonly _tag: Schema.tag<"Forbidden">;
36
36
  }>, import("effect/Cause").YieldableError>;
37
37
  export declare class Forbidden extends Forbidden_base {
38
38
  }
39
- export type Policy<E = never, R = never> = Effect.Effect<void, Forbidden | E, CurrentPrincipal | R>;
40
- export declare const policy: <E, R>(predicate: (principal: CurrentPrincipal) => Effect.Effect<boolean, E, R>) => Policy<E, R>;
39
+ export type Policy<E = never, R = never> = Effect.Effect<void, Forbidden | E, CurrentActor | R>;
40
+ export declare const policy: <E, R>(predicate: (actor: CurrentActor) => Effect.Effect<boolean, E, R>) => Policy<E, R>;
41
41
  export declare const permission: (requiredPermission: string) => Policy;
42
+ export declare const actorUserId: Effect.Effect<string, Forbidden, CurrentActor>;
42
43
  export declare const all: <E, R>(...policies: readonly [Policy<E, R>, ...Array<Policy<E, R>>]) => Policy<E, R>;
43
44
  export declare const any: <E, R>(...policies: readonly [Policy<E, R>, ...Array<Policy<E, R>>]) => Policy<E, R>;
44
- export declare const withPolicy: <E, R>(accessPolicy: Policy<E, R>) => <A, E2, R2>(self: Effect.Effect<A, E2, R2>) => Effect.Effect<A, E | E2 | Forbidden, R | R2 | CurrentPrincipal>;
45
+ export declare const withPolicy: <E, R>(accessPolicy: Effect.Effect<void, E, R>) => <A, E2, R2>(self: Effect.Effect<A, E2, R2>) => Effect.Effect<A, E | E2, R | R2>;
45
46
  type ProjectPermission<Project extends string, Action extends string> = `${Project}:${Action}`;
46
47
  export type ProjectAccessDefinition<Project extends string = string, Action extends string = string> = {
47
48
  readonly project: Project;
@@ -50,44 +51,48 @@ export type ProjectAccessDefinition<Project extends string = string, Action exte
50
51
  readonly apiKeys: {
51
52
  readonly user: ReadonlyArray<Action>;
52
53
  readonly organization: ReadonlyArray<Action>;
54
+ readonly service: ReadonlyArray<Action>;
53
55
  };
54
56
  readonly qualify: (action: Action) => ProjectPermission<Project, Action>;
55
57
  readonly permission: (action: Action) => Policy;
56
58
  readonly permissionsForRoles: (roles: unknown) => ReadonlySet<ProjectPermission<Project, Action>>;
57
- readonly permissionsForGrant: (grant: ApiKeyPermissionGrant) => ReadonlySet<ProjectPermission<Project, Action>>;
59
+ readonly permissionsForGrant: (grant: ApiKeyPermissionGrant | null | undefined) => ReadonlySet<ProjectPermission<Project, Action>>;
58
60
  readonly permissionsForUserKey: (input: {
59
- readonly grant: ApiKeyPermissionGrant;
61
+ readonly grant: ApiKeyPermissionGrant | null | undefined;
60
62
  readonly roles: unknown;
61
63
  }) => ReadonlySet<ProjectPermission<Project, Action>>;
62
64
  readonly decodeGrant: (input: unknown) => Effect.Effect<ReadonlySet<ProjectPermission<Project, Action>>, Schema.SchemaError>;
63
65
  readonly encodeGrant: (actions: ReadonlyArray<Action>) => ApiKeyPermissionGrant;
64
66
  readonly userApiKeyPermissions: ApiKeyPermissionGrant;
65
67
  readonly organizationApiKeyPermissions: ApiKeyPermissionGrant;
66
- readonly principalForUser: (input: {
68
+ readonly serviceApiKeyPermissions: ApiKeyPermissionGrant;
69
+ readonly actorForUser: (input: {
67
70
  readonly userId: string;
68
71
  readonly organizationId: string | null;
69
72
  readonly roles: unknown;
70
- }) => CurrentPrincipal;
71
- readonly principalForApiKey: (input: {
73
+ }) => CurrentActor;
74
+ readonly actorForApiKey: (input: {
72
75
  readonly apiKeyId: string;
73
76
  readonly owner: ApiKeyOwner;
74
- readonly grant: ApiKeyPermissionGrant;
75
- }) => CurrentPrincipal;
77
+ readonly grant: ApiKeyPermissionGrant | null | undefined;
78
+ }) => CurrentActor;
76
79
  };
77
80
  export type ProjectAccessCatalog = {
78
81
  readonly project: string;
79
82
  readonly roles: Readonly<Record<string, ReadonlyArray<string> | undefined>>;
80
83
  readonly userApiKeyPermissions: ApiKeyPermissionGrant;
81
84
  readonly organizationApiKeyPermissions: ApiKeyPermissionGrant;
85
+ readonly serviceApiKeyPermissions: ApiKeyPermissionGrant;
82
86
  };
83
- export type ProjectAccessConfig<Project extends string, Action extends string> = {
87
+ export type ProjectAccessConfig<Project extends string, Permissions extends ReadonlyArray<string>> = {
84
88
  readonly project: Project;
85
- readonly permissions: ReadonlyArray<Action>;
86
- readonly roles: Readonly<Record<string, ReadonlyArray<Action> | undefined>>;
89
+ readonly permissions: Permissions;
90
+ readonly roles: Readonly<Record<string, ReadonlyArray<Permissions[number]> | undefined>>;
87
91
  readonly apiKeys?: {
88
- readonly user?: ReadonlyArray<Action>;
89
- readonly organization?: ReadonlyArray<Action>;
92
+ readonly user?: ReadonlyArray<Permissions[number]>;
93
+ readonly organization?: ReadonlyArray<Permissions[number]>;
94
+ readonly service?: ReadonlyArray<Permissions[number]>;
90
95
  };
91
96
  };
92
- export declare const defineProjectAccess: <const Project extends string, const Action extends string>(config: ProjectAccessConfig<Project, Action>) => ProjectAccessDefinition<Project, Action>;
97
+ export declare const defineProjectAccess: <const Project extends string, const Permissions extends ReadonlyArray<string>>(config: ProjectAccessConfig<Project, Permissions>) => ProjectAccessDefinition<Project, Permissions[number]>;
93
98
  export {};
package/dist/access.js CHANGED
@@ -5,18 +5,25 @@ export const ApiKeyPermissionGrant = Schema.Record(Schema.String, Schema.Array(S
5
5
  title: "API key permission grant",
6
6
  description: "Better Auth resource and action permissions assigned to a key.",
7
7
  });
8
- export const CurrentPrincipal = Context.Service("@krak-stack/auth/CurrentPrincipal");
8
+ export const CurrentActor = Context.Service("@krak-stack/auth/CurrentActor");
9
9
  export class Forbidden extends Schema.ErrorClass("Forbidden")({
10
10
  _tag: Schema.tag("Forbidden"),
11
11
  }, {
12
12
  identifier: "Forbidden",
13
13
  title: "Forbidden",
14
- description: "The authenticated principal lacks a required permission.",
14
+ description: "The authenticated actor lacks a required permission.",
15
15
  httpApiStatus: 403,
16
16
  }) {
17
17
  }
18
- export const policy = (predicate) => Effect.flatMap(CurrentPrincipal, (principal) => Effect.flatMap(predicate(principal), (allowed) => allowed ? Effect.void : Effect.fail(new Forbidden())));
19
- export const permission = (requiredPermission) => policy((principal) => Effect.succeed(principal.permissions.has(requiredPermission)));
18
+ export const policy = (predicate) => Effect.flatMap(CurrentActor, (actor) => Effect.flatMap(predicate(actor), (allowed) => allowed ? Effect.void : Effect.fail(new Forbidden())));
19
+ export const permission = (requiredPermission) => policy((actor) => Effect.succeed(actor.permissions.has(requiredPermission)));
20
+ export const actorUserId = CurrentActor.pipe(Effect.flatMap(({ actor }) => {
21
+ if (actor.type === "user")
22
+ return Effect.succeed(actor.userId);
23
+ if (actor.owner.type === "user")
24
+ return Effect.succeed(actor.owner.userId);
25
+ return Effect.fail(new Forbidden());
26
+ }));
20
27
  export const all = (...policies) => Effect.all(policies, { concurrency: 1, discard: true });
21
28
  export const any = (...policies) => Effect.firstSuccessOf(policies);
22
29
  export const withPolicy = (accessPolicy) => (self) => Effect.andThen(accessPolicy, self);
@@ -31,24 +38,27 @@ export const defineProjectAccess = (config) => {
31
38
  const permissionsForRoles = (input) => {
32
39
  const actions = new Set();
33
40
  for (const role of roleList(input)) {
34
- for (const action of config.roles[role] ?? [])
35
- actions.add(action);
41
+ for (const action of config.roles[role] ?? []) {
42
+ if (allowedActions.has(action))
43
+ actions.add(action);
44
+ }
36
45
  }
37
46
  return permissionsForActions(actions);
38
47
  };
39
48
  const permissionsForGrant = (grant) => {
40
- const actions = (grant[config.project] ?? []).filter((action) => allowedActions.has(action));
49
+ const actions = (grant?.[config.project] ?? []).filter((action) => allowedActions.has(action));
41
50
  return permissionsForActions(actions);
42
51
  };
43
52
  const encodeGrant = (actions) => ({
44
53
  [config.project]: actions.filter((action) => allowedActions.has(action)),
45
54
  });
46
- const userApiKeyActions = config.apiKeys?.user ?? [];
47
- const organizationApiKeyActions = config.apiKeys?.organization ?? [];
48
- const principalForUser = (input) => {
55
+ const userApiKeyActions = (config.apiKeys?.user ?? []).filter((action) => allowedActions.has(action));
56
+ const organizationApiKeyActions = (config.apiKeys?.organization ?? []).filter((action) => allowedActions.has(action));
57
+ const serviceApiKeyActions = (config.apiKeys?.service ?? []).filter((action) => allowedActions.has(action));
58
+ const actorForUser = (input) => {
49
59
  const roles = roleList(input.roles);
50
60
  return {
51
- principal: {
61
+ actor: {
52
62
  type: "user",
53
63
  userId: input.userId,
54
64
  organizationId: input.organizationId,
@@ -58,7 +68,7 @@ export const defineProjectAccess = (config) => {
58
68
  permissions: permissionsForRoles(roles),
59
69
  };
60
70
  };
61
- const principalForApiKey = (input) => {
71
+ const actorForApiKey = (input) => {
62
72
  const keyPermissions = permissionsForGrant(input.grant);
63
73
  const permissions = (() => {
64
74
  switch (input.owner.type) {
@@ -67,12 +77,12 @@ export const defineProjectAccess = (config) => {
67
77
  case "organization":
68
78
  return intersection(permissionsForActions(organizationApiKeyActions), keyPermissions);
69
79
  case "service":
70
- return keyPermissions;
80
+ return intersection(permissionsForActions(serviceApiKeyActions), keyPermissions);
71
81
  }
72
82
  })();
73
83
  const organizationId = input.owner.type === "service" ? null : input.owner.organizationId;
74
84
  return {
75
- principal: {
85
+ actor: {
76
86
  type: "apiKey",
77
87
  apiKeyId: input.apiKeyId,
78
88
  owner: input.owner,
@@ -88,17 +98,19 @@ export const defineProjectAccess = (config) => {
88
98
  apiKeys: {
89
99
  user: userApiKeyActions,
90
100
  organization: organizationApiKeyActions,
101
+ service: serviceApiKeyActions,
91
102
  },
92
103
  qualify,
93
104
  permission: (action) => permission(qualify(action)),
94
105
  permissionsForRoles,
95
106
  permissionsForGrant,
96
- permissionsForUserKey: ({ grant, roles }) => intersection(permissionsForRoles(roles), permissionsForGrant(grant)),
107
+ permissionsForUserKey: ({ grant, roles }) => intersection(intersection(permissionsForRoles(roles), permissionsForActions(userApiKeyActions)), permissionsForGrant(grant)),
97
108
  decodeGrant: (input) => Schema.decodeUnknownEffect(ApiKeyPermissionGrant)(input).pipe(Effect.map(permissionsForGrant)),
98
109
  encodeGrant,
99
110
  userApiKeyPermissions: encodeGrant(userApiKeyActions),
100
111
  organizationApiKeyPermissions: encodeGrant(organizationApiKeyActions),
101
- principalForUser,
102
- principalForApiKey,
112
+ serviceApiKeyPermissions: encodeGrant(serviceApiKeyActions),
113
+ actorForUser,
114
+ actorForApiKey,
103
115
  };
104
116
  };
package/dist/api.d.ts CHANGED
@@ -141,11 +141,14 @@ export declare const AuthServiceApi: HttpApi.HttpApi<"AuthServiceApi", import("e
141
141
  readonly newPassword: import("effect/Schema").NonEmptyString;
142
142
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
143
143
  readonly ok: import("effect/Schema").Boolean;
144
- }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKeyPermissions", "PATCH", "/api/auth/api-key/:keyId/permissions", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
144
+ }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKey", "PATCH", "/api/auth/api-key/:keyId", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
145
145
  readonly keyId: import("effect/Schema").NonEmptyString;
146
146
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
147
147
  readonly configId: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>;
148
- readonly permissions: import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>;
148
+ readonly name: import("effect/Schema").NonEmptyString;
149
+ readonly enabled: import("effect/Schema").Boolean;
150
+ readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
151
+ readonly referrers: import("effect/Schema").optional<import("effect/Schema").$Array<import("effect/Schema").String>>;
149
152
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
150
153
  readonly ok: import("effect/Schema").Boolean;
151
154
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"uploadUserImage", "POST", "/api/auth/image/upload", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/unstable/httpapi/HttpApiSchema").asMultipartStream<import("effect/Schema").Struct<{
@@ -155,7 +158,6 @@ export declare const AuthServiceApi: HttpApi.HttpApi<"AuthServiceApi", import("e
155
158
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"verifyApiKey", "POST", "/api/auth/verify-api-key", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
156
159
  readonly key: import("effect/Schema").NonEmptyString;
157
160
  readonly configId: import("effect/Schema").optional<import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>>;
158
- readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
159
161
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
160
162
  readonly valid: import("effect/Schema").Boolean;
161
163
  readonly error: import("effect/Schema").NullOr<import("effect/Schema").Struct<{
@@ -1044,11 +1046,14 @@ export declare const AuthClientApi: HttpApi.HttpApi<"AuthClientApi", import("eff
1044
1046
  readonly newPassword: import("effect/Schema").NonEmptyString;
1045
1047
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
1046
1048
  readonly ok: import("effect/Schema").Boolean;
1047
- }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKeyPermissions", "PATCH", "/api/auth/api-key/:keyId/permissions", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
1049
+ }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKey", "PATCH", "/api/auth/api-key/:keyId", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
1048
1050
  readonly keyId: import("effect/Schema").NonEmptyString;
1049
1051
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
1050
1052
  readonly configId: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>;
1051
- readonly permissions: import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>;
1053
+ readonly name: import("effect/Schema").NonEmptyString;
1054
+ readonly enabled: import("effect/Schema").Boolean;
1055
+ readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
1056
+ readonly referrers: import("effect/Schema").optional<import("effect/Schema").$Array<import("effect/Schema").String>>;
1052
1057
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
1053
1058
  readonly ok: import("effect/Schema").Boolean;
1054
1059
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"uploadUserImage", "POST", "/api/auth/image/upload", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/unstable/httpapi/HttpApiSchema").asMultipartStream<import("effect/Schema").Struct<{
@@ -1058,7 +1063,6 @@ export declare const AuthClientApi: HttpApi.HttpApi<"AuthClientApi", import("eff
1058
1063
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("./extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"verifyApiKey", "POST", "/api/auth/verify-api-key", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
1059
1064
  readonly key: import("effect/Schema").NonEmptyString;
1060
1065
  readonly configId: import("effect/Schema").optional<import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>>;
1061
- readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
1062
1066
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
1063
1067
  readonly valid: import("effect/Schema").Boolean;
1064
1068
  readonly error: import("effect/Schema").NullOr<import("effect/Schema").Struct<{
@@ -1,5 +1,4 @@
1
1
  import type { ApiKey } from "@better-auth/api-key/client";
2
- import type { AuthUiClient } from "./auth-client";
3
2
  type ApiKeySummary = Omit<ApiKey, "key">;
4
3
  export type ApiKeyEditMessages = {
5
4
  enabled: string;
@@ -8,13 +7,15 @@ export type ApiKeyEditMessages = {
8
7
  referrersDescription: string;
9
8
  referrersError: string;
10
9
  referrersPlaceholder: string;
10
+ permissions: string;
11
+ permissionsDescription: string;
11
12
  updateError: string;
12
13
  };
13
- export declare const ApiKeyEditForm: ({ authClient, configId, keyData, messages, onSaved, }: {
14
- authClient: AuthUiClient;
14
+ export declare const ApiKeyEditForm: ({ configId, keyData, messages, permissions, onSaved, }: {
15
15
  configId: "organization" | "user";
16
16
  keyData: ApiKeySummary;
17
17
  messages: ApiKeyEditMessages;
18
+ permissions: Readonly<Record<string, ReadonlyArray<string>>>;
18
19
  onSaved: () => void;
19
20
  }) => import("react").JSX.Element;
20
21
  export {};
@@ -2,15 +2,36 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
4
  import { Effect, Schema } from "effect";
5
- import { useState } from "react";
5
+ import { useRef, useState } from "react";
6
6
  import { CheckboxField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@/components/ui/effect-form";
7
- import { parseApiKeyReferrers } from "./api-key";
8
- import { apiKeyReferrers, withApiKeyReferrers } from "./api-key-referrers";
7
+ import { Checkbox } from "@/components/ui/checkbox";
8
+ import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel, FieldLegend, FieldSet, } from "@/components/ui/field";
9
+ import { parseApiKeyReferrers, updateApiKey } from "./api-key";
10
+ import { apiKeyReferrers } from "./api-key-referrers";
11
+ import { ExtraApiKeyPermissions } from "../extra/schema";
9
12
  const editApiKeyFormBuilder = FormBuilder.empty
10
13
  .addField("name", Schema.NonEmptyString)
11
14
  .addField("enabled", Schema.Boolean)
12
15
  .addField("referrers", Schema.String);
13
- export const ApiKeyEditForm = ({ authClient, configId, keyData, messages, onSaved, }) => {
16
+ export const ApiKeyEditForm = ({ configId, keyData, messages, permissions, onSaved, }) => {
17
+ const permissionOptions = Object.entries(permissions).flatMap(([project, actions]) => actions.map((action) => ({
18
+ id: `${project}:${action}`,
19
+ project,
20
+ action,
21
+ })));
22
+ const currentPermissions = Schema.decodeUnknownOption(ExtraApiKeyPermissions)(keyData.permissions ?? {});
23
+ const currentGrant = currentPermissions._tag === "Some" ? currentPermissions.value : {};
24
+ const initialSelectedPermissions = Object.fromEntries(permissionOptions.map((option) => [
25
+ option.id,
26
+ currentGrant[option.project]?.includes(option.action) ?? false,
27
+ ]));
28
+ const [selectedPermissions, setSelectedPermissions] = useState(initialSelectedPermissions);
29
+ const selectedPermissionsRef = useRef(selectedPermissions);
30
+ const permissionOptionsRef = useRef(permissionOptions);
31
+ const permissionsRef = useRef(permissions);
32
+ selectedPermissionsRef.current = selectedPermissions;
33
+ permissionOptionsRef.current = permissionOptions;
34
+ permissionsRef.current = permissions;
14
35
  const [form] = useState(() => FormReact.make(editApiKeyFormBuilder, {
15
36
  fields: {
16
37
  name: TextField,
@@ -21,16 +42,26 @@ export const ApiKeyEditForm = ({ authClient, configId, keyData, messages, onSave
21
42
  onSubmit: (_, { decoded }) => Effect.tryPromise({
22
43
  try: async () => {
23
44
  const referrers = parseApiKeyReferrers(decoded.referrers, messages.referrersError);
24
- const result = await authClient.apiKey.update({
45
+ const selectedGrant = {};
46
+ for (const project of Object.keys(permissionsRef.current)) {
47
+ selectedGrant[project] = [];
48
+ }
49
+ for (const option of permissionOptionsRef.current) {
50
+ if (!selectedPermissionsRef.current[option.id])
51
+ continue;
52
+ selectedGrant[option.project] = [
53
+ ...(selectedGrant[option.project] ?? []),
54
+ option.action,
55
+ ];
56
+ }
57
+ await updateApiKey({
25
58
  configId,
26
59
  keyId: keyData.id,
27
60
  name: decoded.name.trim(),
28
61
  enabled: decoded.enabled,
29
- metadata: withApiKeyReferrers(keyData.metadata, referrers),
30
- });
31
- if (result.error) {
32
- throw new Error(result.error.message ?? messages.updateError);
33
- }
62
+ permissions: selectedGrant,
63
+ referrers,
64
+ }, messages.updateError);
34
65
  onSaved();
35
66
  },
36
67
  catch: (cause) => cause instanceof Error ? cause : new Error(messages.updateError),
@@ -46,5 +77,8 @@ export const ApiKeyEditForm = ({ authClient, configId, keyData, messages, onSave
46
77
  event.preventDefault();
47
78
  event.stopPropagation();
48
79
  submit();
49
- }, children: [_jsx(form.name, { label: messages.name, required: true }), _jsx(form.enabled, { label: messages.enabled }), _jsx(form.referrers, { label: messages.referrers, description: messages.referrersDescription, placeholder: messages.referrersPlaceholder, rows: 3 }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
80
+ }, children: [_jsx(form.name, { label: messages.name, required: true }), _jsx(form.enabled, { label: messages.enabled }), _jsx(form.referrers, { label: messages.referrers, description: messages.referrersDescription, placeholder: messages.referrersPlaceholder, rows: 3 }), permissionOptions.length > 0 ? (_jsxs(FieldSet, { children: [_jsx(FieldLegend, { children: messages.permissions }), _jsx(FieldDescription, { children: messages.permissionsDescription }), _jsx(FieldGroup, { "data-slot": "checkbox-group", className: "gap-3", children: permissionOptions.map((permission) => (_jsxs(Field, { orientation: "horizontal", children: [_jsx(Checkbox, { id: `edit-${permission.id}`, checked: selectedPermissions[permission.id] ?? false, onCheckedChange: (checked) => setSelectedPermissions((current) => ({
81
+ ...current,
82
+ [permission.id]: checked,
83
+ })) }), _jsx(FieldContent, { children: _jsx(FieldLabel, { htmlFor: `edit-${permission.id}`, children: permission.id }) })] }, permission.id))) })] })) : null, _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) }) }));
50
84
  };
@@ -1,5 +1,10 @@
1
- import { ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse } from "../extra/schema";
1
+ import { Schema } from "effect";
2
+ import { ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraUpdateApiKeyPayload } from "../extra/schema";
2
3
  export type CreateApiKeyPayload = typeof ExtraCreateApiKeyPayload.Type;
3
4
  export type CreatedApiKey = typeof ExtraCreateApiKeyResponse.Type;
5
+ export type UpdateApiKeyPayload = typeof ExtraUpdateApiKeyPayload.Type;
4
6
  export declare const parseApiKeyReferrers: (value: string, errorMessage: string) => string[];
5
7
  export declare const createApiKey: (payload: CreateApiKeyPayload, fallbackError: string) => Promise<CreatedApiKey>;
8
+ export declare const updateApiKey: (payload: UpdateApiKeyPayload, fallbackError: string) => Promise<Schema.Struct.ReadonlySide<{
9
+ readonly ok: Schema.Boolean;
10
+ }, "Type">>;
@@ -1,5 +1,5 @@
1
1
  import { Option, Schema } from "effect";
2
- import { ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, } from "../extra/schema";
2
+ import { ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraOkResponse, ExtraUpdateApiKeyPayload, } from "../extra/schema";
3
3
  const decodeUrl = Schema.decodeUnknownOption(Schema.URLFromString);
4
4
  export const parseApiKeyReferrers = (value, errorMessage) => {
5
5
  const referrers = value
@@ -37,3 +37,23 @@ export const createApiKey = async (payload, fallbackError) => {
37
37
  }
38
38
  return await Schema.decodeUnknownPromise(ExtraCreateApiKeyResponse)(data);
39
39
  };
40
+ export const updateApiKey = async (payload, fallbackError) => {
41
+ const decoded = await Schema.decodeUnknownPromise(ExtraUpdateApiKeyPayload)(payload);
42
+ const response = await fetch(`/api/auth/api-key/${encodeURIComponent(decoded.keyId)}`, {
43
+ method: "PATCH",
44
+ credentials: "include",
45
+ headers: { "Content-Type": "application/json" },
46
+ body: JSON.stringify({
47
+ configId: decoded.configId,
48
+ name: decoded.name,
49
+ enabled: decoded.enabled,
50
+ permissions: decoded.permissions,
51
+ referrers: decoded.referrers,
52
+ }),
53
+ });
54
+ const data = await response.json().catch(() => null);
55
+ if (!response.ok) {
56
+ throw new Error(await errorMessage(data, fallbackError));
57
+ }
58
+ return await Schema.decodeUnknownPromise(ExtraOkResponse)(data);
59
+ };
@@ -524,11 +524,14 @@ export declare const authClientApi: (baseUrl?: string | undefined) => AtomHttpAp
524
524
  readonly newPassword: import("effect/Schema").NonEmptyString;
525
525
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
526
526
  readonly ok: import("effect/Schema").Boolean;
527
- }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("../extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKeyPermissions", "PATCH", "/api/auth/api-key/:keyId/permissions", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
527
+ }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("../extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"updateApiKey", "PATCH", "/api/auth/api-key/:keyId", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
528
528
  readonly keyId: import("effect/Schema").NonEmptyString;
529
529
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
530
530
  readonly configId: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>;
531
- readonly permissions: import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>;
531
+ readonly name: import("effect/Schema").NonEmptyString;
532
+ readonly enabled: import("effect/Schema").Boolean;
533
+ readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
534
+ readonly referrers: import("effect/Schema").optional<import("effect/Schema").$Array<import("effect/Schema").String>>;
532
535
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
533
536
  readonly ok: import("effect/Schema").Boolean;
534
537
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("../extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"uploadUserImage", "POST", "/api/auth/image/upload", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/unstable/httpapi/HttpApiSchema").asMultipartStream<import("effect/Schema").Struct<{
@@ -538,7 +541,6 @@ export declare const authClientApi: (baseUrl?: string | undefined) => AtomHttpAp
538
541
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").Forbidden | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError | typeof import("../extra/schema").ExtraBadRequest>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"verifyApiKey", "POST", "/api/auth/verify-api-key", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
539
542
  readonly key: import("effect/Schema").NonEmptyString;
540
543
  readonly configId: import("effect/Schema").optional<import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>>;
541
- readonly permissions: import("effect/Schema").optional<import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>>;
542
544
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
543
545
  readonly valid: import("effect/Schema").Boolean;
544
546
  readonly error: import("effect/Schema").NullOr<import("effect/Schema").Struct<{
@@ -0,0 +1,6 @@
1
+ import type { ReactNode } from "react";
2
+ export declare const useHasPermission: (permission: string) => boolean;
3
+ export declare const HasPermission: ({ children, permission, }: {
4
+ children: ReactNode;
5
+ permission: string;
6
+ }) => import("react").JSX.Element | null;
@@ -0,0 +1,4 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { usePermissions } from "./auth-provider";
3
+ export const useHasPermission = (permission) => usePermissions().can(permission);
4
+ export const HasPermission = ({ children, permission, }) => (useHasPermission(permission) ? _jsx(_Fragment, { children: children }) : null);
@@ -2,14 +2,15 @@ export { KrakstackAuthProvider, useAuthClient, useKrakstackAuth, useKrakstackAut
2
2
  export { createAuthUiClient } from "./auth-client";
3
3
  export { OrganizationSwitcher } from "./organization-switcher";
4
4
  export { MemberRequired } from "./member-required";
5
+ export { HasPermission, useHasPermission } from "./has-permission";
5
6
  export { ResetPassword, Signin, Signup, TwoFactor, VerifyEmail, } from "./auth-forms";
6
7
  export { UserButton } from "./user-button";
7
8
  export { AdminOrganizationsTable } from "./admin-organizations";
8
9
  export { AdminOrganizationForm } from "./admin-organization-form";
9
10
  export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";
10
11
  export { assetUrl } from "./utils";
11
- export { ApiKeyPermissionGrant, CurrentPrincipal, Forbidden, all, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
12
- export type { ApiKeyOwner, ApiKeyPrincipal, Policy, Principal, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessDefinition, UserPrincipal, } from "../access";
12
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
13
+ export type { ApiKeyOwner, ApiKeyActor, Actor, Policy, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessDefinition, UserActor, } from "../access";
13
14
  export type { KrakstackAuthContextValue, KrakstackAuthLocale, KrakstackAuthProviderProps, } from "./auth-provider";
14
15
  export type { OrganizationSwitcherDialog, OrganizationSwitcherFeatures, OrganizationSwitcherProps, } from "./organization-switcher";
15
16
  export type { UserButtonDialog } from "./user-button";
@@ -2,10 +2,11 @@ export { KrakstackAuthProvider, useAuthClient, useKrakstackAuth, useKrakstackAut
2
2
  export { createAuthUiClient } from "./auth-client";
3
3
  export { OrganizationSwitcher } from "./organization-switcher";
4
4
  export { MemberRequired } from "./member-required";
5
+ export { HasPermission, useHasPermission } from "./has-permission";
5
6
  export { ResetPassword, Signin, Signup, TwoFactor, VerifyEmail, } from "./auth-forms";
6
7
  export { UserButton } from "./user-button";
7
8
  export { AdminOrganizationsTable } from "./admin-organizations";
8
9
  export { AdminOrganizationForm } from "./admin-organization-form";
9
10
  export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";
10
11
  export { assetUrl } from "./utils";
11
- export { ApiKeyPermissionGrant, CurrentPrincipal, Forbidden, all, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
12
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
@@ -106,7 +106,7 @@ declare const messages: {
106
106
  readonly user_api_key_created_title: "API key created";
107
107
  readonly user_api_key_delete_error: "Could not delete the API key.";
108
108
  readonly user_api_key_disabled: "Disabled";
109
- readonly user_api_key_edit_description: "Update the key name, status, and allowed referrers.";
109
+ readonly user_api_key_edit_description: "Update the key name, status, allowed referrers, and permissions.";
110
110
  readonly user_api_key_edit_title: "Edit API key";
111
111
  readonly user_api_key_enabled: "Enabled";
112
112
  readonly user_api_key_hidden: "Secret hidden";
@@ -242,7 +242,7 @@ declare const messages: {
242
242
  readonly user_api_key_created_title: "Clé API créée";
243
243
  readonly user_api_key_delete_error: "Impossible de supprimer la clé API.";
244
244
  readonly user_api_key_disabled: "Désactivée";
245
- readonly user_api_key_edit_description: "Mettez à jour le nom, le statut et les référents autorisés de la clé.";
245
+ readonly user_api_key_edit_description: "Mettez à jour le nom, le statut, les référents autorisés et les autorisations de la clé.";
246
246
  readonly user_api_key_edit_title: "Modifier la clé API";
247
247
  readonly user_api_key_enabled: "Activée";
248
248
  readonly user_api_key_hidden: "Secret masqué";
@@ -22,7 +22,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem,
22
22
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
23
23
  import { Separator } from "@/components/ui/separator";
24
24
  import { OrganizationEmail, OrganizationAddress, OrganizationMetadata, OrganizationPhone, OrganizationSocial, OrganizationTranslation, OrganizationWebsite, decodeOrganizationMetadata, } from "@krak-stack/auth/schema";
25
- import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, } from "../roles";
25
+ import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles";
26
26
  import { authClientApi } from "./auth-client-api";
27
27
  import { useKrakstackAuth } from "./auth-provider";
28
28
  import { createApiKey, parseApiKeyReferrers } from "./api-key";
@@ -138,7 +138,7 @@ const messages = {
138
138
  user_api_key_created_title: "API key created",
139
139
  user_api_key_delete_error: "Could not delete the API key.",
140
140
  user_api_key_disabled: "Disabled",
141
- user_api_key_edit_description: "Update the key name, status, and allowed referrers.",
141
+ user_api_key_edit_description: "Update the key name, status, allowed referrers, and permissions.",
142
142
  user_api_key_edit_title: "Edit API key",
143
143
  user_api_key_enabled: "Enabled",
144
144
  user_api_key_hidden: "Secret hidden",
@@ -274,7 +274,7 @@ const messages = {
274
274
  user_api_key_created_title: "Clé API créée",
275
275
  user_api_key_delete_error: "Impossible de supprimer la clé API.",
276
276
  user_api_key_disabled: "Désactivée",
277
- user_api_key_edit_description: "Mettez à jour le nom, le statut et les référents autorisés de la clé.",
277
+ user_api_key_edit_description: "Mettez à jour le nom, le statut, les référents autorisés et les autorisations de la clé.",
278
278
  user_api_key_edit_title: "Modifier la clé API",
279
279
  user_api_key_enabled: "Activée",
280
280
  user_api_key_hidden: "Secret masqué",
@@ -847,8 +847,8 @@ export function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl,
847
847
  onSuccess: () => null,
848
848
  });
849
849
  const loadingUserInvitations = invitationsResult._tag === "Initial";
850
- const activeMemberRole = normalizeOrganizationRole(activeOrganization.data?.members.find((member) => member.userId === session.data?.user.id)?.role);
851
- const canManageApiKeys = activeMemberRole === "owner" || activeMemberRole === "admin";
850
+ const activeMemberRoles = parseRoleList(activeOrganization.data?.members.find((member) => member.userId === session.data?.user.id)?.role);
851
+ const canManageApiKeys = activeMemberRoles.some((role) => role === "owner" || role === "admin");
852
852
  const canUpdateOrganization = canManageApiKeys;
853
853
  const canSwitchOrganizations = features?.organizationSwitching ?? true;
854
854
  const canCreateOrganization = features?.organizationCreation ?? true;
@@ -1603,13 +1603,15 @@ function OrganizationApiKeyManager({ authClient, organization, active, permissio
1603
1603
  }, searchState: "local", state: {
1604
1604
  empty: loading ? m.user_loading() : m.table_empty(),
1605
1605
  loading,
1606
- } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { authClient: authClient, configId: "organization", keyData: editingKey, messages: {
1606
+ } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { configId: "organization", keyData: editingKey, permissions: permissions, messages: {
1607
1607
  enabled: m.user_api_key_enabled(),
1608
1608
  name: m.user_api_key_name(),
1609
1609
  referrers: m.user_api_key_referrers(),
1610
1610
  referrersDescription: m.user_api_key_referrers_description(),
1611
1611
  referrersError: m.user_api_key_referrers_error(),
1612
1612
  referrersPlaceholder: m.user_api_key_referrers_placeholder(),
1613
+ permissions: m.user_api_key_permissions(),
1614
+ permissionsDescription: m.user_api_key_permissions_description(),
1613
1615
  updateError: m.user_api_key_update_error(),
1614
1616
  }, onSaved: () => {
1615
1617
  refreshKeys();
@@ -42,7 +42,7 @@ declare const messages: {
42
42
  readonly user_api_key_created_title: "API key created";
43
43
  readonly user_api_key_delete_error: "Could not delete the API key.";
44
44
  readonly user_api_key_disabled: "Disabled";
45
- readonly user_api_key_edit_description: "Update the key name, status, and allowed referrers.";
45
+ readonly user_api_key_edit_description: "Update the key name, status, allowed referrers, and permissions.";
46
46
  readonly user_api_key_edit_title: "Edit API key";
47
47
  readonly user_api_key_enabled: "Enabled";
48
48
  readonly user_api_key_hidden: "Secret hidden";
@@ -149,7 +149,7 @@ declare const messages: {
149
149
  readonly user_api_key_created_title: "Clé API créée";
150
150
  readonly user_api_key_delete_error: "Impossible de supprimer la clé API.";
151
151
  readonly user_api_key_disabled: "Désactivée";
152
- readonly user_api_key_edit_description: "Mettez à jour le nom, le statut et les référents autorisés de la clé.";
152
+ readonly user_api_key_edit_description: "Mettez à jour le nom, le statut, les référents autorisés et les autorisations de la clé.";
153
153
  readonly user_api_key_edit_title: "Modifier la clé API";
154
154
  readonly user_api_key_enabled: "Activée";
155
155
  readonly user_api_key_hidden: "Secret masqué";
@@ -71,7 +71,7 @@ const messages = {
71
71
  user_api_key_created_title: "API key created",
72
72
  user_api_key_delete_error: "Could not delete the API key.",
73
73
  user_api_key_disabled: "Disabled",
74
- user_api_key_edit_description: "Update the key name, status, and allowed referrers.",
74
+ user_api_key_edit_description: "Update the key name, status, allowed referrers, and permissions.",
75
75
  user_api_key_edit_title: "Edit API key",
76
76
  user_api_key_enabled: "Enabled",
77
77
  user_api_key_hidden: "Secret hidden",
@@ -178,7 +178,7 @@ const messages = {
178
178
  user_api_key_created_title: "Clé API créée",
179
179
  user_api_key_delete_error: "Impossible de supprimer la clé API.",
180
180
  user_api_key_disabled: "Désactivée",
181
- user_api_key_edit_description: "Mettez à jour le nom, le statut et les référents autorisés de la clé.",
181
+ user_api_key_edit_description: "Mettez à jour le nom, le statut, les référents autorisés et les autorisations de la clé.",
182
182
  user_api_key_edit_title: "Modifier la clé API",
183
183
  user_api_key_enabled: "Activée",
184
184
  user_api_key_hidden: "Secret masqué",
@@ -858,13 +858,15 @@ function ApiKeyManager({ authClient, active, permissions = {}, }) {
858
858
  }, searchState: "local", state: {
859
859
  empty: loading ? m.user_loading() : m.table_empty(),
860
860
  loading,
861
- } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { authClient: authClient, configId: "user", keyData: editingKey, messages: {
861
+ } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { configId: "user", keyData: editingKey, permissions: permissions, messages: {
862
862
  enabled: m.user_api_key_enabled(),
863
863
  name: m.user_api_key_name(),
864
864
  referrers: m.user_api_key_referrers(),
865
865
  referrersDescription: m.user_api_key_referrers_description(),
866
866
  referrersError: m.user_api_key_referrers_error(),
867
867
  referrersPlaceholder: m.user_api_key_referrers_placeholder(),
868
+ permissions: m.user_api_key_permissions(),
869
+ permissionsDescription: m.user_api_key_permissions_description(),
868
870
  updateError: m.user_api_key_update_error(),
869
871
  }, onSaved: () => {
870
872
  refreshKeys();
@@ -88,11 +88,14 @@ export declare const ExtraApiGroup: HttpApiGroup.HttpApiGroup<"authExtra", HttpA
88
88
  readonly newPassword: Schema.NonEmptyString;
89
89
  }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<Schema.Struct<{
90
90
  readonly ok: Schema.Boolean;
91
- }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"updateApiKeyPermissions", "PATCH", "/auth/api-key/:keyId/permissions", HttpApiEndpoint.StringTree<Schema.Struct<{
91
+ }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"updateApiKey", "PATCH", "/auth/api-key/:keyId", HttpApiEndpoint.StringTree<Schema.Struct<{
92
92
  readonly keyId: Schema.NonEmptyString;
93
93
  }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<Schema.Struct<{
94
94
  readonly configId: Schema.Union<readonly [Schema.Literal<"user">, Schema.Literal<"organization">, Schema.Literal<"service">]>;
95
- readonly permissions: Schema.$Record<Schema.String, Schema.$Array<Schema.String>>;
95
+ readonly name: Schema.NonEmptyString;
96
+ readonly enabled: Schema.Boolean;
97
+ readonly permissions: Schema.optional<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
98
+ readonly referrers: Schema.optional<Schema.$Array<Schema.String>>;
96
99
  }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<Schema.Struct<{
97
100
  readonly ok: Schema.Boolean;
98
101
  }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"uploadUserImage", "POST", "/auth/image/upload", HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<import("effect/unstable/httpapi/HttpApiSchema").asMultipartStream<Schema.Struct<{
@@ -102,7 +105,6 @@ export declare const ExtraApiGroup: HttpApiGroup.HttpApiGroup<"authExtra", HttpA
102
105
  }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"verifyApiKey", "POST", "/auth/verify-api-key", HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<Schema.Struct<{
103
106
  readonly key: Schema.NonEmptyString;
104
107
  readonly configId: Schema.optional<Schema.Union<readonly [Schema.Literal<"user">, Schema.Literal<"organization">, Schema.Literal<"service">]>>;
105
- readonly permissions: Schema.optional<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
106
108
  }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<Schema.Struct<{
107
109
  readonly valid: Schema.Boolean;
108
110
  readonly error: Schema.NullOr<Schema.Struct<{
@@ -1,7 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  import { OpenApi } from "effect/unstable/httpapi";
3
3
  import { HttpApiEndpoint, HttpApiError, HttpApiGroup, } from "effect/unstable/httpapi";
4
- import { ExtraBadRequest, ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraImageUploadMultipartPayload, ExtraOkResponse, ExtraOrganizationPublicProfile, ExtraOrganizationPublicProfileQuery, ExtraProjectPublicConfig, ExtraProjectPublicConfigQuery, ExtraSetPasswordPayload, ExtraUpdateApiKeyPermissionsPayload, ExtraUploadedAsset, ExtraVerifyApiKeyPayload, ExtraVerifyApiKeyResponse, ExtraVerifyPasswordPayload, } from "./schema";
4
+ import { ExtraBadRequest, ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraImageUploadMultipartPayload, ExtraOkResponse, ExtraOrganizationPublicProfile, ExtraOrganizationPublicProfileQuery, ExtraProjectPublicConfig, ExtraProjectPublicConfigQuery, ExtraSetPasswordPayload, ExtraUpdateApiKeyPayload, ExtraUploadedAsset, ExtraVerifyApiKeyPayload, ExtraVerifyApiKeyResponse, ExtraVerifyPasswordPayload, } from "./schema";
5
5
  export * from "./schema";
6
6
  export const ExtraApiGroup = HttpApiGroup.make("authExtra")
7
7
  .add(HttpApiEndpoint.get("getProjectPublicConfig", "/auth/project-config", {
@@ -13,11 +13,14 @@ export const ExtraApiGroup = HttpApiGroup.make("authExtra")
13
13
  summary: "Get host-aware project white-label config",
14
14
  description: "Returns resolved public branding and authentication options through the proxied auth API.",
15
15
  })))
16
- .add(HttpApiEndpoint.patch("updateApiKeyPermissions", "/auth/api-key/:keyId/permissions", {
16
+ .add(HttpApiEndpoint.patch("updateApiKey", "/auth/api-key/:keyId", {
17
17
  params: Schema.Struct({ keyId: Schema.NonEmptyString }),
18
18
  payload: Schema.Struct({
19
- configId: ExtraUpdateApiKeyPermissionsPayload.fields.configId,
20
- permissions: ExtraUpdateApiKeyPermissionsPayload.fields.permissions,
19
+ configId: ExtraUpdateApiKeyPayload.fields.configId,
20
+ name: ExtraUpdateApiKeyPayload.fields.name,
21
+ enabled: ExtraUpdateApiKeyPayload.fields.enabled,
22
+ permissions: ExtraUpdateApiKeyPayload.fields.permissions,
23
+ referrers: ExtraUpdateApiKeyPayload.fields.referrers,
21
24
  }),
22
25
  success: ExtraOkResponse,
23
26
  error: [
@@ -27,9 +30,9 @@ export const ExtraApiGroup = HttpApiGroup.make("authExtra")
27
30
  HttpApiError.InternalServerError,
28
31
  ],
29
32
  }).annotateMerge(OpenApi.annotations({
30
- title: "Update API key permissions",
31
- summary: "Replace an API key's permissions",
32
- description: "Updates server-only API key permissions after Better Auth verifies user ownership or organization key-management access.",
33
+ title: "Update API key",
34
+ summary: "Update an API key",
35
+ description: "Updates API key details and server-only permissions after Better Auth verifies user ownership or organization key-management access.",
33
36
  })))
34
37
  .add(HttpApiEndpoint.get("getOrganizationPublicProfile", "/auth/organization-profile", {
35
38
  query: ExtraOrganizationPublicProfileQuery,
@@ -26,15 +26,17 @@ export declare const ExtraCreateApiKeyResponse: Schema.Struct<{
26
26
  readonly id: Schema.String;
27
27
  readonly key: Schema.String;
28
28
  }>;
29
- export declare const ExtraUpdateApiKeyPermissionsPayload: Schema.Struct<{
29
+ export declare const ExtraUpdateApiKeyPayload: Schema.Struct<{
30
30
  readonly configId: Schema.Union<readonly [Schema.Literal<"user">, Schema.Literal<"organization">, Schema.Literal<"service">]>;
31
31
  readonly keyId: Schema.NonEmptyString;
32
- readonly permissions: Schema.$Record<Schema.String, Schema.$Array<Schema.String>>;
32
+ readonly name: Schema.NonEmptyString;
33
+ readonly enabled: Schema.Boolean;
34
+ readonly permissions: Schema.optional<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
35
+ readonly referrers: Schema.optional<Schema.$Array<Schema.String>>;
33
36
  }>;
34
37
  export declare const ExtraVerifyApiKeyPayload: Schema.Struct<{
35
38
  readonly key: Schema.NonEmptyString;
36
39
  readonly configId: Schema.optional<Schema.Union<readonly [Schema.Literal<"user">, Schema.Literal<"organization">, Schema.Literal<"service">]>>;
37
- readonly permissions: Schema.optional<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
38
40
  }>;
39
41
  export declare const ExtraApiKeyVerificationError: Schema.Struct<{
40
42
  readonly message: Schema.String;
@@ -176,7 +178,7 @@ export type ExtraSetPasswordPayload = typeof ExtraSetPasswordPayload.Type;
176
178
  export type ExtraVerifyPasswordPayload = typeof ExtraVerifyPasswordPayload.Type;
177
179
  export type ExtraCreateApiKeyPayload = typeof ExtraCreateApiKeyPayload.Type;
178
180
  export type ExtraCreateApiKeyResponse = typeof ExtraCreateApiKeyResponse.Type;
179
- export type ExtraUpdateApiKeyPermissionsPayload = typeof ExtraUpdateApiKeyPermissionsPayload.Type;
181
+ export type ExtraUpdateApiKeyPayload = typeof ExtraUpdateApiKeyPayload.Type;
180
182
  export type ExtraVerifyApiKeyPayload = typeof ExtraVerifyApiKeyPayload.Type;
181
183
  export type ExtraVerifyApiKeyResponse = typeof ExtraVerifyApiKeyResponse.Type;
182
184
  export type ExtraProjectPublicConfigQuery = typeof ExtraProjectPublicConfigQuery.Type;
@@ -70,35 +70,39 @@ export const ExtraCreateApiKeyResponse = Schema.Struct({
70
70
  description: "Response returned after creating an API key. The secret key is only returned once.",
71
71
  examples: [{ id: "api-key-id", key: "user_1234567890" }],
72
72
  });
73
- export const ExtraUpdateApiKeyPermissionsPayload = Schema.Struct({
73
+ export const ExtraUpdateApiKeyPayload = Schema.Struct({
74
74
  configId: ExtraApiKeyConfigId,
75
75
  keyId: Schema.NonEmptyString,
76
- permissions: ExtraApiKeyPermissions,
76
+ name: Schema.NonEmptyString,
77
+ enabled: Schema.Boolean,
78
+ permissions: Schema.optional(ExtraApiKeyPermissions),
79
+ referrers: Schema.optional(Schema.Array(Schema.String)),
77
80
  }).annotate({
78
- identifier: "ExtraUpdateApiKeyPermissionsPayload",
79
- title: "Extra update API key permissions payload",
80
- description: "Server-authorized replacement permissions for an existing API key.",
81
+ identifier: "ExtraUpdateApiKeyPayload",
82
+ title: "Extra update API key payload",
83
+ description: "Server-authorized updates for an existing API key, including its permissions.",
81
84
  examples: [
82
85
  {
83
86
  configId: "organization",
84
87
  keyId: "api-key-id",
88
+ name: "Production key",
89
+ enabled: true,
85
90
  permissions: { "211-search": ["search:execute"] },
91
+ referrers: ["https://app.example.com"],
86
92
  },
87
93
  ],
88
94
  });
89
95
  export const ExtraVerifyApiKeyPayload = Schema.Struct({
90
96
  key: Schema.NonEmptyString,
91
97
  configId: Schema.optional(ExtraApiKeyConfigId),
92
- permissions: Schema.optional(ExtraApiKeyPermissions),
93
98
  }).annotate({
94
99
  identifier: "ExtraVerifyApiKeyPayload",
95
100
  title: "Extra verify API key payload",
96
- description: "Payload used by remote services to verify a KrakStack API key.",
101
+ description: "Payload used to verify a KrakStack API key. Project permissions are enforced by consumer access policies.",
97
102
  examples: [
98
103
  {
99
104
  key: "user_1234567890",
100
105
  configId: "user",
101
- permissions: { projects: ["read"] },
102
106
  },
103
107
  ],
104
108
  });
@@ -0,0 +1,95 @@
1
+ import { Layer } from "effect";
2
+ import { HttpApiError, HttpApiMiddleware } from "effect/unstable/httpapi";
3
+ import { CurrentActor, type ProjectAccessDefinition } from "../access";
4
+ import { AuthService } from "../service";
5
+ declare const AnyActorRequired_base: HttpApiMiddleware.ServiceClass<AnyActorRequired, "@krak-stack/auth/ActorRequired", {
6
+ requires: AuthService;
7
+ provides: CurrentActor;
8
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
9
+ clientError: never;
10
+ requiredForClient: false;
11
+ security: never;
12
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
13
+ declare class AnyActorRequired extends AnyActorRequired_base {
14
+ }
15
+ declare const UserActorRequired_base: HttpApiMiddleware.ServiceClass<UserActorRequired, "@krak-stack/auth/ActorRequired/User", {
16
+ requires: AuthService;
17
+ provides: CurrentActor;
18
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
19
+ clientError: never;
20
+ requiredForClient: false;
21
+ security: never;
22
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
23
+ declare class UserActorRequired extends UserActorRequired_base {
24
+ }
25
+ declare const ApiKeyActorRequired_base: HttpApiMiddleware.ServiceClass<ApiKeyActorRequired, "@krak-stack/auth/ActorRequired/ApiKey", {
26
+ requires: AuthService;
27
+ provides: CurrentActor;
28
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
29
+ clientError: never;
30
+ requiredForClient: false;
31
+ security: never;
32
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
33
+ declare class ApiKeyActorRequired extends ApiKeyActorRequired_base {
34
+ }
35
+ declare const UserApiKeyActorRequired_base: HttpApiMiddleware.ServiceClass<UserApiKeyActorRequired, "@krak-stack/auth/ActorRequired/ApiKey/User", {
36
+ requires: AuthService;
37
+ provides: CurrentActor;
38
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
39
+ clientError: never;
40
+ requiredForClient: false;
41
+ security: never;
42
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
43
+ declare class UserApiKeyActorRequired extends UserApiKeyActorRequired_base {
44
+ }
45
+ declare const OrganizationApiKeyActorRequired_base: HttpApiMiddleware.ServiceClass<OrganizationApiKeyActorRequired, "@krak-stack/auth/ActorRequired/ApiKey/Organization", {
46
+ requires: AuthService;
47
+ provides: CurrentActor;
48
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
49
+ clientError: never;
50
+ requiredForClient: false;
51
+ security: never;
52
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
53
+ declare class OrganizationApiKeyActorRequired extends OrganizationApiKeyActorRequired_base {
54
+ }
55
+ declare const ServiceApiKeyActorRequired_base: HttpApiMiddleware.ServiceClass<ServiceApiKeyActorRequired, "@krak-stack/auth/ActorRequired/ApiKey/Service", {
56
+ requires: AuthService;
57
+ provides: CurrentActor;
58
+ error: readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden];
59
+ clientError: never;
60
+ requiredForClient: false;
61
+ security: never;
62
+ }, HttpApiMiddleware.HttpApiMiddleware<CurrentActor, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden], AuthService>>;
63
+ declare class ServiceApiKeyActorRequired extends ServiceApiKeyActorRequired_base {
64
+ }
65
+ export type ActorConstraint = {
66
+ readonly type: "user";
67
+ } | {
68
+ readonly type: "apiKey";
69
+ readonly ownerType?: "user" | "organization" | "service" | undefined;
70
+ };
71
+ declare const actorRequiredLayer: <Project extends string, Action extends string>(access: ProjectAccessDefinition<Project, Action>) => Layer.Layer<AnyActorRequired | ApiKeyActorRequired | OrganizationApiKeyActorRequired | ServiceApiKeyActorRequired | UserActorRequired | UserApiKeyActorRequired, never, never>;
72
+ type ActorRequiredFactory = {
73
+ (): typeof AnyActorRequired;
74
+ (constraint: {
75
+ readonly type: "user";
76
+ }): typeof UserActorRequired;
77
+ (constraint: {
78
+ readonly type: "apiKey";
79
+ readonly ownerType: "user";
80
+ }): typeof UserApiKeyActorRequired;
81
+ (constraint: {
82
+ readonly type: "apiKey";
83
+ readonly ownerType: "organization";
84
+ }): typeof OrganizationApiKeyActorRequired;
85
+ (constraint: {
86
+ readonly type: "apiKey";
87
+ readonly ownerType: "service";
88
+ }): typeof ServiceApiKeyActorRequired;
89
+ (constraint: {
90
+ readonly type: "apiKey";
91
+ }): typeof ApiKeyActorRequired;
92
+ readonly layer: typeof actorRequiredLayer;
93
+ };
94
+ export declare const ActorRequired: ActorRequiredFactory;
95
+ export {};
@@ -0,0 +1,127 @@
1
+ import { Effect, Layer, Schema } from "effect";
2
+ import { HttpApiError, HttpApiMiddleware } from "effect/unstable/httpapi";
3
+ import { ApiKeyPermissionGrant, CurrentActor, } from "../access";
4
+ import { parseRoleList } from "../roles";
5
+ import { AuthService } from "../service";
6
+ const activeMemberRoles = ({ organizationId, userId, }) => Effect.gen(function* () {
7
+ const auth = yield* AuthService;
8
+ const member = yield* auth.organizations
9
+ .getActiveMember({ params: { organizationId, userId } })
10
+ .pipe(Effect.mapError(() => new HttpApiError.Forbidden({})));
11
+ return parseRoleList(member.role);
12
+ });
13
+ const resolveCurrentActor = (access) => Effect.gen(function* () {
14
+ const auth = yield* AuthService;
15
+ const session = yield* auth.requireSession();
16
+ if (session.authMethod.type === "apiKey") {
17
+ const apiKey = session.authMethod.apiKey;
18
+ const grant = yield* Schema.decodeUnknownEffect(ApiKeyPermissionGrant)(apiKey.permissions ?? {}).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
19
+ if (apiKey.configId === "service") {
20
+ return access.actorForApiKey({
21
+ apiKeyId: apiKey.id,
22
+ owner: { type: "service", serviceId: apiKey.referenceId },
23
+ grant,
24
+ });
25
+ }
26
+ const organizationId = session.session.activeOrganizationId;
27
+ if (!organizationId)
28
+ return yield* new HttpApiError.Unauthorized({});
29
+ if (apiKey.configId === "organization") {
30
+ return access.actorForApiKey({
31
+ apiKeyId: apiKey.id,
32
+ owner: { type: "organization", organizationId },
33
+ grant,
34
+ });
35
+ }
36
+ if (apiKey.configId === "user" && session.user) {
37
+ const roles = yield* activeMemberRoles({
38
+ organizationId,
39
+ userId: session.user.id,
40
+ });
41
+ return access.actorForApiKey({
42
+ apiKeyId: apiKey.id,
43
+ owner: {
44
+ type: "user",
45
+ userId: session.user.id,
46
+ organizationId,
47
+ roles,
48
+ },
49
+ grant,
50
+ });
51
+ }
52
+ return yield* new HttpApiError.Unauthorized({});
53
+ }
54
+ if (!session.user)
55
+ return yield* new HttpApiError.Unauthorized({});
56
+ const organizationId = session.session.activeOrganizationId;
57
+ if (!organizationId)
58
+ return yield* new HttpApiError.Unauthorized({});
59
+ const roles = yield* activeMemberRoles({
60
+ organizationId,
61
+ userId: session.user.id,
62
+ });
63
+ return access.actorForUser({
64
+ userId: session.user.id,
65
+ organizationId,
66
+ roles,
67
+ });
68
+ });
69
+ class AnyActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired", {
70
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
71
+ }) {
72
+ }
73
+ class UserActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired/User", {
74
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
75
+ }) {
76
+ }
77
+ class ApiKeyActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired/ApiKey", {
78
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
79
+ }) {
80
+ }
81
+ class UserApiKeyActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired/ApiKey/User", {
82
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
83
+ }) {
84
+ }
85
+ class OrganizationApiKeyActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired/ApiKey/Organization", {
86
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
87
+ }) {
88
+ }
89
+ class ServiceApiKeyActorRequired extends HttpApiMiddleware.Service()("@krak-stack/auth/ActorRequired/ApiKey/Service", {
90
+ error: [HttpApiError.Unauthorized, HttpApiError.Forbidden],
91
+ }) {
92
+ }
93
+ const matchesConstraint = (actor, constraint) => {
94
+ if (!constraint)
95
+ return true;
96
+ if (constraint.type === "user")
97
+ return actor.actor.type === "user";
98
+ return (actor.actor.type === "apiKey" &&
99
+ (!constraint.ownerType || actor.actor.owner.type === constraint.ownerType));
100
+ };
101
+ const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.flatMap((actor) => matchesConstraint(actor, constraint)
102
+ ? Effect.succeed(actor)
103
+ : Effect.fail(new HttpApiError.Forbidden({}))));
104
+ const actorRequired = (constraint) => {
105
+ if (!constraint)
106
+ return AnyActorRequired;
107
+ if (constraint.type === "user")
108
+ return UserActorRequired;
109
+ if (constraint.ownerType === "user")
110
+ return UserApiKeyActorRequired;
111
+ if (constraint.ownerType === "organization") {
112
+ return OrganizationApiKeyActorRequired;
113
+ }
114
+ if (constraint.ownerType === "service")
115
+ return ServiceApiKeyActorRequired;
116
+ return ApiKeyActorRequired;
117
+ };
118
+ const actorRequiredLayer = (access) => Layer.mergeAll(Layer.succeed(AnyActorRequired, (httpEffect) => requiredActor(access).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(UserActorRequired, (httpEffect) => requiredActor(access, { type: "user" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(ApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(UserApiKeyActorRequired, (httpEffect) => requiredActor(access, { type: "apiKey", ownerType: "user" }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(OrganizationApiKeyActorRequired, (httpEffect) => requiredActor(access, {
119
+ type: "apiKey",
120
+ ownerType: "organization",
121
+ }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))), Layer.succeed(ServiceApiKeyActorRequired, (httpEffect) => requiredActor(access, {
122
+ type: "apiKey",
123
+ ownerType: "service",
124
+ }).pipe(Effect.flatMap((actor) => httpEffect.pipe(Effect.provideService(CurrentActor, actor))))));
125
+ export const ActorRequired = Object.assign(actorRequired, {
126
+ layer: actorRequiredLayer,
127
+ });
@@ -3,9 +3,11 @@ export type { AuthSession, AuthSessionWithOrganization, AuthSessionWithUser, Aut
3
3
  export { AuthClientConfig } from "../config";
4
4
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group";
5
5
  export { proxyAuthRequest } from "./proxy";
6
+ export { ActorRequired } from "./actor";
7
+ export type { ActorConstraint } from "./actor";
6
8
  export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware";
7
9
  export type { AuthenticationLiveOptions } from "./middleware";
8
10
  export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema";
9
11
  export type { Member, Organization, OrganizationMetadata, User, } from "../schema";
10
- export { ApiKeyPermissionGrant, CurrentPrincipal, Forbidden, all, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
11
- export type { ApiKeyOwner, ApiKeyPrincipal, Policy, Principal, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessDefinition, UserPrincipal, } from "../access";
12
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
13
+ export type { ApiKeyOwner, ApiKeyActor, Actor, Policy, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessDefinition, UserActor, } from "../access";
@@ -2,6 +2,7 @@ export { AuthService } from "../service";
2
2
  export { AuthClientConfig } from "../config";
3
3
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group";
4
4
  export { proxyAuthRequest } from "./proxy";
5
+ export { ActorRequired } from "./actor";
5
6
  export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware";
6
7
  export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema";
7
- export { ApiKeyPermissionGrant, CurrentPrincipal, Forbidden, all, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
8
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access";
package/dist/service.d.ts CHANGED
@@ -28,7 +28,7 @@ export type AuthSessionWithUser = AuthSession & {
28
28
  export type AuthSessionWithUserAndOrganization = AuthSessionWithUser & AuthSessionWithOrganization;
29
29
  export type AuthServiceLayerOptions = Partial<ClientConfig> & {
30
30
  readonly headers?: Record<string, string>;
31
- readonly apiKeyConfigId?: "user" | "organization";
31
+ readonly apiKeyConfigId?: "user" | "organization" | "service";
32
32
  };
33
33
  declare const AuthService_base: Context.ServiceClass<AuthService, "@krak-stack/auth/AuthService", {
34
34
  getSession: () => Effect.Effect<AuthSession | null, HttpApiError.Unauthorized, never>;
@@ -206,14 +206,19 @@ declare const AuthService_base: Context.ServiceClass<AuthService, "@krak-stack/a
206
206
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
207
207
  readonly ok: import("effect/Schema").Boolean;
208
208
  }, "Type">, Mode>, import("effect/unstable/http/HttpClientError").HttpClientError | ([Mode] extends ["response-only"] ? never : import("./extra/schema").ExtraBadRequest | HttpApiError.Forbidden | HttpApiError.InternalServerError | import("effect/Schema").SchemaError | HttpApiError.Unauthorized), [Mode] extends ["response-only"] ? never : never>;
209
- readonly updateApiKeyPermissions: <Mode extends HttpApiClient.Client.ResponseMode = import("effect/unstable/httpapi/HttpApiEndpoint").ClientResponseMode>(request: {
209
+ readonly updateApiKey: <Mode extends HttpApiClient.Client.ResponseMode = import("effect/unstable/httpapi/HttpApiEndpoint").ClientResponseMode>(request: {
210
210
  readonly params: import("effect/Schema").Struct.ReadonlySide<{
211
211
  readonly keyId: import("effect/Schema").NonEmptyString;
212
212
  }, "Type">;
213
- readonly payload: import("effect/Schema").Struct.ReadonlySide<{
214
- readonly configId: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>;
215
- readonly permissions: import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>;
216
- }, "Type">;
213
+ readonly payload: {
214
+ readonly configId: "organization" | "service" | "user";
215
+ readonly name: string;
216
+ readonly enabled: boolean;
217
+ readonly permissions?: {
218
+ readonly [x: string]: readonly string[];
219
+ } | undefined;
220
+ readonly referrers?: readonly string[] | undefined;
221
+ };
217
222
  readonly responseMode?: Mode;
218
223
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
219
224
  readonly ok: import("effect/Schema").Boolean;
@@ -228,9 +233,6 @@ declare const AuthService_base: Context.ServiceClass<AuthService, "@krak-stack/a
228
233
  readonly payload: {
229
234
  readonly key: string;
230
235
  readonly configId?: "organization" | "service" | "user" | undefined;
231
- readonly permissions?: {
232
- readonly [x: string]: readonly string[];
233
- } | undefined;
234
236
  };
235
237
  readonly responseMode?: Mode;
236
238
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
@@ -836,14 +838,19 @@ declare const AuthService_base: Context.ServiceClass<AuthService, "@krak-stack/a
836
838
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
837
839
  readonly ok: import("effect/Schema").Boolean;
838
840
  }, "Type">, Mode>, import("effect/unstable/http/HttpClientError").HttpClientError | ([Mode] extends ["response-only"] ? never : import("./extra/schema").ExtraBadRequest | HttpApiError.Forbidden | HttpApiError.InternalServerError | import("effect/Schema").SchemaError | HttpApiError.Unauthorized), [Mode] extends ["response-only"] ? never : never>;
839
- readonly updateApiKeyPermissions: <Mode extends HttpApiClient.Client.ResponseMode = import("effect/unstable/httpapi/HttpApiEndpoint").ClientResponseMode>(request: {
841
+ readonly updateApiKey: <Mode extends HttpApiClient.Client.ResponseMode = import("effect/unstable/httpapi/HttpApiEndpoint").ClientResponseMode>(request: {
840
842
  readonly params: import("effect/Schema").Struct.ReadonlySide<{
841
843
  readonly keyId: import("effect/Schema").NonEmptyString;
842
844
  }, "Type">;
843
- readonly payload: import("effect/Schema").Struct.ReadonlySide<{
844
- readonly configId: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"user">, import("effect/Schema").Literal<"organization">, import("effect/Schema").Literal<"service">]>;
845
- readonly permissions: import("effect/Schema").$Record<import("effect/Schema").String, import("effect/Schema").$Array<import("effect/Schema").String>>;
846
- }, "Type">;
845
+ readonly payload: {
846
+ readonly configId: "organization" | "service" | "user";
847
+ readonly name: string;
848
+ readonly enabled: boolean;
849
+ readonly permissions?: {
850
+ readonly [x: string]: readonly string[];
851
+ } | undefined;
852
+ readonly referrers?: readonly string[] | undefined;
853
+ };
847
854
  readonly responseMode?: Mode;
848
855
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
849
856
  readonly ok: import("effect/Schema").Boolean;
@@ -858,9 +865,6 @@ declare const AuthService_base: Context.ServiceClass<AuthService, "@krak-stack/a
858
865
  readonly payload: {
859
866
  readonly key: string;
860
867
  readonly configId?: "organization" | "service" | "user" | undefined;
861
- readonly permissions?: {
862
- readonly [x: string]: readonly string[];
863
- } | undefined;
864
868
  };
865
869
  readonly responseMode?: Mode;
866
870
  }) => Effect.Effect<HttpApiClient.Client.Response<import("effect/Schema").Struct.ReadonlySide<{
package/dist/service.js CHANGED
@@ -59,7 +59,7 @@ const sessionCache = Effect.runSync(Cache.makeWith(() => Effect.gen(function* ()
59
59
  export class AuthService extends Context.Service()("@krak-stack/auth/AuthService", {
60
60
  make: (options = {}) => Effect.gen(function* () {
61
61
  const headers = options.headers ?? {};
62
- const apiKeyConfigId = options.apiKeyConfigId ?? "user";
62
+ const apiKeyConfigId = options.apiKeyConfigId;
63
63
  const config = yield* AuthClientConfig;
64
64
  const http = yield* HttpClient.HttpClient;
65
65
  const httpClient = HttpClient.mapRequest(http, (request) => isBetterAuthSessionRequest(request)
@@ -101,7 +101,10 @@ export class AuthService extends Context.Service()("@krak-stack/auth/AuthService
101
101
  const getApiKeySession = (key) => Effect.gen(function* () {
102
102
  const verified = yield* api.authExtra
103
103
  .verifyApiKey({
104
- payload: { key, configId: apiKeyConfigId },
104
+ payload: {
105
+ key,
106
+ ...(apiKeyConfigId ? { configId: apiKeyConfigId } : {}),
107
+ },
105
108
  })
106
109
  .pipe(Effect.mapError(unauthorized));
107
110
  if (!verified.valid || !verified.key) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krak-stack/auth",
3
- "version": "0.1.59",
3
+ "version": "0.1.60",
4
4
  "description": "Effect HttpApi clients and schemas for KrakStack Auth.",
5
5
  "license": "MIT",
6
6
  "files": [