|
| 1 | +import { genericConfig } from "../config.js"; |
| 2 | +import { EntraInvitationError, InternalServerError } from "../errors/index.js"; |
| 3 | +import { getSecretValue } from "../plugins/auth.js"; |
| 4 | +import { ConfidentialClientApplication } from "@azure/msal-node"; |
| 5 | +import { getItemFromCache, insertItemIntoCache } from "./cache.js"; |
| 6 | + |
| 7 | +interface EntraInvitationResponse { |
| 8 | + status: number; |
| 9 | + data?: Record<string, string>; |
| 10 | + error?: { |
| 11 | + message: string; |
| 12 | + code?: string; |
| 13 | + }; |
| 14 | +} |
| 15 | +export async function getEntraIdToken( |
| 16 | + clientId: string, |
| 17 | + scopes: string[] = ["https://graph.microsoft.com/.default"], |
| 18 | +) { |
| 19 | + const secretApiConfig = |
| 20 | + (await getSecretValue(genericConfig.ConfigSecretName)) || {}; |
| 21 | + if ( |
| 22 | + !secretApiConfig.entra_id_private_key || |
| 23 | + !secretApiConfig.entra_id_thumbprint |
| 24 | + ) { |
| 25 | + throw new InternalServerError({ |
| 26 | + message: "Could not find Entra ID credentials.", |
| 27 | + }); |
| 28 | + } |
| 29 | + const decodedPrivateKey = Buffer.from( |
| 30 | + secretApiConfig.entra_id_private_key as string, |
| 31 | + "base64", |
| 32 | + ).toString("utf8"); |
| 33 | + const cachedToken = await getItemFromCache("entra_id_access_token"); |
| 34 | + if (cachedToken) { |
| 35 | + return cachedToken["token"] as string; |
| 36 | + } |
| 37 | + const config = { |
| 38 | + auth: { |
| 39 | + clientId: clientId, |
| 40 | + authority: `https://login.microsoftonline.com/${genericConfig.EntraTenantId}`, |
| 41 | + clientCertificate: { |
| 42 | + thumbprint: (secretApiConfig.entra_id_thumbprint as string) || "", |
| 43 | + privateKey: decodedPrivateKey, |
| 44 | + }, |
| 45 | + }, |
| 46 | + }; |
| 47 | + const cca = new ConfidentialClientApplication(config); |
| 48 | + try { |
| 49 | + const result = await cca.acquireTokenByClientCredential({ |
| 50 | + scopes, |
| 51 | + }); |
| 52 | + const date = result?.expiresOn; |
| 53 | + if (!date) { |
| 54 | + throw new InternalServerError({ |
| 55 | + message: `Failed to acquire token: token has no expiry field.`, |
| 56 | + }); |
| 57 | + } |
| 58 | + date.setTime(date.getTime() - 30000); |
| 59 | + if (result?.accessToken) { |
| 60 | + await insertItemIntoCache( |
| 61 | + "entra_id_access_token", |
| 62 | + { token: result?.accessToken }, |
| 63 | + date, |
| 64 | + ); |
| 65 | + } |
| 66 | + return result?.accessToken ?? null; |
| 67 | + } catch (error) { |
| 68 | + throw new InternalServerError({ |
| 69 | + message: `Failed to acquire token: ${error}`, |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Adds a user to the tenant by sending an invitation to their email |
| 76 | + * @param email - The email address of the user to invite |
| 77 | + * @throws {InternalServerError} If the invitation fails |
| 78 | + * @returns {Promise<boolean>} True if the invitation was successful |
| 79 | + */ |
| 80 | +export async function addToTenant(token: string, email: string) { |
| 81 | + email = email.toLowerCase().replace(/\s/g, ""); |
| 82 | + if (!email.endsWith("@illinois.edu")) { |
| 83 | + throw new EntraInvitationError({ |
| 84 | + email, |
| 85 | + message: "User's domain must be illinois.edu to be invited.", |
| 86 | + }); |
| 87 | + } |
| 88 | + try { |
| 89 | + const body = { |
| 90 | + invitedUserEmailAddress: email, |
| 91 | + inviteRedirectUrl: "https://acm.illinois.edu", |
| 92 | + }; |
| 93 | + const url = "https://graph.microsoft.com/v1.0/invitations"; |
| 94 | + const response = await fetch(url, { |
| 95 | + method: "POST", |
| 96 | + headers: { |
| 97 | + Authorization: `Bearer ${token}`, |
| 98 | + "Content-Type": "application/json", |
| 99 | + }, |
| 100 | + body: JSON.stringify(body), |
| 101 | + }); |
| 102 | + |
| 103 | + if (!response.ok) { |
| 104 | + const errorData = (await response.json()) as EntraInvitationResponse; |
| 105 | + throw new EntraInvitationError({ |
| 106 | + message: errorData.error?.message || response.statusText, |
| 107 | + email, |
| 108 | + }); |
| 109 | + } |
| 110 | + |
| 111 | + return { success: true, email }; |
| 112 | + } catch (error) { |
| 113 | + if (error instanceof EntraInvitationError) { |
| 114 | + throw error; |
| 115 | + } |
| 116 | + |
| 117 | + throw new EntraInvitationError({ |
| 118 | + message: error instanceof Error ? error.message : String(error), |
| 119 | + email, |
| 120 | + }); |
| 121 | + } |
| 122 | +} |
0 commit comments