1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
|
import { Hono } from "hono";
import { eq, and, ne } from "drizzle-orm";
import * as crypto from "crypto";
import { db } from "../db";
import {
scimTokens,
orgMembers,
organizations,
users,
} from "../db/schema";
import type { AuthEnv } from "../middleware/auth";
const scim = new Hono<AuthEnv>();
const SCIM_USER_SCHEMA = "urn:ietf:params:scim:schemas:core:2.0:User";
const SCIM_LIST_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
const SCIM_ERROR_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:Error";
async function scimAuth(
c: any,
orgId: string
): Promise<{ ok: true; token: typeof scimTokens.$inferSelect } | { ok: false }> {
const authHeader = c.req.header("authorization") || "";
if (!authHeader.startsWith("Bearer ")) return { ok: false };
const rawToken = authHeader.slice(7);
const tokenHash = crypto
.createHash("sha256")
.update(rawToken)
.digest("hex");
const [token] = await db
.select()
.from(scimTokens)
.where(
and(
eq(scimTokens.tokenHash, tokenHash),
eq(scimTokens.orgId, orgId)
)
)
.limit(1);
if (!token) return { ok: false };
db.update(scimTokens)
.set({ lastUsedAt: new Date() })
.where(eq(scimTokens.id, token.id))
.catch(() => {});
return { ok: true, token };
}
export function mayScimDisableAccount(args: {
/** users.scimProvisionedByOrgId for the target account. */
provisionedByOrgId: string | null;
/** The org whose SCIM token is making the request. */
orgId: string;
/** Does the target belong to any organization other than `orgId`? */
hasOtherOrgMemberships: boolean;
}): boolean {
const { provisionedByOrgId, orgId, hasOtherOrgMemberships } = args;
if (!provisionedByOrgId) return false;
if (provisionedByOrgId !== orgId) return false;
if (hasOtherOrgMemberships) return false;
return true;
}
async function canScimManageAccount(
userId: string,
orgId: string
): Promise<boolean> {
const [target] = await db
.select({ provisionedBy: users.scimProvisionedByOrgId })
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!target) return false;
const elsewhere = await db
.select({ id: orgMembers.id })
.from(orgMembers)
.where(and(eq(orgMembers.userId, userId), ne(orgMembers.orgId, orgId)))
.limit(1);
return mayScimDisableAccount({
provisionedByOrgId: target.provisionedBy ?? null,
orgId,
hasOtherOrgMemberships: elsewhere.length > 0,
});
}
function scimError(c: any, status: number, detail: string, scimType?: string) {
return c.json(
{
schemas: [SCIM_ERROR_SCHEMA],
status,
...(scimType ? { scimType } : {}),
detail,
},
status
);
}
function toScimUser(user: {
id: string;
username: string;
email: string;
displayName: string | null;
createdAt: Date;
updatedAt: Date;
deletedAt: Date | null;
}) {
const [firstName, ...rest] = (user.displayName || user.username).split(" ");
const lastName = rest.join(" ") || "";
const base = process.env.APP_URL || process.env.BASE_URL || "https://gluecron.com";
return {
schemas: [SCIM_USER_SCHEMA],
id: user.id,
userName: user.email,
name: {
formatted: user.displayName || user.username,
givenName: firstName,
familyName: lastName,
},
emails: [{ value: user.email, primary: true }],
active: !user.deletedAt,
meta: {
resourceType: "User",
created: user.createdAt.toISOString(),
lastModified: user.updatedAt.toISOString(),
location: `${base}/scim/v2/${user.id}`,
},
};
}
scim.get("/scim/v2/:orgId/Users", async (c) => {
const { orgId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [org] = await db
.select({ id: organizations.id })
.from(organizations)
.where(eq(organizations.id, orgId))
.limit(1);
if (!org) return scimError(c, 404, "Organization not found");
const startIndex = Math.max(1, parseInt(c.req.query("startIndex") || "1", 10));
const count = Math.min(100, Math.max(1, parseInt(c.req.query("count") || "100", 10)));
const offset = startIndex - 1;
const members = await db
.select({
id: users.id,
username: users.username,
email: users.email,
displayName: users.displayName,
createdAt: users.createdAt,
updatedAt: users.updatedAt,
deletedAt: users.deletedAt,
})
.from(orgMembers)
.innerJoin(users, eq(users.id, orgMembers.userId))
.where(eq(orgMembers.orgId, orgId))
.limit(count)
.offset(offset);
const resources = members.map(toScimUser);
return c.json({
schemas: [SCIM_LIST_SCHEMA],
totalResults: resources.length + offset,
startIndex,
itemsPerPage: count,
Resources: resources,
});
});
scim.post("/scim/v2/:orgId/Users", async (c) => {
const { orgId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [org] = await db
.select({ id: organizations.id })
.from(organizations)
.where(eq(organizations.id, orgId))
.limit(1);
if (!org) return scimError(c, 404, "Organization not found");
let body: {
userName?: string;
name?: { formatted?: string; givenName?: string; familyName?: string };
emails?: Array<{ value: string; primary?: boolean }>;
active?: boolean;
displayName?: string;
};
try {
body = await c.req.json();
} catch {
return scimError(c, 400, "Invalid JSON", "invalidValue");
}
const email =
body.emails?.find((e) => e.primary)?.value ||
body.emails?.[0]?.value ||
body.userName ||
"";
if (!email || !email.includes("@")) {
return scimError(c, 400, "email is required", "invalidValue");
}
const [existing] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.email, email))
.limit(1);
let userId: string;
if (existing) {
userId = existing.id;
} else {
let username = email.split("@")[0].toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, 39);
const [taken] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.username, username))
.limit(1);
if (taken) username = username + "-" + crypto.randomBytes(3).toString("hex");
const displayName =
body.displayName ||
body.name?.formatted ||
[body.name?.givenName, body.name?.familyName].filter(Boolean).join(" ") ||
username;
const [created] = await db
.insert(users)
.values({
username,
email,
displayName,
passwordHash: await Bun.password.hash(crypto.randomBytes(32).toString("hex"), {
algorithm: "bcrypt",
cost: 10,
}),
emailVerifiedAt: new Date(),
scimProvisionedByOrgId: orgId,
})
.returning({ id: users.id });
if (!created) return scimError(c, 500, "Failed to create user");
userId = created.id;
}
const [isMember] = await db
.select({ id: orgMembers.id })
.from(orgMembers)
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
.limit(1);
if (!isMember) {
await db.insert(orgMembers).values({
orgId,
userId,
role: "member",
});
}
const [userRow] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
return c.json(toScimUser(userRow), 201);
});
scim.get("/scim/v2/:orgId/Users/:userId", async (c) => {
const { orgId, userId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [member] = await db
.select({
id: users.id,
username: users.username,
email: users.email,
displayName: users.displayName,
createdAt: users.createdAt,
updatedAt: users.updatedAt,
deletedAt: users.deletedAt,
})
.from(orgMembers)
.innerJoin(users, eq(users.id, orgMembers.userId))
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
.limit(1);
if (!member) return scimError(c, 404, "User not found");
return c.json(toScimUser(member));
});
scim.put("/scim/v2/:orgId/Users/:userId", async (c) => {
const { orgId, userId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [member] = await db
.select({ id: orgMembers.id })
.from(orgMembers)
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
.limit(1);
if (!member) return scimError(c, 404, "User not found in this organization");
let body: {
displayName?: string;
name?: { formatted?: string; givenName?: string; familyName?: string };
active?: boolean;
};
try {
body = await c.req.json();
} catch {
return scimError(c, 400, "Invalid JSON", "invalidValue");
}
const displayName =
body.displayName ||
body.name?.formatted ||
[body.name?.givenName, body.name?.familyName].filter(Boolean).join(" ") ||
undefined;
const updates: Record<string, unknown> = { updatedAt: new Date() };
if (displayName) updates.displayName = displayName;
if (body.active === false || body.active === true) {
if (await canScimManageAccount(userId, orgId)) {
if (body.active === false) {
updates.deletedAt = new Date();
updates.deletionScheduledFor = new Date(
Date.now() + 30 * 24 * 60 * 60 * 1000
);
} else {
updates.deletedAt = null;
updates.deletionScheduledFor = null;
}
}
}
await db.update(users).set(updates).where(eq(users.id, userId));
const [updated] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
return c.json(toScimUser(updated));
});
scim.patch("/scim/v2/:orgId/Users/:userId", async (c) => {
const { orgId, userId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [member] = await db
.select({ id: orgMembers.id })
.from(orgMembers)
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
.limit(1);
if (!member) return scimError(c, 404, "User not found in this organization");
let body: {
Operations?: Array<{
op: string;
path?: string;
value?: unknown;
}>;
};
try {
body = await c.req.json();
} catch {
return scimError(c, 400, "Invalid JSON", "invalidValue");
}
const updates: Record<string, unknown> = { updatedAt: new Date() };
for (const op of body.Operations || []) {
const opLower = (op.op || "").toLowerCase();
if (op.path === "active" || (typeof op.value === "object" && op.value !== null && "active" in (op.value as object))) {
const activeVal =
op.path === "active"
? op.value
: (op.value as Record<string, unknown>)["active"];
if (opLower === "replace" || opLower === "add") {
if (await canScimManageAccount(userId, orgId)) {
if (activeVal === false || activeVal === "false") {
updates.deletedAt = new Date();
updates.deletionScheduledFor = new Date(
Date.now() + 30 * 24 * 60 * 60 * 1000
);
} else {
updates.deletedAt = null;
updates.deletionScheduledFor = null;
}
}
}
}
if (op.path === "displayName" && (opLower === "replace" || opLower === "add")) {
updates.displayName = String(op.value || "");
}
}
await db.update(users).set(updates).where(eq(users.id, userId));
const [updated] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
return c.json(toScimUser(updated));
});
scim.delete("/scim/v2/:orgId/Users/:userId", async (c) => {
const { orgId, userId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const [member] = await db
.select({ id: orgMembers.id })
.from(orgMembers)
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
.limit(1);
if (!member) return scimError(c, 404, "User not found in this organization");
await db
.delete(orgMembers)
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)));
if (await canScimManageAccount(userId, orgId)) {
await db
.update(users)
.set({
deletedAt: new Date(),
deletionScheduledFor: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
updatedAt: new Date(),
})
.where(eq(users.id, userId));
}
return c.body(null, 204);
});
scim.get("/scim/v2/:orgId/ServiceProviderConfig", async (c) => {
const { orgId } = c.req.param();
const auth = await scimAuth(c, orgId);
if (!auth.ok) return scimError(c, 401, "Unauthorized");
const base = process.env.APP_URL || process.env.BASE_URL || "https://gluecron.com";
return c.json({
schemas: ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"],
patch: { supported: true },
bulk: { supported: false, maxOperations: 0, maxPayloadSize: 0 },
filter: { supported: false, maxResults: 100 },
changePassword: { supported: false },
sort: { supported: false },
etag: { supported: false },
authenticationSchemes: [
{
type: "oauthbearertoken",
name: "OAuth Bearer Token",
description: "Authentication scheme using the OAuth Bearer Token Standard",
specUri: "http://www.rfc-editor.org/info/rfc6750",
primary: true,
},
],
meta: {
resourceType: "ServiceProviderConfig",
location: `${base}/scim/v2/${orgId}/ServiceProviderConfig`,
},
});
});
export default scim;
|