1 import {
2 ApiKeyTypes,
3 Context,
4 DAL,
5 FilterableApiKeyProps,
6 FindConfig,
7 IApiKeyModuleService,
8 InferEntityType,
9 InternalModuleDeclaration,
10 ModuleJoinerConfig,
11 ModulesSdkTypes,
12 } from "@medusajs/framework/types"
13 import {
14 ApiKeyType,
15 EmitEvents,
16 InjectManager,
17 InjectTransactionManager,
18 isObject,
19 isPresent,
20 isString,
21 MedusaContext,
22 MedusaError,
23 MedusaService,
24 promiseAll,
25 } from "@medusajs/framework/utils"
26 import { ApiKey } from "@models"
27 import {
28 CreateApiKeyDTO,
29 RevokeApiKeyInput,
30 TokenDTO,
31 UpdateApiKeyInput,
32 } from "@types"
33 import crypto from "crypto"
34 import util from "util"
35 import { joinerConfig } from "../joiner-config"
36
37 const scrypt = util.promisify(crypto.scrypt)
38
39 type InjectedDependencies = {
40 baseRepository: DAL.RepositoryService
41 apiKeyService: ModulesSdkTypes.IMedusaInternalService<any>
42 }
43
44 export class ApiKeyModuleService
45 extends MedusaService<{
46 ApiKey: { dto: ApiKeyTypes.ApiKeyDTO }
47 }>({ ApiKey })
48 implements IApiKeyModuleService
49 {
50 protected baseRepository_: DAL.RepositoryService
51 protected readonly apiKeyService_: ModulesSdkTypes.IMedusaInternalService<
52 InferEntityType<typeof ApiKey>
53 >
54
55 constructor(
56 { baseRepository, apiKeyService }: InjectedDependencies,
57 protected readonly moduleDeclaration: InternalModuleDeclaration
58 ) {
59 // @ts-ignore
60 super(...arguments)
61 this.baseRepository_ = baseRepository
62 this.apiKeyService_ = apiKeyService
63 }
64
65 __joinerConfig(): ModuleJoinerConfig {
66 return joinerConfig
67 }
68
69 @InjectManager()
70 @EmitEvents()
71 // @ts-expect-error
72 async deleteApiKeys(
73 ids: string | string[],
74 @MedusaContext() sharedContext: Context = {}
75 ) {
76 return await this.deleteApiKeys_(ids, sharedContext)
77 }
78
79 @InjectTransactionManager()
80 protected async deleteApiKeys_(
81 ids: string | string[],
82 @MedusaContext() sharedContext: Context = {}
83 ) {
84 const apiKeyIds = Array.isArray(ids) ? ids : [ids]
85
86 const unrevokedApiKeys = (
87 await this.apiKeyService_.list(
88 {
89 id: ids,
90 $or: [
91 { revoked_at: { $eq: null } },
92 { revoked_at: { $gt: new Date() } },
93 ],
94 },
95 { select: ["id"] },
96 sharedContext
97 )
98 ).map((apiKey) => apiKey.id)
99
100 if (isPresent(unrevokedApiKeys)) {
101 throw new MedusaError(
102 MedusaError.Types.NOT_ALLOWED,
103 `Cannot delete api keys that are not revoked - ${unrevokedApiKeys.join(
104 ", "
105 )}`
106 )
107 }
108
109 return await super.deleteApiKeys(apiKeyIds, sharedContext)
110 }
111
112 //@ts-expect-error
113 createApiKeys(
114 data: ApiKeyTypes.CreateApiKeyDTO[],
115 sharedContext?: Context
116 ): Promise<ApiKeyTypes.ApiKeyDTO[]>
117 //@ts-expect-error
118 createApiKeys(
119 data: ApiKeyTypes.CreateApiKeyDTO,
120 sharedContext?: Context
121 ): Promise<ApiKeyTypes.ApiKeyDTO>
122
123 @InjectManager()
124 @EmitEvents()
125 //@ts-expect-error
126 async createApiKeys(
127 data: ApiKeyTypes.CreateApiKeyDTO | ApiKeyTypes.CreateApiKeyDTO[],
128 @MedusaContext() sharedContext: Context = {}
129 ): Promise<ApiKeyTypes.ApiKeyDTO | ApiKeyTypes.ApiKeyDTO[]> {
130 const [createdApiKeys, generatedTokens] = await this.createApiKeys_(
131 Array.isArray(data) ? data : [data],
132 sharedContext
133 )
134
135 const serializedResponse = await this.baseRepository_.serialize<
136 ApiKeyTypes.ApiKeyDTO[]
137 >(createdApiKeys, {
138 populate: true,
139 })
140
141 // When creating we want to return the raw token, as this will be the only time the user will be able to take note of it for future use.
142 const responseWithRawToken = serializedResponse.map((key) => ({
143 ...key,
144 token:
145 generatedTokens.find((t) => t.hashedToken === key.token)?.rawToken ??
146 key.token,
147 salt: undefined,
148 }))
149
150 return Array.isArray(data) ? responseWithRawToken : responseWithRawToken[0]
151 }
152
153 @InjectTransactionManager()
154 protected async createApiKeys_(
155 data: ApiKeyTypes.CreateApiKeyDTO[],
156 @MedusaContext() sharedContext: Context = {}
157 ): Promise<[InferEntityType<typeof ApiKey>[], TokenDTO[]]> {
158 const normalizedInput: CreateApiKeyDTO[] = []
159 const generatedTokens: TokenDTO[] = []
160 for (const key of data) {
161 let tokenData: TokenDTO
162 if (key.type === ApiKeyType.PUBLISHABLE) {
163 tokenData = ApiKeyModuleService.generatePublishableKey()
164 } else {
165 tokenData = await ApiKeyModuleService.generateSecretKey()
166 }
167
168 generatedTokens.push(tokenData)
169 normalizedInput.push({
170 ...key,
171 token: tokenData.hashedToken,
172 salt: tokenData.salt,
173 redacted: tokenData.redacted,
174 })
175 }
176
177 const createdApiKeys = await this.apiKeyService_.create(
178 normalizedInput,
179 sharedContext
180 )
181
182 return [createdApiKeys, generatedTokens]
183 }
184
185 async upsertApiKeys(
186 data: ApiKeyTypes.UpsertApiKeyDTO[],
187 sharedContext?: Context
188 ): Promise<ApiKeyTypes.ApiKeyDTO[]>
189 async upsertApiKeys(
190 data: ApiKeyTypes.UpsertApiKeyDTO,
191 sharedContext?: Context
192 ): Promise<ApiKeyTypes.ApiKeyDTO>
193
194 @InjectManager()
195 @EmitEvents()
196 async upsertApiKeys(
197 data: ApiKeyTypes.UpsertApiKeyDTO | ApiKeyTypes.UpsertApiKeyDTO[],
198 @MedusaContext() sharedContext: Context = {}
199 ): Promise<ApiKeyTypes.ApiKeyDTO | ApiKeyTypes.ApiKeyDTO[]> {
200 const result = await this.upsertApiKeys_(data, sharedContext)
201
202 return await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO[]>(result)
203 }
204
205 @InjectTransactionManager()
206 protected async upsertApiKeys_(
207 data: ApiKeyTypes.UpsertApiKeyDTO | ApiKeyTypes.UpsertApiKeyDTO[],
208 @MedusaContext() sharedContext: Context = {}
209 ): Promise<ApiKeyTypes.ApiKeyDTO | ApiKeyTypes.ApiKeyDTO[]> {
210 const input = Array.isArray(data) ? data : [data]
211 const forUpdate = input.filter(
212 (apiKey): apiKey is UpdateApiKeyInput => !!apiKey.id
213 )
214 const forCreate = input.filter(
215 (apiKey): apiKey is ApiKeyTypes.CreateApiKeyDTO => !apiKey.id
216 )
217
218 const operations: Promise<ApiKeyTypes.ApiKeyDTO[]>[] = []
219
220 if (forCreate.length) {
221 const op = async () => {
222 const [createdApiKeys, generatedTokens] = await this.createApiKeys_(
223 forCreate,
224 sharedContext
225 )
226 const serializedResponse = await this.baseRepository_.serialize<
227 ApiKeyTypes.ApiKeyDTO[]
228 >(createdApiKeys)
229
230 return serializedResponse.map(
231 (key) =>
232 ({
233 ...key,
234 token:
235 generatedTokens.find((t) => t.hashedToken === key.token)
236 ?.rawToken ?? key.token,
237 salt: undefined,
238 } as ApiKeyTypes.ApiKeyDTO)
239 )
240 }
241
242 operations.push(op())
243 }
244
245 if (forUpdate.length) {
246 const op = async () => {
247 return await this.updateApiKeys_(forUpdate, sharedContext)
248 }
249
250 operations.push(op())
251 }
252
253 const result = (await promiseAll(operations)).flat()
254 return Array.isArray(data) ? result : result[0]
255 }
256
257 //@ts-expect-error
258 async updateApiKeys(
259 id: string,
260 data: ApiKeyTypes.UpdateApiKeyDTO,
261 sharedContext?: Context
262 ): Promise<ApiKeyTypes.ApiKeyDTO>
263 //@ts-expect-error
264 async updateApiKeys(
265 selector: FilterableApiKeyProps,
266 data: ApiKeyTypes.UpdateApiKeyDTO,
267 sharedContext?: Context
268 ): Promise<ApiKeyTypes.ApiKeyDTO[]>
269
270 @InjectManager()
271 @EmitEvents()
272 //@ts-expect-error
273 async updateApiKeys(
274 idOrSelector: string | FilterableApiKeyProps,
275 data: ApiKeyTypes.UpdateApiKeyDTO,
276 @MedusaContext() sharedContext: Context = {}
277 ): Promise<ApiKeyTypes.ApiKeyDTO[] | ApiKeyTypes.ApiKeyDTO> {
278 let normalizedInput = await this.normalizeUpdateInput_<UpdateApiKeyInput>(
279 idOrSelector,
280 data,
281 sharedContext
282 )
283
284 const updatedApiKeys = await this.updateApiKeys_(
285 normalizedInput,
286 sharedContext
287 )
288
289 const serializedResponse = await this.baseRepository_.serialize<
290 ApiKeyTypes.ApiKeyDTO[]
291 >(updatedApiKeys.map(omitToken), {
292 populate: true,
293 })
294
295 return isString(idOrSelector) ? serializedResponse[0] : serializedResponse
296 }
297
298 @InjectTransactionManager()
299 protected async updateApiKeys_(
300 normalizedInput: UpdateApiKeyInput[],
301 @MedusaContext() sharedContext: Context = {}
302 ): Promise<InferEntityType<typeof ApiKey>[]> {
303 const updateRequest = normalizedInput.map((k) => ({
304 id: k.id,
305 title: k.title,
306 }))
307
308 const updatedApiKeys = await this.apiKeyService_.update(
309 updateRequest,
310 sharedContext
311 )
312 return updatedApiKeys
313 }
314
315 @InjectManager()
316 // @ts-expect-error
317 async retrieveApiKey(
318 id: string,
319 config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
320 sharedContext?: Context
321 ): Promise<ApiKeyTypes.ApiKeyDTO> {
322 const apiKey = await this.apiKeyService_.retrieve(id, config, sharedContext)
323
324 return await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO>(
325 omitToken(apiKey),
326 {
327 populate: true,
328 }
329 )
330 }
331
332 @InjectManager()
333 //@ts-expect-error
334 async listApiKeys(
335 filters?: ApiKeyTypes.FilterableApiKeyProps,
336 config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
337 sharedContext?: Context
338 ): Promise<ApiKeyTypes.ApiKeyDTO[]> {
339 const apiKeys = await this.apiKeyService_.list(
340 filters,
341 config,
342 sharedContext
343 )
344
345 return await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO[]>(
346 apiKeys.map(omitToken),
347 {
348 populate: true,
349 }
350 )
351 }
352
353 @InjectManager()
354 //@ts-expect-error
355 async listAndCountApiKeys(
356 filters?: ApiKeyTypes.FilterableApiKeyProps,
357 config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
358 sharedContext?: Context
359 ): Promise<[ApiKeyTypes.ApiKeyDTO[], number]> {
360 const [apiKeys, count] = await this.apiKeyService_.listAndCount(
361 filters,
362 config,
363 sharedContext
364 )
365
366 return [
367 await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO[]>(
368 apiKeys.map(omitToken),
369 {
370 populate: true,
371 }
372 ),
373 count,
374 ]
375 }
376
377 async revoke(
378 id: string,
379 data: ApiKeyTypes.RevokeApiKeyDTO,
380 sharedContext?: Context
381 ): Promise<ApiKeyTypes.ApiKeyDTO>
382 async revoke(
383 selector: FilterableApiKeyProps,
384 data: ApiKeyTypes.RevokeApiKeyDTO,
385 sharedContext?: Context
386 ): Promise<ApiKeyTypes.ApiKeyDTO[]>
387
388 @InjectManager()
389 @EmitEvents()
390 async revoke(
391 idOrSelector: string | FilterableApiKeyProps,
392 data: ApiKeyTypes.RevokeApiKeyDTO,
393 @MedusaContext() sharedContext: Context = {}
394 ): Promise<ApiKeyTypes.ApiKeyDTO[] | ApiKeyTypes.ApiKeyDTO> {
395 const normalizedInput = await this.normalizeUpdateInput_<RevokeApiKeyInput>(
396 idOrSelector,
397 data,
398 sharedContext
399 )
400 const revokedApiKeys = await this.revoke_(normalizedInput, sharedContext)
401
402 const serializedResponse = await this.baseRepository_.serialize<
403 ApiKeyTypes.ApiKeyDTO[]
404 >(revokedApiKeys.map(omitToken), {
405 populate: true,
406 })
407
408 return isString(idOrSelector) ? serializedResponse[0] : serializedResponse
409 }
410
411 @InjectTransactionManager()
412 async revoke_(
413 normalizedInput: RevokeApiKeyInput[],
414 @MedusaContext() sharedContext: Context = {}
415 ): Promise<InferEntityType<typeof ApiKey>[]> {
416 await this.validateRevokeApiKeys_(normalizedInput)
417
418 const updateRequest = normalizedInput.map((k) => {
419 const revokedAt = new Date()
420 if (k.revoke_in && k.revoke_in > 0) {
421 revokedAt.setSeconds(revokedAt.getSeconds() + k.revoke_in)
422 }
423
424 return {
425 id: k.id,
426 revoked_at: revokedAt,
427 revoked_by: k.revoked_by,
428 }
429 })
430
431 const revokedApiKeys = await this.apiKeyService_.update(
432 updateRequest,
433 sharedContext
434 )
435
436 return revokedApiKeys
437 }
438
439 @InjectManager()
440 async authenticate(
441 token: string,
442 @MedusaContext() sharedContext: Context = {}
443 ): Promise<ApiKeyTypes.ApiKeyDTO | false> {
444 const result = await this.authenticate_(token, sharedContext)
445 if (!result) {
446 return false
447 }
448
449 const serialized =
450 await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO>(result, {
451 populate: true,
452 })
453
454 return serialized
455 }
456
457 @InjectTransactionManager()
458 protected async authenticate_(
459 token: string,
460 @MedusaContext() sharedContext: Context = {}
461 ): Promise<InferEntityType<typeof ApiKey> | false> {
462 const secretKeys = await this.apiKeyService_.list(
463 {
464 type: ApiKeyType.SECRET,
465 // There could be many unrevoked keys at the same time, so we narrow the list down by the redacted key.
466 // Note that the redacted key doesn't guarantee uniqueness and is not an authentication check, but just an optimization.
467 redacted: redactKey(token),
468 // If the revoke date is set in the future, it means the key is still valid.
469 $or: [
470 { revoked_at: { $eq: null } },
471 { revoked_at: { $gt: new Date() } },
472 ],
473 },
474 {
475 take: undefined,
476 },
477 sharedContext
478 )
479
480 const matches = await promiseAll(
481 secretKeys.map(async (dbKey) => {
482 const hashedInput = await ApiKeyModuleService.calculateHash(
483 token,
484 dbKey.salt
485 )
486 if (hashedInput === dbKey.token) {
487 return dbKey
488 }
489
490 return undefined
491 })
492 )
493
494 const matchedKeys = matches.filter((match) => !!match)
495 if (!matchedKeys.length) {
496 return false
497 }
498 return matchedKeys[0]
499 }
500
501 protected async normalizeUpdateInput_<T>(
502 idOrSelector: string | FilterableApiKeyProps,
503 data: Omit<T, "id">,
504 sharedContext: Context = {}
505 ): Promise<T[]> {
506 let normalizedInput: T[] = []
507 if (isString(idOrSelector)) {
508 normalizedInput = [{ id: idOrSelector, ...data } as T]
509 }
510
511 if (isObject(idOrSelector)) {
512 const apiKeys = await this.apiKeyService_.list(
513 idOrSelector,
514 {},
515 sharedContext
516 )
517
518 normalizedInput = apiKeys.map(
519 (apiKey) =>
520 ({
521 id: apiKey.id,
522 ...data,
523 } as T)
524 )
525 }
526
527 return normalizedInput
528 }
529
530 protected async validateRevokeApiKeys_(
531 data: RevokeApiKeyInput[],
532 sharedContext: Context = {}
533 ): Promise<void> {
534 if (!data.length) {
535 return
536 }
537
538 if (data.some((k) => !k.id)) {
539 throw new MedusaError(
540 MedusaError.Types.INVALID_DATA,
541 `You must provide an api key id field when revoking a key.`
542 )
543 }
544
545 if (data.some((k) => !k.revoked_by)) {
546 throw new MedusaError(
547 MedusaError.Types.INVALID_DATA,
548 `You must provide a revoked_by field when revoking a key.`
549 )
550 }
551
552 const revokedApiKeys = await this.apiKeyService_.list(
553 {
554 id: data.map((k) => k.id),
555 type: ApiKeyType.SECRET,
556 revoked_at: { $lt: new Date() },
557 },
558 {},
559 sharedContext
560 )
561
562 if (revokedApiKeys.length) {
563 throw new MedusaError(
564 MedusaError.Types.INVALID_DATA,
565 `There are ${revokedApiKeys.length} secret keys that are already revoked.`
566 )
567 }
568 }
569
570 // These are public keys, so there is no point hashing them.
571 protected static generatePublishableKey(): TokenDTO {
572 const token = "pk_" + crypto.randomBytes(32).toString("hex")
573
574 return {
575 rawToken: token,
576 hashedToken: token,
577 salt: "",
578 redacted: redactKey(token),
579 }
580 }
581
582 protected static async generateSecretKey(): Promise<TokenDTO> {
583 const token = "sk_" + crypto.randomBytes(32).toString("hex")
584 const salt = crypto.randomBytes(16).toString("hex")
585 const hashed = await this.calculateHash(token, salt)
586
587 return {
588 rawToken: token,
589 hashedToken: hashed,
590 salt,
591 redacted: redactKey(token),
592 }
593 }
594
595 protected static async calculateHash(
596 token: string,
597 salt: string
598 ): Promise<string> {
599 return ((await scrypt(token, salt, 64)) as Buffer).toString("hex")
600 }
601 }
602
603 // We are mutating the object here as what microORM relies on non-enumerable fields for serialization, among other things.
604 const omitToken = (
605 // We have to make salt optional before deleting it (and we do want it required in the DB)
606 key: Omit<InferEntityType<typeof ApiKey>, "salt"> & { salt?: string }
607 ): Omit<InferEntityType<typeof ApiKey>, "salt"> => {
608 key.token = key.type === ApiKeyType.SECRET ? "" : key.token
609 delete key.salt
610 return key
611 }
612
613 const redactKey = (key: string): string => {
614 return [key.slice(0, 6), key.slice(-3)].join("***")
615 }