Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
scim.tsx15.0 KB · 479 lines
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
/**
 * SCIM 2.0 — System for Cross-domain Identity Management.
 *
 * Identity providers (Okta, Azure AD, Google Workspace) use SCIM to
 * automatically provision and deprovision users from Gluecron orgs.
 *
 * Endpoints:
 *   GET    /scim/v2/:orgId/Users              — list users in the org
 *   POST   /scim/v2/:orgId/Users              — provision (create) a user
 *   GET    /scim/v2/:orgId/Users/:userId      — get user details
 *   PUT    /scim/v2/:orgId/Users/:userId      — replace user
 *   PATCH  /scim/v2/:orgId/Users/:userId      — partial update (deactivate, etc.)
 *   DELETE /scim/v2/:orgId/Users/:userId      — deprovision (disable, keep data)
 *
 * Auth: Bearer token → validated against scim_tokens.token_hash (SHA-256).
 *
 * All responses follow RFC 7643 (SCIM Core Schema) and RFC 7644 (SCIM Protocol).
 */

import { Hono } from "hono";
import { eq, and } 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>();

// ---------------------------------------------------------------------------
// SCIM schemas / constants
// ---------------------------------------------------------------------------

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";

// ---------------------------------------------------------------------------
// Auth middleware
// ---------------------------------------------------------------------------

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 };

  // Update last_used_at lazily (fire-and-forget)
  db.update(scimTokens)
    .set({ lastUsedAt: new Date() })
    .where(eq(scimTokens.id, token.id))
    .catch(() => {});

  return { ok: true, token };
}

function scimError(c: any, status: number, detail: string, scimType?: string) {
  return c.json(
    {
      schemas: [SCIM_ERROR_SCHEMA],
      status,
      ...(scimType ? { scimType } : {}),
      detail,
    },
    status
  );
}

/** Convert a Drizzle user row to a SCIM User resource. */
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}`,
    },
  };
}

// ---------------------------------------------------------------------------
// GET /scim/v2/:orgId/Users — list users in the org
// ---------------------------------------------------------------------------

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");

  // Verify org exists
  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");

  // Pagination params
  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;

  // Get org members and their user data
  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, // approximate
    startIndex,
    itemsPerPage: count,
    Resources: resources,
  });
});

// ---------------------------------------------------------------------------
// POST /scim/v2/:orgId/Users — provision a user
// ---------------------------------------------------------------------------

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");
  }

  // Check if user already exists
  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 {
    // Auto-derive a username
    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(),
      })
      .returning({ id: users.id });

    if (!created) return scimError(c, 500, "Failed to create user");
    userId = created.id;
  }

  // Add to org if not already a member
  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);
});

// ---------------------------------------------------------------------------
// GET /scim/v2/:orgId/Users/:userId — get a single user
// ---------------------------------------------------------------------------

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));
});

// ---------------------------------------------------------------------------
// PUT /scim/v2/:orgId/Users/:userId — replace a user
// ---------------------------------------------------------------------------

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) {
    updates.deletedAt = new Date();
    updates.deletionScheduledFor = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
  } else if (body.active === true) {
    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));
});

// ---------------------------------------------------------------------------
// PATCH /scim/v2/:orgId/Users/:userId — partial update
// ---------------------------------------------------------------------------

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 (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));
});

// ---------------------------------------------------------------------------
// DELETE /scim/v2/:orgId/Users/:userId — deprovision (soft-delete)
// ---------------------------------------------------------------------------

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");

  // Remove from org membership (preserves user account + git history)
  await db
    .delete(orgMembers)
    .where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)));

  // Soft-disable the account
  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);
});

// ---------------------------------------------------------------------------
// GET /scim/v2/:orgId/ServiceProviderConfig — SCIM capability discovery
// ---------------------------------------------------------------------------

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;