Files
WeHub Mirror 6bf8bebf51
CI / Test and Build (push) Failing after 1s
CI / Migrate Dev DB (push) Has been skipped
CI / Migrate DB (push) Has been skipped
CodeQL / Analyze actions (push) Has been cancelled
CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI / Detect Version (push) Has been cancelled
CI / Detect Desktop Changes (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/cron.Dockerfile, ubuntu-latest, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build AMD64 (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/cron.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/db.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/pii.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/realtime.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-8vcpu-ubuntu-2404-arm, ./docker/app.Dockerfile, linux-arm64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
Helm Chart / Lint, test, and validate chart (push) Has been cancelled
Helm Chart / Chart version bumped (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Build Dev ECR (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core) (push) Has been cancelled
CI / Promote Images (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Check Desktop Signing Secrets (push) Has been cancelled
CI / Desktop Release (push) Has been cancelled
CI / Create Desktop Prerelease (push) Has been cancelled
CI / Desktop Prerelease Build (push) Has been cancelled
CI / Publish Desktop Prerelease (push) Has been cancelled
CI / Prune Desktop Prereleases (push) Has been cancelled
Helm Chart / Install on kind and run helm test (push) Has been cancelled
WeHub snapshot of cb28d14c6f2c081de7a0d8729a8c816c9adef67a
2026-08-10 11:17:50 +08:00

217 lines
7.2 KiB
TypeScript

import { db } from '@sim/db'
import { account, credential, credentialMember, credentialTypeEnum } from '@sim/db/schema'
import { and, eq, inArray } from 'drizzle-orm'
import type { DbOrTx } from '@/lib/db/types'
import {
getUserEntityPermissions,
resolveWorkspaceAccess,
type WorkspaceAccess,
} from '@/lib/workspaces/permissions/utils'
type ActiveCredentialMember = typeof credentialMember.$inferSelect
type CredentialRecord = typeof credential.$inferSelect
export type CredentialType = (typeof credentialTypeEnum.enumValues)[number]
/**
* Credential types shared at the workspace level — every type except a user's
* personal env vars. Derived from the enum so a newly added credential type is
* treated as shared by default, keeping visibility, role, and admin derivation
* consistent instead of drifting against a hand-maintained inclusion list.
*/
export const SHARED_CREDENTIAL_TYPES = credentialTypeEnum.enumValues.filter(
(type) => type !== 'env_personal'
)
/**
* Which user a credential's token must be read as.
*
* Service-account credentials mint their own token and ignore the acting user
* entirely, so they carry no user id — callers pass their existing one through.
*/
export type CredentialTokenIdentity =
| { kind: 'service_account' }
| { kind: 'oauth'; userId: string }
/**
* Resolves which user a credential's token must be read as, for background jobs
* that run without a request context (connector syncs, scheduled runs).
*
* Workspace-scoped OAuth credentials are shared, so the member who authorized one
* is frequently not the user driving the job. Token reads are scoped to
* `account.userId`, so a job passing its own user id resolves no token at all.
* Mirrors the ownership resolution in `authorizeCredentialUse`: the credential must
* belong to `workspaceId`, and its owner must still have access to that workspace.
*
* @returns the identity to read the token as, or `null` when the credential is
* unusable from this workspace (wrong workspace, missing account, owner lost access).
*/
export async function resolveCredentialTokenIdentity(
credentialId: string,
workspaceId: string
): Promise<CredentialTokenIdentity | null> {
const [platformCredential] = await db
.select({
workspaceId: credential.workspaceId,
type: credential.type,
accountId: credential.accountId,
})
.from(credential)
.where(eq(credential.id, credentialId))
.limit(1)
if (platformCredential) {
if (platformCredential.workspaceId !== workspaceId) return null
if (platformCredential.type === 'service_account') return { kind: 'service_account' }
if (platformCredential.type !== 'oauth' || !platformCredential.accountId) return null
}
// Credentials predating the workspace-scoped `credential` table are raw account ids.
const accountId = platformCredential?.accountId ?? credentialId
const [accountRow] = await db
.select({ userId: account.userId })
.from(account)
.where(eq(account.id, accountId))
.limit(1)
if (!accountRow) return null
const ownerPerm = await getUserEntityPermissions(accountRow.userId, 'workspace', workspaceId)
if (ownerPerm === null) return null
return { kind: 'oauth', userId: accountRow.userId }
}
/** Whether a credential is shared at the workspace level (i.e. not a personal env var). */
export function isSharedCredentialType(type: CredentialType): boolean {
return type !== 'env_personal'
}
/**
* Whether a user is an admin of a credential: an explicit credential-member admin,
* or — for shared credentials only — a workspace admin (workspace admins are
* derived credential admins, but never for personal env vars).
*/
export function deriveCredentialAdmin(params: {
credentialType: CredentialType
memberRole: ActiveCredentialMember['role'] | null | undefined
workspaceCanAdmin: boolean
}): boolean {
return (
params.memberRole === 'admin' ||
(isSharedCredentialType(params.credentialType) && params.workspaceCanAdmin)
)
}
export interface CredentialActorContext {
credential: CredentialRecord | null
member: ActiveCredentialMember | null
hasWorkspaceAccess: boolean
canWriteWorkspace: boolean
isAdmin: boolean
}
/**
* Resolves user access context for a credential. Pass `workspaceAccess` when the
* caller has already resolved access for the credential's workspace to skip a
* redundant lookup; it is reused only when it matches the credential's workspace.
*/
export async function getCredentialActorContext(
credentialId: string,
userId: string,
options?: { workspaceAccess?: WorkspaceAccess }
): Promise<CredentialActorContext> {
const [credentialRow] = await db
.select()
.from(credential)
.where(eq(credential.id, credentialId))
.limit(1)
if (!credentialRow) {
return {
credential: null,
member: null,
hasWorkspaceAccess: false,
canWriteWorkspace: false,
isAdmin: false,
}
}
const workspaceAccess = await resolveWorkspaceAccess(
credentialRow.workspaceId,
userId,
options?.workspaceAccess
)
const [memberRow] = await db
.select()
.from(credentialMember)
.where(
and(
eq(credentialMember.credentialId, credentialId),
eq(credentialMember.userId, userId),
eq(credentialMember.status, 'active')
)
)
.limit(1)
const isAdmin = deriveCredentialAdmin({
credentialType: credentialRow.type,
memberRole: memberRow?.role,
workspaceCanAdmin: workspaceAccess.canAdmin,
})
return {
credential: credentialRow,
member: memberRow ?? null,
hasWorkspaceAccess: workspaceAccess.hasAccess,
canWriteWorkspace: workspaceAccess.canWrite,
isAdmin,
}
}
/**
* Revokes all credential memberships for a user across one or more workspaces.
* Workspace owners and admins are derived credential admins, so no per-credential
* owner promotion is needed to avoid orphaning a credential. Returns the number
* of memberships revoked.
*
* Deliberately DIVERGES from the skill sibling (`removeWorkspaceSkillMembershipsTx`
* deletes active rows): credential access is explicit-rows-only, so a revoked
* row here is an inert tombstone the env-credential join sync uses to avoid
* resurrecting access. Skills have an implicit workspace-shared grant, where a
* revoked row is a live per-skill DENY marker and a kept-active row would
* re-grant on rejoin — do not "harmonize" either helper toward the other.
*/
export async function revokeWorkspaceCredentialMembershipsTx(
tx: DbOrTx,
workspaceId: string | string[],
userId: string
): Promise<number> {
const workspaceIds = Array.isArray(workspaceId) ? workspaceId : [workspaceId]
if (workspaceIds.length === 0) return 0
const workspaceCredentialIds = await tx
.select({ id: credential.id })
.from(credential)
.where(inArray(credential.workspaceId, workspaceIds))
if (workspaceCredentialIds.length === 0) return 0
const credIds = workspaceCredentialIds.map((c) => c.id)
const revoked = await tx
.update(credentialMember)
.set({ status: 'revoked', updatedAt: new Date() })
.where(
and(
eq(credentialMember.userId, userId),
eq(credentialMember.status, 'active'),
inArray(credentialMember.credentialId, credIds)
)
)
.returning({ id: credentialMember.id })
return revoked.length
}