@intelligo-dev/auth 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +201 -0
  2. package/dist/client.js +25 -0
  3. package/dist/client.js.map +1 -0
  4. package/dist/edge.js +39 -0
  5. package/dist/edge.js.map +1 -0
  6. package/dist/helpers.js +248 -0
  7. package/dist/helpers.js.map +1 -0
  8. package/dist/impersonation.js +42 -0
  9. package/dist/impersonation.js.map +1 -0
  10. package/dist/index.js +30 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/onboarding/errors.js +31 -0
  13. package/dist/onboarding/errors.js.map +1 -0
  14. package/dist/onboarding/schemas.js +24 -0
  15. package/dist/onboarding/schemas.js.map +1 -0
  16. package/dist/onboarding/service.js +147 -0
  17. package/dist/onboarding/service.js.map +1 -0
  18. package/dist/org-api.js +86 -0
  19. package/dist/org-api.js.map +1 -0
  20. package/dist/profile/errors.js +32 -0
  21. package/dist/profile/errors.js.map +1 -0
  22. package/dist/profile/schemas.js +20 -0
  23. package/dist/profile/schemas.js.map +1 -0
  24. package/dist/profile/service.js +157 -0
  25. package/dist/profile/service.js.map +1 -0
  26. package/dist/roles.js +17 -0
  27. package/dist/roles.js.map +1 -0
  28. package/dist/server.js +251 -0
  29. package/dist/server.js.map +1 -0
  30. package/dist/team/errors.js +31 -0
  31. package/dist/team/errors.js.map +1 -0
  32. package/dist/team/schemas.js +29 -0
  33. package/dist/team/schemas.js.map +1 -0
  34. package/dist/team/service.js +438 -0
  35. package/dist/team/service.js.map +1 -0
  36. package/dist/workspace/errors.js +32 -0
  37. package/dist/workspace/errors.js.map +1 -0
  38. package/dist/workspace/schemas.js +45 -0
  39. package/dist/workspace/schemas.js.map +1 -0
  40. package/dist/workspace/service.js +268 -0
  41. package/dist/workspace/service.js.map +1 -0
  42. package/dist/workspace-init.js +121 -0
  43. package/dist/workspace-init.js.map +1 -0
  44. package/package.json +58 -0
  45. package/src/client.ts +27 -0
  46. package/src/edge.ts +43 -0
  47. package/src/helpers.ts +317 -0
  48. package/src/impersonation.ts +57 -0
  49. package/src/index.ts +109 -0
  50. package/src/onboarding/errors.ts +52 -0
  51. package/src/onboarding/schemas.ts +27 -0
  52. package/src/onboarding/service.ts +174 -0
  53. package/src/org-api.ts +198 -0
  54. package/src/profile/errors.ts +58 -0
  55. package/src/profile/schemas.ts +23 -0
  56. package/src/profile/service.ts +208 -0
  57. package/src/roles.ts +17 -0
  58. package/src/server.ts +305 -0
  59. package/src/team/errors.ts +71 -0
  60. package/src/team/schemas.ts +35 -0
  61. package/src/team/service.ts +611 -0
  62. package/src/workspace/errors.ts +69 -0
  63. package/src/workspace/schemas.ts +57 -0
  64. package/src/workspace/service.ts +381 -0
  65. package/src/workspace-init.ts +140 -0
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Workspace Validation Schemas
3
+ *
4
+ * Zod schemas for workspace create/update inputs, shared by the
5
+ * workspace service and its transports.
6
+ *
7
+ * (Ported from the product application's workspace validation module —
8
+ * same semantics. Ignite's copy is retired at cutover.)
9
+ */
10
+
11
+ import { z } from "zod";
12
+
13
+ /**
14
+ * Create Workspace Schema
15
+ * Name + optional slug for new workspaces
16
+ */
17
+ export const createWorkspaceSchema = z.object({
18
+ name: z
19
+ .string()
20
+ .min(2, "Workspace name must be at least 2 characters")
21
+ .max(50, "Workspace name must be at most 50 characters"),
22
+ slug: z
23
+ .string()
24
+ .min(2, "Slug must be at least 2 characters")
25
+ .max(50, "Slug must be at most 50 characters")
26
+ .regex(
27
+ /^[a-z0-9-]+$/,
28
+ "Slug can only contain lowercase letters, numbers, and hyphens"
29
+ )
30
+ .optional(), // Auto-generated from name if not provided
31
+ });
32
+
33
+ export type CreateWorkspaceInput = z.infer<typeof createWorkspaceSchema>;
34
+
35
+ /**
36
+ * Update Workspace Schema
37
+ * Optional name, slug, and logo for workspace settings
38
+ */
39
+ export const updateWorkspaceSchema = z.object({
40
+ name: z
41
+ .string()
42
+ .min(2, "Workspace name must be at least 2 characters")
43
+ .max(50, "Workspace name must be at most 50 characters")
44
+ .optional(),
45
+ slug: z
46
+ .string()
47
+ .min(2, "Slug must be at least 2 characters")
48
+ .max(50, "Slug must be at most 50 characters")
49
+ .regex(
50
+ /^[a-z0-9-]+$/,
51
+ "Slug can only contain lowercase letters, numbers, and hyphens"
52
+ )
53
+ .optional(),
54
+ logo: z.string().url("Logo must be a valid URL").optional().nullable(),
55
+ });
56
+
57
+ export type UpdateWorkspaceInput = z.infer<typeof updateWorkspaceSchema>;
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Workspace management service — the durable business rules behind
3
+ * workspace listing, creation, switching, editing and deletion,
4
+ * extracted from the product application's workspace actions (page/
5
+ * registry migration, `workspace-settings` family, roadmap item 8).
6
+ *
7
+ * Mirrors `createTeamService(ports)` (./../team/service.ts) one
8
+ * directory over: a factory over optional ports, so this package's
9
+ * allowlisted dependency (`@intelligo-dev/core` only — see
10
+ * tests/architecture/dependency-direction.test.ts) never grows to
11
+ * include billing. A consumer binds that in at its composition root:
12
+ *
13
+ * const workspaceService = createWorkspaceService({
14
+ * checkWorkspaceLimit: ..., // adapts @intelligo-dev/billing's checkPlanLimit
15
+ * });
16
+ *
17
+ * Authorization (`requireAuth`/`requireWorkspace`/`requireRole`) lives
18
+ * INSIDE each method, not at the transport. Every recognized failure
19
+ * throws `WorkspaceServiceError` with a stable `code` — no
20
+ * revalidatePath/Sentry/next-intl/toast here; that shaping is the
21
+ * transport's job (a Server Action, a route handler).
22
+ *
23
+ * ---------------------------------------------------------------------
24
+ * Why `checkWorkspaceLimit` takes a `userId`, not a `workspaceId`
25
+ * ---------------------------------------------------------------------
26
+ * `createWorkspace` has no workspace to check the plan of yet — it is
27
+ * the thing being created. Ignite's original action worked around this
28
+ * by reading the caller's *existing* workspaces and using the first
29
+ * one's id to look up a plan via `@intelligo-dev/billing`'s
30
+ * `checkPlanLimit(workspaceId, "workspaces", currentCount)`, i.e. it
31
+ * borrowed an arbitrary existing workspace's subscription as a stand-in
32
+ * for "the caller's plan". That borrowing is a binding-layer concern,
33
+ * not a service-layer one: this service only knows the caller's
34
+ * `userId` and how many workspaces they already have. The composition
35
+ * root's binding (`checkWorkspaceLimit`) is where a consumer decides
36
+ * how to resolve "this user's plan" — by reading their first workspace
37
+ * the same way ignite did, or by a real per-user plan lookup if one
38
+ * exists.
39
+ *
40
+ * ---------------------------------------------------------------------
41
+ * The two Better-Auth pitfalls (already solved in ../team/service.ts —
42
+ * copied here rather than re-derived)
43
+ * ---------------------------------------------------------------------
44
+ * 1. Method-name mismatch: the typed `orgApi` wrapper (../org-api.ts)
45
+ * exists precisely because `auth.api`'s organization-plugin methods
46
+ * are keyed by their own camelCase *server* id, which does not
47
+ * always match the HTTP path or the client SDK name. This service
48
+ * uses `orgApi["/organization/list"]` and
49
+ * `orgApi["/organization/set-active"]` for the two calls the
50
+ * wrapper covers, and calls `auth.api.{createOrganization,
51
+ * updateOrganization, deleteOrganization, getFullOrganization}`
52
+ * directly for the base organization CRUD surface, which is not
53
+ * part of `orgApi`'s typed table (the same approach
54
+ * `../team/service.ts` takes for `getFullOrganization`). Ignite's
55
+ * original `actions/workspace.ts` already called these four by
56
+ * their correct `auth.api` names directly (it never went through a
57
+ * path-keyed cast), so there is no method-name bug to fix here.
58
+ * 2. `sessions.activeOrganizationId` does not exist on this repo's
59
+ * Drizzle schema. Ignite's original `getActiveWorkspace()` called
60
+ * `auth.api.getFullOrganization({ headers })` with no
61
+ * `organizationId` — the exact bug documented in
62
+ * `../team/service.ts`'s module comment: that resolves to *no*
63
+ * organization regardless of what the caller most recently
64
+ * activated. This service's `getActiveWorkspace` instead resolves
65
+ * the caller's workspace via `requireWorkspace()` first (which has
66
+ * its own explicit-id fallback) and passes that id explicitly to
67
+ * `getFullOrganization`.
68
+ */
69
+
70
+ import { headers } from "next/headers";
71
+ import type { ZodType } from "zod";
72
+ import { createLogger } from "@intelligo-dev/core/logger";
73
+
74
+ import { auth } from "../server";
75
+ import { requireAuth, requireRole, requireWorkspace } from "../helpers";
76
+ import { orgApi, type OrgListItem } from "../org-api";
77
+ import {
78
+ createWorkspaceSchema,
79
+ updateWorkspaceSchema,
80
+ type CreateWorkspaceInput,
81
+ type UpdateWorkspaceInput,
82
+ } from "./schemas";
83
+ import { WorkspaceServiceError, isWorkspaceServiceError } from "./errors";
84
+
85
+ const log = createLogger("WorkspaceService");
86
+
87
+ /** Minimal organization shape returned by create/update/getActiveWorkspace. */
88
+ export interface WorkspaceRecord {
89
+ id: string;
90
+ name: string;
91
+ slug: string;
92
+ logo?: string | null;
93
+ [key: string]: unknown;
94
+ }
95
+
96
+ export type WorkspaceServicePorts = {
97
+ /**
98
+ * Plan-defined workspace cap for the caller. No port ⇒ unlimited (no
99
+ * gate applied) — matches "no billing dependency without one bound
100
+ * explicitly" (ADR-0005). Not consulted when the caller has zero
101
+ * existing workspaces (their first workspace is always allowed) —
102
+ * see the module doc comment for why the port is keyed by `userId`
103
+ * rather than `workspaceId`.
104
+ */
105
+ checkWorkspaceLimit?: (
106
+ userId: string,
107
+ currentCount: number
108
+ ) => Promise<{ allowed: boolean; limit: number }>;
109
+ };
110
+
111
+ function errorMessage(error: unknown): string {
112
+ return error instanceof Error ? error.message : String(error);
113
+ }
114
+
115
+ /** Maps requireAuth/requireWorkspace/requireRole failures to `forbidden`. */
116
+ function toForbidden(error: unknown): WorkspaceServiceError {
117
+ if (isWorkspaceServiceError(error)) return error;
118
+ return new WorkspaceServiceError("forbidden", errorMessage(error), {
119
+ cause: error,
120
+ });
121
+ }
122
+
123
+ function parseInput<T>(schema: ZodType<T>, input: unknown): T {
124
+ const result = schema.safeParse(input);
125
+ if (!result.success) {
126
+ throw new WorkspaceServiceError(
127
+ "invalid_input",
128
+ result.error.issues.map((issue) => issue.message).join("; ") ||
129
+ "Invalid input",
130
+ { cause: result.error }
131
+ );
132
+ }
133
+ return result.data;
134
+ }
135
+
136
+ /** Derives a URL-safe slug base from a workspace name. */
137
+ function slugify(name: string): string {
138
+ return name
139
+ .toLowerCase()
140
+ .replace(/[^a-z0-9-]/g, "-")
141
+ .replace(/-+/g, "-")
142
+ .slice(0, 50);
143
+ }
144
+
145
+ export function createWorkspaceService(ports: WorkspaceServicePorts = {}) {
146
+ async function callRequireAuth() {
147
+ try {
148
+ return await requireAuth();
149
+ } catch (error) {
150
+ throw toForbidden(error);
151
+ }
152
+ }
153
+
154
+ async function callRequireWorkspace() {
155
+ try {
156
+ return await requireWorkspace();
157
+ } catch (error) {
158
+ throw toForbidden(error);
159
+ }
160
+ }
161
+
162
+ async function callRequireRole(
163
+ allowedRoles: Array<"owner" | "admin" | "member">
164
+ ) {
165
+ try {
166
+ return await requireRole(allowedRoles);
167
+ } catch (error) {
168
+ throw toForbidden(error);
169
+ }
170
+ }
171
+
172
+ /** Wraps a Better-Auth org-plugin call; unrecognized failures become `provider_error`. */
173
+ async function callOrgApi<T>(
174
+ context: string,
175
+ fn: () => Promise<T>
176
+ ): Promise<T> {
177
+ try {
178
+ return await fn();
179
+ } catch (error) {
180
+ if (isWorkspaceServiceError(error)) throw error;
181
+ log.error("Org API call failed", { context, error: errorMessage(error) });
182
+ throw new WorkspaceServiceError(
183
+ "provider_error",
184
+ `Better-Auth organization API call failed (${context})`,
185
+ { cause: error }
186
+ );
187
+ }
188
+ }
189
+
190
+ /**
191
+ * List all workspaces for the current user.
192
+ */
193
+ async function listWorkspaces(): Promise<OrgListItem[]> {
194
+ await callRequireAuth();
195
+ const hdrs = await headers();
196
+
197
+ const orgs = await callOrgApi("list", () =>
198
+ orgApi["/organization/list"]({ headers: hdrs })
199
+ );
200
+
201
+ return orgs ?? [];
202
+ }
203
+
204
+ /**
205
+ * Create a new workspace. Auto-generates a slug from the name if not
206
+ * provided, and appends a uniqueness suffix (Better-Auth requires
207
+ * unique slugs). The caller's first workspace is always allowed; the
208
+ * limit port, when bound, gates every workspace after that. The new
209
+ * workspace is auto-activated on success.
210
+ */
211
+ async function createWorkspace(
212
+ input: CreateWorkspaceInput
213
+ ): Promise<WorkspaceRecord> {
214
+ const { user } = await callRequireAuth();
215
+ const validated = parseInput(createWorkspaceSchema, input);
216
+ const hdrs = await headers();
217
+
218
+ const existing = await callOrgApi("list", () =>
219
+ orgApi["/organization/list"]({ headers: hdrs })
220
+ );
221
+ const existingCount = existing?.length ?? 0;
222
+
223
+ if (ports.checkWorkspaceLimit && existingCount > 0) {
224
+ const limitCheck = await ports.checkWorkspaceLimit(
225
+ user.id,
226
+ existingCount
227
+ );
228
+ if (!limitCheck.allowed) {
229
+ throw new WorkspaceServiceError(
230
+ "workspace_limit_reached",
231
+ `Your plan allows up to ${limitCheck.limit} workspace${
232
+ limitCheck.limit === 1 ? "" : "s"
233
+ }. Upgrade to create more workspaces.`,
234
+ { meta: { limit: limitCheck.limit } }
235
+ );
236
+ }
237
+ }
238
+
239
+ const slugBase = validated.slug || slugify(validated.name);
240
+ // Append timestamp for uniqueness (Better-Auth requires unique slugs).
241
+ const slug = `${slugBase}-${Date.now().toString(36)}`;
242
+
243
+ const org = (await callOrgApi("create", () =>
244
+ auth.api.createOrganization({
245
+ headers: hdrs,
246
+ body: { name: validated.name, slug },
247
+ })
248
+ )) as WorkspaceRecord | null;
249
+
250
+ if (!org) {
251
+ throw new WorkspaceServiceError(
252
+ "provider_error",
253
+ "Failed to create workspace"
254
+ );
255
+ }
256
+
257
+ await callOrgApi("set-active", () =>
258
+ orgApi["/organization/set-active"]({
259
+ headers: hdrs,
260
+ body: { organizationId: org.id },
261
+ })
262
+ );
263
+
264
+ return org;
265
+ }
266
+
267
+ /**
268
+ * Switch the caller's active workspace.
269
+ */
270
+ async function switchWorkspace(organizationId: string): Promise<void> {
271
+ await callRequireAuth();
272
+
273
+ if (typeof organizationId !== "string" || organizationId.length === 0) {
274
+ throw new WorkspaceServiceError("invalid_input", "Invalid workspace id");
275
+ }
276
+
277
+ const hdrs = await headers();
278
+
279
+ await callOrgApi("set-active", () =>
280
+ orgApi["/organization/set-active"]({
281
+ headers: hdrs,
282
+ body: { organizationId },
283
+ })
284
+ );
285
+ }
286
+
287
+ /**
288
+ * Update workspace settings (name/slug/logo). Owner/admin only.
289
+ */
290
+ async function updateWorkspace(
291
+ input: UpdateWorkspaceInput
292
+ ): Promise<WorkspaceRecord> {
293
+ const { workspace } = await callRequireRole(["owner", "admin"]);
294
+ const validated = parseInput(updateWorkspaceSchema, input);
295
+ const hdrs = await headers();
296
+
297
+ const updateData: { name?: string; slug?: string; logo?: string } = {};
298
+ if (validated.name) updateData.name = validated.name;
299
+ if (validated.slug) updateData.slug = validated.slug;
300
+ if (validated.logo) updateData.logo = validated.logo;
301
+
302
+ const result = (await callOrgApi("update", () =>
303
+ auth.api.updateOrganization({
304
+ headers: hdrs,
305
+ body: { data: updateData, organizationId: workspace.id },
306
+ })
307
+ )) as WorkspaceRecord | null;
308
+
309
+ if (!result) {
310
+ throw new WorkspaceServiceError(
311
+ "provider_error",
312
+ "Failed to update workspace"
313
+ );
314
+ }
315
+
316
+ return result;
317
+ }
318
+
319
+ /**
320
+ * Delete the caller's active workspace. Owner only. Switches the
321
+ * caller to another workspace afterward, if one remains.
322
+ */
323
+ async function deleteWorkspace(): Promise<void> {
324
+ const { workspace } = await callRequireRole(["owner"]);
325
+ const hdrs = await headers();
326
+
327
+ await callOrgApi("delete", () =>
328
+ auth.api.deleteOrganization({
329
+ headers: hdrs,
330
+ body: { organizationId: workspace.id },
331
+ })
332
+ );
333
+
334
+ const orgs = await callOrgApi("list", () =>
335
+ orgApi["/organization/list"]({ headers: hdrs })
336
+ );
337
+ if (orgs && orgs.length > 0) {
338
+ await callOrgApi("set-active", () =>
339
+ orgApi["/organization/set-active"]({
340
+ headers: hdrs,
341
+ body: { organizationId: orgs[0]!.id },
342
+ })
343
+ );
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Get the caller's active workspace, fully resolved. Unlike
349
+ * ignite's original (see the module doc comment), this resolves the
350
+ * workspace id explicitly via `requireWorkspace()` rather than
351
+ * relying on a non-existent `sessions.activeOrganizationId` fallback.
352
+ */
353
+ async function getActiveWorkspace(): Promise<WorkspaceRecord> {
354
+ const { workspace } = await callRequireWorkspace();
355
+ const hdrs = await headers();
356
+
357
+ const org = (await callOrgApi("getFullOrganization", () =>
358
+ auth.api.getFullOrganization({
359
+ headers: hdrs,
360
+ query: { organizationId: workspace.id },
361
+ })
362
+ )) as WorkspaceRecord | null;
363
+
364
+ if (!org) {
365
+ throw new WorkspaceServiceError("not_found", "Workspace not found");
366
+ }
367
+
368
+ return org;
369
+ }
370
+
371
+ return {
372
+ listWorkspaces,
373
+ createWorkspace,
374
+ switchWorkspace,
375
+ updateWorkspace,
376
+ deleteWorkspace,
377
+ getActiveWorkspace,
378
+ };
379
+ }
380
+
381
+ export type WorkspaceService = ReturnType<typeof createWorkspaceService>;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Workspace Initialization
3
+ *
4
+ * Ensures every authenticated user has at least one workspace.
5
+ * Called from the (app) layout to guarantee workspace exists.
6
+ * Idempotent - safe to call on every page load.
7
+ *
8
+ * Pattern: "Belt-and-suspenders" approach consistent with Phase 9.
9
+ * Better-Auth doesn't provide a reliable hook for post-signup workspace creation,
10
+ * so we check + create on every authenticated page load.
11
+ *
12
+ * Dependency Inversion (Phase 42, PKG-01 preparation):
13
+ * Post-creation logic (e.g., trial provisioning) is injected via callback,
14
+ * so this module has ZERO billing imports. The actual billing call lives
15
+ * in the consumer application's authenticated layout, which already
16
+ * imports billing.
17
+ * This breaks the auth → billing circular dependency before Phase 43 extraction.
18
+ */
19
+
20
+ import { auth } from "./server";
21
+ import type { User } from "better-auth/types";
22
+ import { createLogger } from "@intelligo-dev/core/logger";
23
+
24
+ const log = createLogger("WorkspaceInit");
25
+
26
+ /**
27
+ * Ensure user has at least one workspace (WORK-01).
28
+ *
29
+ * If user has organizations, sets the first as active. If none exist,
30
+ * creates a personal workspace — this serves as a fallback in case the
31
+ * user.create hook (server.ts databaseHooks) hasn't completed yet, and
32
+ * also handles users created via non-Better-Auth flows (e.g. admin panel).
33
+ *
34
+ * Idempotent - safe to call repeatedly. Returns quickly if workspace exists.
35
+ *
36
+ * @param user - Authenticated user from session
37
+ * @param headers - Request headers (required for Better-Auth API)
38
+ * @param options.onWorkspaceCreated - Optional callback invoked after a new workspace is created.
39
+ * Receives workspaceId and email. Failure does NOT block workspace creation (same fire-and-forget
40
+ * behavior as the previous inline trial provisioning call).
41
+ * @returns The organization ID that was set as active (useful for immediate access before session updates)
42
+ */
43
+ export async function ensureUserWorkspace(
44
+ user: User,
45
+ headers: Headers,
46
+ options?: {
47
+ onWorkspaceCreated?: (params: {
48
+ workspaceId: string;
49
+ email: string;
50
+ }) => Promise<void>;
51
+ }
52
+ ): Promise<string> {
53
+ log.info("Starting workspace check", { email: user.email });
54
+
55
+ // Check if user has any organizations
56
+ const orgs = await auth.api.listOrganizations({
57
+ headers,
58
+ });
59
+
60
+ log.info("Found organizations", { count: orgs?.length ?? 0 });
61
+
62
+ if (orgs && orgs.length > 0 && orgs[0]) {
63
+ log.debug("User has workspaces, setting first as active");
64
+ // User has workspaces - ensure one is active
65
+ try {
66
+ await auth.api.setActiveOrganization({
67
+ headers,
68
+ body: { organizationId: orgs[0].id },
69
+ });
70
+ log.info("Set active organization", { orgId: orgs[0].id });
71
+ } catch (error) {
72
+ log.error("Failed to set active organization", {
73
+ error: error instanceof Error ? error.message : String(error),
74
+ });
75
+ throw error;
76
+ }
77
+ return orgs[0].id;
78
+ }
79
+
80
+ // TR-DB03 fix: No organizations found — the user.create hook may not have
81
+ // completed yet, or user was created via a non-Better-Auth flow.
82
+ // Create the workspace here as a fallback rather than throwing.
83
+ // Idempotent: the unique constraint on organization.slug prevents duplicates
84
+ // if both this fallback and the hook fire for the same signup.
85
+ log.warn("No workspace found, creating one (hook may still fire)", {
86
+ email: user.email,
87
+ });
88
+ const slug = ((user.email || "user").split("@")[0] || "user")
89
+ .toLowerCase()
90
+ .replace(/[^a-z0-9-]/g, "-")
91
+ .slice(0, 30);
92
+
93
+ let workspaceId: string;
94
+ try {
95
+ const result = await auth.api.createOrganization({
96
+ headers,
97
+ body: {
98
+ name: `${user.name || "User"}'s Workspace`,
99
+ slug: `${slug}-${Date.now().toString(36)}`,
100
+ userId: user.id,
101
+ },
102
+ });
103
+ if (!result) {
104
+ throw new Error("createOrganization returned no result");
105
+ }
106
+ workspaceId = result.id;
107
+ log.info("Created fallback workspace", { workspaceId });
108
+ } catch (error) {
109
+ // If creation failed because the unique constraint was hit (hook already
110
+ // created), the error message contains the duplicate key info.
111
+ // List orgs again — if one now exists, use it.
112
+ const orgsAfter = await auth.api.listOrganizations({ headers });
113
+ if (orgsAfter && orgsAfter.length > 0 && orgsAfter[0]) {
114
+ log.info("Workspace created concurrently by hook, using it");
115
+ await auth.api.setActiveOrganization({
116
+ headers,
117
+ body: { organizationId: orgsAfter[0].id },
118
+ });
119
+ return orgsAfter[0].id;
120
+ }
121
+ // Genuine failure
122
+ log.error("Failed to create fallback workspace", {
123
+ error: error instanceof Error ? error.message : String(error),
124
+ });
125
+ throw error;
126
+ }
127
+
128
+ // Fire the optional callback (trial credits, referral tracking, etc.)
129
+ if (options?.onWorkspaceCreated) {
130
+ options
131
+ .onWorkspaceCreated({ workspaceId, email: user.email })
132
+ .catch((err) =>
133
+ log.error("onWorkspaceCreated callback failed", {
134
+ error: err instanceof Error ? err.message : String(err),
135
+ })
136
+ );
137
+ }
138
+
139
+ return workspaceId;
140
+ }