1// Find everyone in HiBob who starts today, copy their title, department and
2// manager onto their staged Okta account, then activate it. Anyone who can't
3// be set up goes on one ticket for IT.
4//
5// Before publishing: replace acme.okta.com with your Okta domain (in
6// `domains` and OKTA_BASE). Set HIBOB_SERVICE_USER_ID and
7// HIBOB_SERVICE_USER_TOKEN for a HiBob service user that can view the Root
8// and Work categories, with "Access data for" covering people who haven't
9// started yet. Set OKTA_API_TOKEN from an Okta admin who can manage users.
10// It assumes each hire's Okta login is their HiBob work email. Run it from a
11// daily scheduled automation.
12
13type NewHire = {
14 name: string;
15 email: string;
16 title: string | null;
17 department: string | null;
18 managerName: string | null;
19 managerEmail: string | null;
20};
21
22type StagedAccount = { hire: NewHire; userId: string };
23
24type OktaReply = { status_code: number; body: unknown };
25
26type OktaLookup = { hire: NewHire; reply: OktaReply };
27
28type SyncResult = {
29 hire: NewHire;
30 updateStatus: number;
31 activationStatus: number | null;
32};
33
34export const input = z.object({
35 start_date: z
36 .string()
37 .regex(/^\d{4}-\d{2}-\d{2}$/)
38 .optional()
39 .describe("Start date to onboard, as YYYY-MM-DD. Defaults to today (UTC)"),
40 send_activation_email: z
41 .boolean()
42 .default(false)
43 .describe(
44 "Have Okta email each hire an activation link. Leave off when IT " +
45 "hands over credentials on day one",
46 ),
47});
48
49// HiBob's people search only reads, but it's a POST, and the posture follows
50// the verb: api.hibob.com needs "read_write" too.
51export const domains = {
52 "api.hibob.com": "read_write",
53 "acme.okta.com": "read_write",
54};
55
56const OKTA_BASE = "https://acme.okta.com/api/v1";
57
58// HiBob field IDs (dot notation). Responses key them in slash notation.
59const HIBOB_FIELDS = [
60 "root.displayName",
61 "root.email",
62 "work.startDate",
63 "work.title",
64 "work.department",
65 "work.reportsTo",
66];
67
68const oktaAuth = () => ({
69 type: "api_key_header" as const,
70 header: "Authorization",
71 value: `SSWS ${env.OKTA_API_TOKEN}`,
72});
73
74const isObject = (value: unknown): value is Record<string, unknown> =>
75 typeof value === "object" && value !== null;
76
77const getNested = (value: unknown, path: string[]): unknown => {
78 let current: unknown = value;
79 for (const key of path) {
80 if (!isObject(current)) {
81 return null;
82 }
83 current = current[key];
84 }
85 return current;
86};
87
88const getNestedString = (value: unknown, path: string[]): string | null => {
89 const found = getNested(value, path);
90 return typeof found === "string" && found !== "" ? found : null;
91};
92
93// Machine format wraps each field: "/work/startDate": { "value": "..." }.
94// Title and department are list IDs there, so their names come from the
95// "humanReadable" node that humanReadable: "APPEND" adds.
96const toNewHire = (employee: unknown): NewHire => ({
97 name:
98 getNestedString(employee, ["/root/displayName", "value"]) ?? "Unnamed",
99 email: getNestedString(employee, ["/root/email", "value"]) ?? "",
100 title: getNestedString(employee, ["humanReadable", "work", "title"]),
101 department: getNestedString(employee, [
102 "humanReadable",
103 "work",
104 "department",
105 ]),
106 managerName: getNestedString(employee, [
107 "/work/reportsTo",
108 "value",
109 "displayName",
110 ]),
111 managerEmail: getNestedString(employee, [
112 "/work/reportsTo",
113 "value",
114 "email",
115 ]),
116});
117
118// Okta's default profile: `manager` is the manager's display name and
119// `managerId` their Okta user ID. Fields HiBob left empty aren't sent, and
120// a POST to /users/{id} leaves unsent fields as they are.
121const oktaProfile = (hire: NewHire, managerId: string | null) => {
122 const profile: Record<string, string> = {};
123 const values: [string, string | null][] = [
124 ["title", hire.title],
125 ["department", hire.department],
126 ["manager", hire.managerName],
127 ["managerId", managerId],
128 ];
129 for (const [key, value] of values) {
130 if (value !== null) {
131 profile[key] = value;
132 }
133 }
134 return profile;
135};
136
137const isString = (value: string | null): value is string => value !== null;
138
139const label = (hire: NewHire) => `${hire.name} (${hire.email})`;
140
141const oktaStatus = (reply: OktaReply): string | null =>
142 reply.status_code === 200 ? getNestedString(reply.body, ["status"]) : null;
143
144const oktaUserId = (reply: OktaReply | null): string | null =>
145 reply?.status_code === 200 ? getNestedString(reply.body, ["id"]) : null;
146
147// Only a STAGED account is activated. ACTIVE and PROVISIONED accounts were
148// activated before; any other status needs a person to look.
149const stagedAccount = (lookup: OktaLookup): StagedAccount[] => {
150 const userId = oktaUserId(lookup.reply);
151 return oktaStatus(lookup.reply) === "STAGED" && userId !== null
152 ? [{ hire: lookup.hire, userId }]
153 : [];
154};
155
156const isActivated = (lookup: OktaLookup) => {
157 const status = oktaStatus(lookup.reply);
158 return status === "ACTIVE" || status === "PROVISIONED";
159};
160
161const lookupProblem = (lookup: OktaLookup): string | null => {
162 if (stagedAccount(lookup).length > 0 || isActivated(lookup)) {
163 return null;
164 }
165 const { status_code } = lookup.reply;
166 if (status_code === 404) {
167 return `${label(lookup.hire)}: no Okta account with this login`;
168 }
169 if (status_code !== 200) {
170 return `${label(lookup.hire)}: Okta lookup returned ${status_code}`;
171 }
172 const status = oktaStatus(lookup.reply) ?? "in an unknown status";
173 return `${label(lookup.hire)}: Okta account is ${status}, not STAGED`;
174};
175
176const syncProblem = (result: SyncResult): string | null => {
177 if (result.updateStatus !== 200) {
178 return (
179 `${label(result.hire)}: profile update returned ` +
180 `${result.updateStatus}, so the account was left staged`
181 );
182 }
183 if (result.activationStatus !== 200) {
184 return (
185 `${label(result.hire)}: activation returned ` +
186 `${result.activationStatus}`
187 );
188 }
189 return null;
190};
191
192export default async function run(params: z.infer<typeof input>) {
193 // The run's date in UTC unless one is given.
194 const startDate = params.start_date ?? new Date().toISOString().slice(0, 10);
195
196 // **Find who starts in HiBob**
197 // The search includes inactive people: new hires are inactive until day one.
198 const search = await http.post("https://api.hibob.com/v1/people/search", {
199 auth: {
200 type: "basic",
201 username: env.HIBOB_SERVICE_USER_ID,
202 password: env.HIBOB_SERVICE_USER_TOKEN,
203 },
204 json: {
205 fields: HIBOB_FIELDS,
206 showInactive: true,
207 humanReadable: "APPEND",
208 },
209 });
210 if (search.status_code !== 200) {
211 fail(
212 `HiBob people search returned ${search.status_code}. Check the ` +
213 "service user's ID and token, and that its permission group can " +
214 "view people who haven't started yet.",
215 );
216 }
217 const employees: unknown[] = Array.isArray(search.body?.employees)
218 ? search.body.employees
219 : [];
220 // HiBob can't filter on start date, so match it here.
221 const startingToday = employees.filter(
222 (employee) =>
223 getNestedString(employee, ["/work/startDate", "value"]) === startDate,
224 );
225 if (startingToday.length === 0) {
226 return `Nobody in HiBob starts on ${startDate}. Nothing to activate.`;
227 }
228 const hires = startingToday.map(toNewHire);
229 const withEmail = hires.filter((hire) => hire.email !== "");
230 const problems = hires
231 .filter((hire) => hire.email === "")
232 .map((hire) => `${hire.name}: no work email in HiBob`);
233
234 // **Find their staged Okta accounts**
235 // Looks up each hire in Okta by login.
236 const lookups: OktaLookup[] = [];
237 // Calls run one hire at a time. That's well inside the 120-second limit
238 // for a day's starters.
239 for (const hire of withEmail) {
240 const reply = await http.get(
241 `${OKTA_BASE}/users/${encodeURIComponent(hire.email)}`,
242 { auth: oktaAuth() },
243 );
244 lookups.push({ hire, reply });
245 }
246 const staged = lookups.flatMap(stagedAccount);
247 const alreadyActive = lookups
248 .filter(isActivated)
249 .map((lookup) => lookup.hire.name);
250 problems.push(...lookups.map(lookupProblem).filter(isString));
251
252 // **Sync the profile and activate**
253 // Updates title, department and manager, then activates the account.
254 const results: SyncResult[] = [];
255 for (const { hire, userId } of staged) {
256 const manager =
257 hire.managerEmail === null
258 ? null
259 : await http.get(
260 `${OKTA_BASE}/users/${encodeURIComponent(hire.managerEmail)}`,
261 { auth: oktaAuth() },
262 );
263 const update = await http.post(`${OKTA_BASE}/users/${userId}`, {
264 auth: oktaAuth(),
265 json: { profile: oktaProfile(hire, oktaUserId(manager)) },
266 });
267 // A failed update leaves the account staged. With sendEmail=false Okta
268 // answers with an activation link; it isn't passed on, as IT hands over
269 // credentials its own way.
270 const activation =
271 update.status_code !== 200
272 ? null
273 : await http.post(`${OKTA_BASE}/users/${userId}/lifecycle/activate`, {
274 auth: oktaAuth(),
275 query: {
276 sendEmail: params.send_activation_email ? "true" : "false",
277 },
278 });
279 results.push({
280 hire,
281 updateStatus: update.status_code,
282 activationStatus: activation?.status_code ?? null,
283 });
284 }
285 const activated = results
286 .filter((result) => result.activationStatus === 200)
287 .map((result) => result.hire.name);
288 problems.push(...results.map(syncProblem).filter(isString));
289
290 // **Ticket anyone left over**
291 // Opens one ticket listing everyone who couldn't be set up.
292 const summary =
293 `Activated ${activated.length} of ${hires.length} people starting ` +
294 `${startDate}` +
295 (activated.length > 0 ? `: ${activated.join(", ")}.` : ".") +
296 (alreadyActive.length > 0
297 ? ` Already activated in Okta: ${alreadyActive.join(", ")}.`
298 : "");
299 if (problems.length === 0) {
300 return summary;
301 }
302 const ticket = await risotto.create_ticket({
303 title: `New hire activation: ${problems.length} not set up (${startDate})`,
304 description:
305 `These people start on ${startDate} but their Okta accounts weren't ` +
306 "activated. Fix each one, then activate it in Okta.\n\n" +
307 problems.map((problem) => `- ${problem}`).join("\n"),
308 });
309 return (
310 `${summary} Skipped ${problems.length}: ${problems.join("; ")}. ` +
311 `Opened ticket ${ticket.ticket_id}.`
312 );
313}