(params: {
workspaceId: string
userId: string
name: string
})
| 165 | } |
| 166 | |
| 167 | export async function createWorkspaceApiKey(params: { |
| 168 | workspaceId: string |
| 169 | userId: string |
| 170 | name: string |
| 171 | }) { |
| 172 | const existingKey = await db |
| 173 | .select({ id: apiKey.id }) |
| 174 | .from(apiKey) |
| 175 | .where( |
| 176 | and( |
| 177 | eq(apiKey.workspaceId, params.workspaceId), |
| 178 | eq(apiKey.name, params.name), |
| 179 | eq(apiKey.type, 'workspace') |
| 180 | ) |
| 181 | ) |
| 182 | .limit(1) |
| 183 | |
| 184 | if (existingKey.length > 0) { |
| 185 | throw new Error( |
| 186 | `A workspace API key named "${params.name}" already exists. Choose a different name.` |
| 187 | ) |
| 188 | } |
| 189 | |
| 190 | const { key: plainKey, encryptedKey } = await createApiKey(true) |
| 191 | if (!encryptedKey) { |
| 192 | throw new Error('Failed to encrypt API key for storage') |
| 193 | } |
| 194 | |
| 195 | const [newKey] = await db |
| 196 | .insert(apiKey) |
| 197 | .values({ |
| 198 | id: generateShortId(), |
| 199 | workspaceId: params.workspaceId, |
| 200 | userId: params.userId, |
| 201 | createdBy: params.userId, |
| 202 | name: params.name, |
| 203 | key: encryptedKey, |
| 204 | keyHash: hashApiKey(plainKey), |
| 205 | type: 'workspace', |
| 206 | createdAt: new Date(), |
| 207 | updatedAt: new Date(), |
| 208 | }) |
| 209 | .returning({ id: apiKey.id, name: apiKey.name, createdAt: apiKey.createdAt }) |
| 210 | |
| 211 | return { id: newKey.id, name: newKey.name, key: plainKey, createdAt: newKey.createdAt } |
| 212 | } |
no test coverage detected