:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { LemonBanner, LemonDialog } from '@posthog/lemon-ui'
import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import { CodeSnippet } from 'lib/components/CodeSnippet'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import {
APIScope,
API_SCOPES,
SCOPES_IMPLYING_FEATURE_FLAG_WRITE,
type ScopePickerGroup,
type ScopeAccessLevel,
type ScopePickerRow,
scopeRowWarning,
clampScopeLevel,
groupScopeRows,
scopeMatchesSearch,
scopesArrayToObject,
scopesObjectToArray,
} from 'lib/scopes'
import { hasMembershipLevelOrHigher, organizationAllowsPersonalApiKeysForMembers } from 'lib/utils/permissioning'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { API_KEY_SCOPE_PRESETS } from '~/lib/scopes'
import { AvailableFeature, OrganizationBasicType, PersonalAPIKeyType, TeamBasicType, UserType } from '~/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
export type EditingKeyFormValues = Pick<
PersonalAPIKeyType,
'label' | 'description' | 'scopes' | 'scoped_organizations' | 'scoped_teams'
> & {
preset?: string
access_type?: 'all' | 'organizations' | 'teams'
expiration?: KeyExpirationOption
}
/** `keep` leaves an edited key's expiry as it is. The day counts start when the form is saved. */
export type KeyExpirationOption = 'keep' | 'never' | '1' | '7' | '30' | '90' | '365'
export function isExpired(expiresAt: string | null | undefined, now: dayjs.Dayjs = dayjs()): boolean {
return !!expiresAt && !dayjs(expiresAt).isAfter(now)
}
/** The `expires_at` to send for the chosen option, or undefined to leave it unchanged. */
export function expiresAtForOption(
expiration: KeyExpirationOption | undefined,
now: dayjs.Dayjs = dayjs()
): string | null | undefined {
switch (expiration) {
case undefined:
case 'keep':
return undefined
case 'never':
return null
default:
return now.add(Number(expiration), 'day').toISOString()
}
}
/** A picker row for a personal API key, with the scope it stands for so the search can match it. */
export type PersonalAPIKeyScopeRow = ScopePickerRow & { scope: APIScope }
export type PersonalAPIKeyScopeGroup = ScopePickerGroup<PersonalAPIKeyScopeRow>
// The scopes array with each key set to its level. A write on a survey or early access feature also
// writes a feature flag (targeting / linked flag), so it implies feature_flag:write (see
// SCOPES_IMPLYING_FEATURE_FLAG_WRITE). Auto-select it so the key works out of the box. Scoped to
// these toggle actions only, not every scopes change, so it stays visible and removable if the key
// only manages plain surveys.
const withScopeLevels = (scopes: string[], levels: [string, ScopeAccessLevel][]): string[] => {
const scopesObject = scopesArrayToObject(scopes)
for (const [key, level] of levels) {
if (level === 'none') {
delete scopesObject[key]
} else {
scopesObject[key] = level
}
if (
level === 'write' &&
key in SCOPES_IMPLYING_FEATURE_FLAG_WRITE &&
scopesObject['feature_flag'] !== 'write'
) {
scopesObject['feature_flag'] = 'write'
}
}
return scopesObjectToArray(scopesObject)
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personalAPIKeysLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
user: UserType | null // userLogic
allAccessSelected: boolean
allOrganizations: OrganizationBasicType[]
allTeams: TeamBasicType[] | null
allTeamsLoading: boolean
allowedScopeKeys: Set<string>
allowedScopes: APIScope[]
canUsePersonalApiKeys: boolean
editingKey: EditingKeyFormValues
editingKeyAllErrors: Record<string, any>
editingKeyChanged: boolean
editingKeyErrors: DeepPartialMap<EditingKeyFormValues, ValidationErrorType>
editingKeyHasErrors: boolean
editingKeyId: PersonalAPIKeyType['id'] | null
editingKeyManualErrors: Record<string, any>
editingKeyTouched: boolean
editingKeyTouches: Record<string, boolean>
editingKeyValidationErrors: DeepPartialMap<EditingKeyFormValues, ValidationErrorType>
filteredScopeGroups: PersonalAPIKeyScopeGroup[]
formScopeRadioValues: Record<string, string>
getRestrictedOrganizationsForKey: (keyId: string) => OrganizationBasicType[]
getRestrictedTeamsForKey: (keyId: string) => TeamBasicType[]
isDescriptionFieldVisible: boolean
isEditingKeyLegacy: boolean
isEditingKeySubmitting: boolean
isEditingKeyValid: boolean
isPersonalApiKeyIdDisabled: (keyId: string) => boolean
keys: PersonalAPIKeyType[]
keysLoading: boolean
scopeRows: PersonalAPIKeyScopeRow[]
searchTerm: string
showEditingKeyErrors: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personalAPIKeysLogicActions {
createKeySuccess: (key: PersonalAPIKeyType) => {
key: PersonalAPIKeyType
}
deleteKey: (id: PersonalAPIKeyType['id']) => {
id: string
}
deleteKeyFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
deleteKeySuccess: (
keys: PersonalAPIKeyType[],
payload?: {
id: string
}
) => {
keys: PersonalAPIKeyType[]
payload?: {
id: string
}
}
loadAllTeams: () => {
value: true
}
loadAllTeamsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAllTeamsSuccess: (
allTeams: TeamBasicType[],
payload?: {
value: true
}
) => {
allTeams: TeamBasicType[]
payload?: {
value: true
}
}
loadKeys: () => {
value: true
}
loadKeysFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadKeysSuccess: (
keys: PersonalAPIKeyType[],
payload?: {
value: true
}
) => {
keys: PersonalAPIKeyType[]
payload?: {
value: true
}
}
resetEditingKey: (values?: EditingKeyFormValues) => {
values?: EditingKeyFormValues
}
resetScopes: () => {
value: true
}
rollKey: (
id: PersonalAPIKeyType['id'],
expiresAt?: string | null
) => {
expiresAt: string | null | undefined
id: string
}
rollKeyFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
rollKeySuccess: (
keys: PersonalAPIKeyType[],
payload?: {
expiresAt: string | null | undefined
id: string
}
) => {
keys: PersonalAPIKeyType[]
payload?: {
expiresAt: string | null | undefined
id: string
}
}
setEditingKeyId: (id: PersonalAPIKeyType['id'] | null) => {
id: string | null
}
setEditingKeyManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setEditingKeyValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setEditingKeyValues: (values: DeepPartial<EditingKeyFormValues>) => {
values: DeepPartial<EditingKeyFormValues>
}
setScopeGroupAccess: (
keys: string[],
level: ScopeAccessLevel
) => {
keys: string[]
level: ScopeAccessLevel
}
setScopeRadioValue: (
key: string,
action: string
) => {
action: string
key: string
}
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
showDescriptionField: () => {
value: true
}
showRollKeySuccessDialog: (
key: PersonalAPIKeyType,
prevMaskedValue?: string | null
) => {
key: PersonalAPIKeyType
prevMaskedValue: string | null | undefined
}
submitEditingKey: () => {
value: boolean
}
submitEditingKeyFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitEditingKeyRequest: (editingKey: EditingKeyFormValues) => {
editingKey: EditingKeyFormValues
}
submitEditingKeySuccess: (editingKey: EditingKeyFormValues) => {
editingKey: EditingKeyFormValues
}
touchEditingKeyField: (key: string) => {
key: string
}
updateKey: (
data: Partial<Pick<PersonalAPIKeyType, 'label' | 'scopes'>>
) => Partial<Pick<PersonalAPIKeyType, 'label' | 'scopes'>>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personalAPIKeysLogicMeta {
__keaTypeGenInternalSelectorTypes: {
allowedScopes: (
featureFlags: FeatureFlagsSet,
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
) => APIScope[]
allowedScopeKeys: (allowedScopes: APIScope[]) => Set<string>
scopeRows: (
allowedScopes: APIScope[],
formScopeRadioValues: Record<string, string>,
editingKey: EditingKeyFormValues
) => PersonalAPIKeyScopeRow[]
filteredScopeGroups: (searchTerm: string, scopeRows: PersonalAPIKeyScopeRow[]) => PersonalAPIKeyScopeGroup[]
formScopeRadioValues: (editingKey: EditingKeyFormValues) => Record<string, string>
allAccessSelected: (editingKey: EditingKeyFormValues) => boolean
isEditingKeyLegacy: (editingKeyId: string | null, keys: PersonalAPIKeyType[]) => boolean
allOrganizations: (user: UserType | null) => OrganizationBasicType[]
canUsePersonalApiKeys: (user: UserType | null) => boolean
isPersonalApiKeyIdDisabled: (
allOrganizations: OrganizationBasicType[],
allTeams: TeamBasicType[] | null,
keys: PersonalAPIKeyType[],
getRestrictedOrganizationsForKey: (keyId: string) => OrganizationBasicType[]
) => (keyId: string) => boolean
getRestrictedOrganizationsForKey: (
allOrganizations: OrganizationBasicType[],
keys: PersonalAPIKeyType[],
getRestrictedTeamsForKey: (keyId: string) => TeamBasicType[]
) => (keyId: string) => OrganizationBasicType[]
getRestrictedTeamsForKey: (
allOrganizations: OrganizationBasicType[],
allTeams: TeamBasicType[] | null,
keys: PersonalAPIKeyType[]
) => (keyId: string) => TeamBasicType[]
}
}
export type personalAPIKeysLogicType = MakeLogicType<
personalAPIKeysLogicValues,
personalAPIKeysLogicActions,
Record<string, any>,
personalAPIKeysLogicMeta
>
export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
path(['lib', 'components', 'PersonalAPIKeys', 'personalAPIKeysLogic']),
connect(() => ({
values: [userLogic, ['user', 'hasAvailableFeature'], featureFlagLogic, ['featureFlags']],
})),
actions({
setEditingKeyId: (id: PersonalAPIKeyType['id'] | null) => ({ id }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
loadKeys: true,
createKeySuccess: (key: PersonalAPIKeyType) => ({ key }),
showRollKeySuccessDialog: (key: PersonalAPIKeyType, prevMaskedValue?: string | null) => ({
key,
prevMaskedValue,
}),
updateKey: (data: Partial<Pick<PersonalAPIKeyType, 'label' | 'scopes'>>) => data,
deleteKey: (id: PersonalAPIKeyType['id']) => ({ id }),
// `expiresAt` undefined keeps the key's current expiry; null removes it.
rollKey: (id: PersonalAPIKeyType['id'], expiresAt?: string | null) => ({ id, expiresAt }),
setScopeRadioValue: (key: string, action: string) => ({ key, action }),
setScopeGroupAccess: (keys: string[], level: ScopeAccessLevel) => ({ keys, level }),
resetScopes: true,
loadAllTeams: true,
showDescriptionField: true,
}),
reducers({
editingKeyId: [
null as PersonalAPIKeyType['id'] | null,
{
setEditingKeyId: (_, { id }) => id,
},
],
searchTerm: [
'' as string,
{
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
],
// The description field is hidden behind an "Add description" button until used
isDescriptionFieldVisible: [
false,
{
showDescriptionField: () => true,
setEditingKeyId: () => false,
},
],
}),
loaders(({ values, actions }) => ({
keys: [
[] as PersonalAPIKeyType[],
{
loadKeys: async () => {
return await api.personalApiKeys.list()
},
deleteKey: async ({ id }) => {
try {
await api.personalApiKeys.delete(id)
} catch (error) {
// A 404 means the signed-in user has no key with this id, usually because another tab
// already deleted it. The row is stale, so remove it. Otherwise every later delete click
// on the row fails with the same error. A list reload here could finish after a later
// delete and put that key back, so only this row changes.
if (!(error instanceof ApiError && error.status === 404)) {
throw error
}
}
return values.keys.filter((filteredKey) => filteredKey.id != id)
},
rollKey: async ({ id, expiresAt }) => {
const origKey = values.keys.find((filteredKey) => filteredKey.id == id)
if (!origKey) {
return values.keys
}
const rolledKey = await api.personalApiKeys.roll(
id,
expiresAt !== undefined ? { expires_at: expiresAt } : {}
)
actions.showRollKeySuccessDialog(rolledKey, origKey.mask_value)
// avoid persisting the raw value in state
rolledKey.value = undefined
return values.keys.map((filteredKey) => (filteredKey.id == id ? rolledKey : filteredKey))
},
},
],
allTeams: [
null as TeamBasicType[] | null,
{
loadAllTeams: async () => {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
return await api.loadPaginatedResults('api/projects')
},
},
],
})),
forms(({ values, actions }) => ({
editingKey: {
defaults: {
label: '',
description: '',
scopes: [],
scoped_organizations: [],
scoped_teams: [],
access_type: undefined,
expiration: 'never',
} as EditingKeyFormValues,
errors: ({ label, access_type, scopes, scoped_organizations, scoped_teams }) => ({
label: !label ? 'Your personal API key needs a label' : undefined,
scopes: !scopes?.length ? ('Your personal API key needs at least one scope' as any) : undefined,
access_type: !access_type ? ('Select access mode' as any) : undefined,
scoped_organizations:
access_type === 'organizations' && !scoped_organizations?.length
? ('Select at least one organization' as any)
: undefined,
scoped_teams:
access_type === 'teams' && !scoped_teams?.length
? ('Select at least one project' as any)
: undefined,
}),
submit: async (payload, breakpoint) => {
if (!values.editingKeyId) {
return
}
// Sanitize scopes against `allowedScopeKeys` so flag-gated scopes
// (e.g. `llm_gateway`) can't slip through via presets like
// "Read-only access" that expand to every scope in API_SCOPES.
// `*` (all access) is preserved as-is.
const allowed = values.allowedScopeKeys
const sanitizedScopes =
payload.scopes?.filter((scope) => {
if (scope === '*') {
return true
}
const [object] = scope.split(':')
return !!object && allowed.has(object)
}) ?? []
const { expiration, ...rest } = payload
const expiresAt = expiresAtForOption(expiration)
const sanitizedPayload = {
...rest,
scopes: sanitizedScopes,
...(expiresAt !== undefined ? { expires_at: expiresAt } : {}),
}
const key =
values.editingKeyId === 'new'
? await api.personalApiKeys.create(sanitizedPayload)
: await api.personalApiKeys.update(values.editingKeyId, sanitizedPayload)
breakpoint()
if (values.editingKeyId === 'new') {
actions.createKeySuccess(key)
}
actions.loadKeysSuccess([key].concat(values.keys.filter((k) => k.id !== values.editingKeyId)))
actions.setEditingKeyId(null)
},
},
})),
selectors(() => ({
allowedScopes: [
(s) => [s.featureFlags, s.hasAvailableFeature],
(
featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
): APIScope[] => {
let scopes = API_SCOPES
// Filter out llm_gateway scope if feature flag is disabled
if (!featureFlags[FEATURE_FLAGS.GATEWAY_PERSONAL_API_KEY]) {
scopes = scopes.filter((scope) => scope.key !== 'llm_gateway')
}
// Hide engineering analytics scope unless the product's rollout flag is enabled
if (!featureFlags[FEATURE_FLAGS.ENGINEERING_ANALYTICS]) {
scopes = scopes.filter((scope) => scope.key !== 'engineering_analytics')
}
// Hide approvals scope unless the org has the APPROVALS feature
if (!hasAvailableFeature(AvailableFeature.APPROVALS)) {
scopes = scopes.filter((scope) => scope.key !== 'approvals')
}
return scopes
},
],
allowedScopeKeys: [
(s) => [s.allowedScopes],
(allowedScopes: APIScope[]): Set<string> => new Set(allowedScopes.map((scope) => scope.key)),
],
scopeRows: [
(s) => [s.allowedScopes, s.formScopeRadioValues, s.editingKey],
(
allowedScopes: APIScope[],
formScopeRadioValues: Record<string, string>,
editingKey: EditingKeyFormValues
): PersonalAPIKeyScopeRow[] =>
allowedScopes.map((scope) => {
const projectScoped = scope.disabledWhenProjectScoped && editingKey.access_type === 'teams'
const disabledReason = (action: 'read' | 'write'): string | undefined =>
scope.disabledActions?.includes(action)
? 'Does not apply to this resource'
: projectScoped
? 'Not available for project scoped keys'
: undefined
const value = (formScopeRadioValues[scope.key] ?? 'none') as ScopeAccessLevel
return {
scope,
key: scope.key,
label: scope.objectName,
info: scope.info,
value,
warning: scopeRowWarning(scope, scope.key, value),
muted: Boolean(projectScoped),
disabledReasons: { read: disabledReason('read'), write: disabledReason('write') },
}
}),
],
filteredScopeGroups: [
(s) => [s.searchTerm, s.scopeRows],
(searchTerm: string, scopeRows: PersonalAPIKeyScopeRow[]): PersonalAPIKeyScopeGroup[] =>
groupScopeRows(scopeRows.filter((row) => scopeMatchesSearch(row.scope, searchTerm))),
],
formScopeRadioValues: [
(s) => [s.editingKey],
(editingKey: EditingKeyFormValues): Record<string, string> => {
return scopesArrayToObject(editingKey.scopes)
},
],
allAccessSelected: [
(s) => [s.editingKey],
(editingKey: EditingKeyFormValues): boolean => {
return editingKey.scopes.includes('*')
},
],
isEditingKeyLegacy: [
(s) => [s.editingKeyId, s.keys],
(editingKeyId: PersonalAPIKeyType['id'] | null, keys: PersonalAPIKeyType[]): boolean => {
if (!editingKeyId || editingKeyId === 'new') {
return false
}
const key = keys.find((k) => k.id === editingKeyId)
return key?.is_legacy_hashing ?? false
},
],
allOrganizations: [
(s) => [s.user],
(user: UserType | null): OrganizationBasicType[] => {
return user?.organizations ?? []
},
],
canUsePersonalApiKeys: [
(s) => [s.user],
(user: UserType | null): boolean => {
const currentOrg = user?.organization
if (!currentOrg) {
return true
}
if (currentOrg.membership_level && currentOrg.membership_level >= OrganizationMembershipLevel.Admin) {
return true
}
return organizationAllowsPersonalApiKeysForMembers(currentOrg)
},
],
isPersonalApiKeyIdDisabled: [
(s) => [s.allOrganizations, s.allTeams, s.keys, s.getRestrictedOrganizationsForKey],
(
allOrganizations: OrganizationBasicType[],
allTeams: TeamBasicType[] | null,
keys: PersonalAPIKeyType[],
getRestrictedOrganizationsForKey: (keyId: PersonalAPIKeyType['id']) => OrganizationBasicType[]
) =>
(keyId: PersonalAPIKeyType['id']): boolean => {
const key = keys.find((k) => k.id === keyId)
if (!key) {
return false
}
const restrictedOrgs = getRestrictedOrganizationsForKey(keyId)
// If key is scoped to specific organizations
if (key.scoped_organizations?.length) {
// Key is disabled if ALL scoped organizations are restricted
return restrictedOrgs.length === key.scoped_organizations.length
}
// If key is scoped to specific teams
if (key.scoped_teams?.length && allTeams) {
// Get unique organization IDs from scoped teams
const teamOrgIds = new Set<string>()
key.scoped_teams.forEach((teamId) => {
const team = allTeams.find((t) => t.id === teamId)
if (team?.organization) {
teamOrgIds.add(team.organization)
}
})
// Key is disabled if ALL team organizations are restricted
return restrictedOrgs.length === teamOrgIds.size
}
// If key has all access, it's disabled if ALL user's organizations are restricted
return restrictedOrgs.length === allOrganizations.length
},
],
getRestrictedOrganizationsForKey: [
(s) => [s.allOrganizations, s.keys, s.getRestrictedTeamsForKey],
(
allOrganizations: OrganizationBasicType[],
keys: PersonalAPIKeyType[],
getRestrictedTeamsForKey: (keyId: PersonalAPIKeyType['id']) => TeamBasicType[]
) =>
(keyId: PersonalAPIKeyType['id']): OrganizationBasicType[] => {
let restrictedOrgs: OrganizationBasicType[] = []
const key = keys.find((k) => k.id === keyId)
if (!key) {
return []
}
// If key is scoped to specific organizations
if (key.scoped_organizations?.length) {
restrictedOrgs = (key.scoped_organizations || [])
.map((orgId) => {
const org = allOrganizations.find((o) => o.id === orgId)
if (
org &&
!hasMembershipLevelOrHigher(org, OrganizationMembershipLevel.Admin) &&
!organizationAllowsPersonalApiKeysForMembers(org)
) {
return org
}
})
.filter((x) => x) as OrganizationBasicType[]
return restrictedOrgs
}
// If key is scoped to specific teams
if (key.scoped_teams?.length) {
const restrictedTeams = getRestrictedTeamsForKey(keyId)
const orgIds = new Set<string>()
restrictedTeams.forEach((team) => {
if (team.organization) {
orgIds.add(team.organization)
}
})
restrictedOrgs = Array.from(orgIds)
.map((orgId) => allOrganizations.find((o) => o.id === orgId))
.filter((org) => org) as OrganizationBasicType[]
return restrictedOrgs
}
// If key has all access, check all user's organizations
allOrganizations.forEach((org) => {
if (
!hasMembershipLevelOrHigher(org, OrganizationMembershipLevel.Admin) &&
!organizationAllowsPersonalApiKeysForMembers(org)
) {
restrictedOrgs.push(org)
}
})
return restrictedOrgs
},
],
getRestrictedTeamsForKey: [
(s) => [s.allOrganizations, s.allTeams, s.keys],
(allOrganizations: OrganizationBasicType[], allTeams: TeamBasicType[] | null, keys: PersonalAPIKeyType[]) =>
(keyId: PersonalAPIKeyType['id']): TeamBasicType[] => {
const key = keys.find((k) => k.id === keyId)
if (!key || !allTeams || !key.scoped_teams?.length) {
return []
}
return key.scoped_teams
.map((teamId) => {
const team = allTeams.find((t: TeamBasicType) => t.id === teamId)
if (team?.organization) {
const org = allOrganizations.find((o) => o.id === team.organization)
if (
org &&
!hasMembershipLevelOrHigher(org, OrganizationMembershipLevel.Admin) &&
!organizationAllowsPersonalApiKeysForMembers(org)
) {
return team
}
}
})
.filter((team) => team) as TeamBasicType[]
},
],
})),
listeners(({ actions, values }) => ({
touchEditingKeyField: ({ key }) => {
if (key === 'label') {
// If the label contains a prefillable preset, set the preset and access type
const prefillablePresets = ['zapier', 'n8n']
for (const preset of prefillablePresets) {
if (values.editingKey.label.toLowerCase().includes(preset) && !values.editingKey.preset) {
actions.setEditingKeyValue('preset', preset)
actions.setEditingKeyValue('access_type', 'all')
}
}
}
},
submitEditingKeyFailure: ({ error }) => {
// kea-forms swallows the rejected API call, so the server's message has to be copied to the form here
if (!(error instanceof ApiError)) {
return
}
if (error.attr && error.attr in values.editingKey) {
actions.setEditingKeyManualErrors({ [error.attr]: error.detail || error.message })
} else {
lemonToast.error(error.detail || 'Could not save the personal API key. Try again.')
}
},
setEditingKeyValue: async ({ name, value }) => {
const key = Array.isArray(name) ? name[0] : name
// kea-forms only drops a manual error on blur, and a stale one blocks a resubmit from the Enter key
if (key in values.editingKeyManualErrors) {
const { [key]: _stale, ...remainingErrors } = values.editingKeyManualErrors
actions.setEditingKeyManualErrors(remainingErrors)
}
// When we select a preset, update the scopes
if (key === 'preset' && value) {
const preset = API_KEY_SCOPE_PRESETS.find((preset) => preset.value === value)
if (preset) {
actions.setEditingKeyValue('scopes', preset.scopes)
}
}
// When the user deviates from the preset, clear it
if (key === 'scopes' && values.editingKey.preset) {
const preset = API_KEY_SCOPE_PRESETS.find((preset) => preset.value === values.editingKey.preset)
if (preset?.scopes.join(',') !== value.join(',')) {
actions.setEditingKeyValue('preset', undefined)
}
}
// When the user changes the list of valid orgs, clear the teams
if (key === 'access_type') {
actions.setEditingKeyValue('scoped_teams', [])
actions.setEditingKeyValue('scoped_organizations', [])
}
},
setEditingKeyId: async ({ id }) => {
if (id) {
const key = values.keys.find((key) => key.id === id)
const formValues: EditingKeyFormValues = {
label: key?.label ?? '',
description: key?.description ?? '',
scopes: key?.scopes ?? [],
preset: key?.scopes.includes('*') ? 'all_access' : undefined,
scoped_organizations: key?.scoped_organizations ?? [],
scoped_teams: key?.scoped_teams ?? [],
access_type: key?.scoped_organizations?.length
? 'organizations'
: key?.scoped_teams?.length
? 'teams'
: id !== 'new'
? 'all'
: undefined,
expiration: key?.expires_at ? 'keep' : 'never',
}
actions.resetEditingKey(formValues)
if (key?.description) {
actions.showDescriptionField()
}
actions.setSearchTerm('')
} else {
actions.setSearchTerm('')
}
},
resetScopes: () => {
actions.setEditingKeyValue('scopes', [])
},
setScopeRadioValue: ({ key, action }) => {
actions.setEditingKeyValue(
'scopes',
withScopeLevels(values.editingKey.scopes, [[key, action as ScopeAccessLevel]])
)
},
// A group action clamps each row to the levels it can take, so a group set to write holds a
// read-only row at read and a project-scoped row at none.
setScopeGroupAccess: ({ keys, level }) => {
const rowsByKey = new Map<string, PersonalAPIKeyScopeRow>(values.scopeRows.map((row) => [row.key, row]))
const levels = keys.flatMap((key): [string, ScopeAccessLevel][] => {
const row = rowsByKey.get(key)
return row ? [[key, clampScopeLevel(row, level)]] : []
})
actions.setEditingKeyValue('scopes', withScopeLevels(values.editingKey.scopes, levels))
},
createKeySuccess: async ({ key }) => {
const value = key.value
if (!value) {
return
}
LemonDialog.open({
title: 'Personal API key ready',
width: 536,
zIndex: '1168',
content: (
<>
<p className="mb-4">You can now use key "{key.label}" for authentication:</p>
<CodeSnippet className="ph-no-capture" thing="personal API key">
{value}
</CodeSnippet>
<LemonBanner type="warning" className="mt-4">
For security reasons the value above <em>will never be shown again</em>.
<br />
Copy it to your destination right away.
</LemonBanner>
</>
),
})
},
showRollKeySuccessDialog: async ({ key, prevMaskedValue }) => {
const value = key.value
if (!value) {
return
}
LemonDialog.open({
title: 'Personal API key rolled',
width: 536,
content: (
<>
<p className="mb-4">Your key "{key.label}" has been rolled:</p>
<CodeSnippet className="ph-no-capture" thing="personal API key">
{value}
</CodeSnippet>
<LemonBanner type="warning" className="mt-4">
Your previous key{prevMaskedValue ? ` "${prevMaskedValue}"` : ''} is no longer valid.
</LemonBanner>
</>
),
})
},
deleteKeySuccess: () => {
lemonToast.success(`Personal API key deleted`)
},
})),
urlToAction(({ actions }) => ({
[urls.settings('user-api-keys')]: (_, searchParams) => {
const presetKey = searchParams.preset
if (presetKey) {
const preset = API_KEY_SCOPE_PRESETS.find((preset) => preset.value === presetKey)
if (preset) {
actions.setEditingKeyId('new')
actions.setEditingKeyValues({
preset: preset.value,
label: preset.label,
scopes: preset.scopes,
access_type: preset.access_type,
})
}
}
},
})),
actionToUrl(() => ({
setEditingKeyId: ({ id }) => {
if (!id) {
// When the modal is closed, remove the preset from the URL
const { preset, ...searchParams } = router.values.searchParams
return [router.values.location.pathname, searchParams, router.values.location.hash]
}
},
})),
afterMount(({ actions }) => {
actions.loadAllTeams()
}),
])