@slotform/auth 0.0.0-stage → 0.1.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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/dist/ability/index.d.ts +31 -0
  4. package/dist/ability/index.d.ts.map +1 -0
  5. package/dist/ability/index.js +64 -0
  6. package/dist/ability/index.js.map +1 -0
  7. package/dist/access.d.ts +19 -0
  8. package/dist/access.d.ts.map +1 -0
  9. package/dist/access.js +33 -0
  10. package/dist/access.js.map +1 -0
  11. package/dist/callback-stubs.d.ts +15 -0
  12. package/dist/callback-stubs.d.ts.map +1 -0
  13. package/dist/callback-stubs.js +28 -0
  14. package/dist/callback-stubs.js.map +1 -0
  15. package/dist/client.d.ts +38 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +37 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/index.d.ts +190 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +451 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/infer.d.ts +31 -0
  24. package/dist/infer.d.ts.map +1 -0
  25. package/dist/infer.js +2 -0
  26. package/dist/infer.js.map +1 -0
  27. package/dist/schema/devices.d.ts +404 -0
  28. package/dist/schema/devices.d.ts.map +1 -0
  29. package/dist/schema/devices.js +45 -0
  30. package/dist/schema/devices.js.map +1 -0
  31. package/dist/schema/index.d.ts +679 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +94 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/oauth.d.ts +2062 -0
  36. package/dist/schema/oauth.d.ts.map +1 -0
  37. package/dist/schema/oauth.js +245 -0
  38. package/dist/schema/oauth.js.map +1 -0
  39. package/dist/schema/organization.d.ts +388 -0
  40. package/dist/schema/organization.d.ts.map +1 -0
  41. package/dist/schema/organization.js +75 -0
  42. package/dist/schema/organization.js.map +1 -0
  43. package/dist/schema/passkey.d.ts +215 -0
  44. package/dist/schema/passkey.d.ts.map +1 -0
  45. package/dist/schema/passkey.js +29 -0
  46. package/dist/schema/passkey.js.map +1 -0
  47. package/dist/schema/sets.d.ts +3715 -0
  48. package/dist/schema/sets.d.ts.map +1 -0
  49. package/dist/schema/sets.js +48 -0
  50. package/dist/schema/sets.js.map +1 -0
  51. package/dist/scope.d.ts +36 -0
  52. package/dist/scope.d.ts.map +1 -0
  53. package/dist/scope.js +59 -0
  54. package/dist/scope.js.map +1 -0
  55. package/dist/screens-fixtures.d.ts +148 -0
  56. package/dist/screens-fixtures.d.ts.map +1 -0
  57. package/dist/screens-fixtures.js +122 -0
  58. package/dist/screens-fixtures.js.map +1 -0
  59. package/dist/screens-session.d.ts +4 -0
  60. package/dist/screens-session.d.ts.map +1 -0
  61. package/dist/screens-session.js +24 -0
  62. package/dist/screens-session.js.map +1 -0
  63. package/dist/screens.d.ts +3 -0
  64. package/dist/screens.d.ts.map +1 -0
  65. package/dist/screens.js +8 -0
  66. package/dist/screens.js.map +1 -0
  67. package/dist/serve.d.ts +3 -0
  68. package/dist/serve.d.ts.map +1 -0
  69. package/dist/serve.js +44 -0
  70. package/dist/serve.js.map +1 -0
  71. package/dist/types.d.ts +152 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +215 -0
  74. package/dist/types.js.map +1 -0
  75. package/dist/worker/callback-url.d.ts +6 -0
  76. package/dist/worker/callback-url.d.ts.map +1 -0
  77. package/dist/worker/callback-url.js +57 -0
  78. package/dist/worker/callback-url.js.map +1 -0
  79. package/dist/worker/cimd-transport.d.ts +2 -0
  80. package/dist/worker/cimd-transport.d.ts.map +1 -0
  81. package/dist/worker/cimd-transport.js +86 -0
  82. package/dist/worker/cimd-transport.js.map +1 -0
  83. package/dist/worker/devices.d.ts +6 -0
  84. package/dist/worker/devices.d.ts.map +1 -0
  85. package/dist/worker/devices.js +70 -0
  86. package/dist/worker/devices.js.map +1 -0
  87. package/dist/worker/email-key.d.ts +2 -0
  88. package/dist/worker/email-key.d.ts.map +1 -0
  89. package/dist/worker/email-key.js +20 -0
  90. package/dist/worker/email-key.js.map +1 -0
  91. package/dist/worker/index.d.ts +156 -0
  92. package/dist/worker/index.d.ts.map +1 -0
  93. package/dist/worker/index.js +507 -0
  94. package/dist/worker/index.js.map +1 -0
  95. package/dist/worker/listener.d.ts +12 -0
  96. package/dist/worker/listener.d.ts.map +1 -0
  97. package/dist/worker/listener.js +37 -0
  98. package/dist/worker/listener.js.map +1 -0
  99. package/dist/worker/oauth.d.ts +95 -0
  100. package/dist/worker/oauth.d.ts.map +1 -0
  101. package/dist/worker/oauth.js +456 -0
  102. package/dist/worker/oauth.js.map +1 -0
  103. package/dist/worker/outputs.d.ts +75 -0
  104. package/dist/worker/outputs.d.ts.map +1 -0
  105. package/dist/worker/outputs.js +7 -0
  106. package/dist/worker/outputs.js.map +1 -0
  107. package/dist/worker/procedures.d.ts +360 -0
  108. package/dist/worker/procedures.d.ts.map +1 -0
  109. package/dist/worker/procedures.js +464 -0
  110. package/dist/worker/procedures.js.map +1 -0
  111. package/dist/worker/rate-limit.d.ts +7 -0
  112. package/dist/worker/rate-limit.d.ts.map +1 -0
  113. package/dist/worker/rate-limit.js +49 -0
  114. package/dist/worker/rate-limit.js.map +1 -0
  115. package/dist/worker/reserved-slugs.d.ts +4 -0
  116. package/dist/worker/reserved-slugs.d.ts.map +1 -0
  117. package/dist/worker/reserved-slugs.js +30 -0
  118. package/dist/worker/reserved-slugs.js.map +1 -0
  119. package/dist/worker/session-ended.d.ts +6 -0
  120. package/dist/worker/session-ended.d.ts.map +1 -0
  121. package/dist/worker/session-ended.js +10 -0
  122. package/dist/worker/session-ended.js.map +1 -0
  123. package/dist/worker/sign-up-policy.d.ts +20 -0
  124. package/dist/worker/sign-up-policy.d.ts.map +1 -0
  125. package/dist/worker/sign-up-policy.js +65 -0
  126. package/dist/worker/sign-up-policy.js.map +1 -0
  127. package/dist/worker/tenancy.d.ts +23 -0
  128. package/dist/worker/tenancy.d.ts.map +1 -0
  129. package/dist/worker/tenancy.js +133 -0
  130. package/dist/worker/tenancy.js.map +1 -0
  131. package/guide/abilities.md +55 -0
  132. package/guide/add-a-role.md +33 -0
  133. package/guide/callbacks.md +97 -0
  134. package/guide/config.md +84 -0
  135. package/guide/devices.md +85 -0
  136. package/guide/mcp-oauth.md +97 -0
  137. package/guide/organizations.md +114 -0
  138. package/guide/protect-by-scope.md +29 -0
  139. package/guide/scopes.md +87 -0
  140. package/guide/sign-in.md +127 -0
  141. package/package.json +155 -3
  142. package/src/ability/index.ts +174 -0
  143. package/src/access.ts +45 -0
  144. package/src/callback-stubs.ts +45 -0
  145. package/src/client.ts +119 -0
  146. package/src/expo.tsx +275 -0
  147. package/src/index.ts +574 -0
  148. package/src/infer.ts +44 -0
  149. package/src/schema/devices.ts +54 -0
  150. package/src/schema/index.ts +128 -0
  151. package/src/schema/oauth.ts +320 -0
  152. package/src/schema/organization.ts +104 -0
  153. package/src/schema/passkey.ts +38 -0
  154. package/src/schema/sets.ts +73 -0
  155. package/src/scope.ts +135 -0
  156. package/src/screens-fixtures.ts +149 -0
  157. package/src/screens-session.ts +26 -0
  158. package/src/screens.ts +10 -0
  159. package/src/serve.ts +49 -0
  160. package/src/types.ts +313 -0
  161. package/src/worker/callback-url.ts +65 -0
  162. package/src/worker/cimd-transport.ts +115 -0
  163. package/src/worker/devices.ts +83 -0
  164. package/src/worker/email-key.ts +21 -0
  165. package/src/worker/index.ts +945 -0
  166. package/src/worker/listener.ts +55 -0
  167. package/src/worker/oauth.ts +709 -0
  168. package/src/worker/outputs.ts +102 -0
  169. package/src/worker/procedures.ts +758 -0
  170. package/src/worker/rate-limit.ts +64 -0
  171. package/src/worker/reserved-slugs.ts +39 -0
  172. package/src/worker/session-ended.ts +14 -0
  173. package/src/worker/sign-up-policy.ts +88 -0
  174. package/src/worker/tenancy.ts +229 -0
  175. package/templates/callbacks.ts +40 -0
@@ -0,0 +1,758 @@
1
+ import type { apiKey } from "@better-auth/api-key";
2
+ import type { oauthProvider } from "@better-auth/oauth-provider";
3
+ import { createMongoAbility } from "@casl/ability";
4
+ import { ORPCError } from "@orpc/server";
5
+ import { noSuch, type ProcedureFactory } from "@slotform/api/procedure";
6
+ import { z } from "@slotform/api/schema";
7
+ import type { Procedure } from "@slotform/api/types";
8
+ import { getTableName } from "@slotform/db/orm";
9
+ import { isAPIError } from "better-auth/api";
10
+ import type { betterAuth } from "better-auth/minimal";
11
+ import type { role as buildAcRole } from "better-auth/plugins/access";
12
+ import type { emailOTP } from "better-auth/plugins/email-otp";
13
+ import type { magicLink } from "better-auth/plugins/magic-link";
14
+ import type { DefaultOrganizationPlugin } from "better-auth/plugins/organization";
15
+ import {
16
+ compileStatements,
17
+ type PackedRuleSet,
18
+ packAbility,
19
+ } from "../ability/index.ts";
20
+ import {
21
+ organization as organizationScope,
22
+ type Scope,
23
+ type ScopeContext,
24
+ } from "../scope.ts";
25
+ import { type RedirectInput, unsafeCallbackField } from "./callback-url.ts";
26
+ import { DEVICE_EXPIRES_MAX_DAYS, DEVICE_NAME_MAX } from "./devices.ts";
27
+ import { emailKey } from "./email-key.ts";
28
+ import type { OAuth } from "./oauth.ts";
29
+ import type {
30
+ AcceptedInvitation,
31
+ ActiveOrganization,
32
+ CreatedDevice,
33
+ Device,
34
+ Invitation,
35
+ OAuthClientPublic,
36
+ OAuthGrant,
37
+ RejectedInvitation,
38
+ } from "./outputs.ts";
39
+ import type { AuthRateLimiter } from "./rate-limit.ts";
40
+ import { resolveGrants, type Tenancy } from "./tenancy.ts";
41
+
42
+ // The most devices one member holds at once.
43
+ const DEVICES_MAX = 25;
44
+
45
+ // The oRPC face of better-auth: one procedure per endpoint a web app calls,
46
+ // so the app never imports better-auth's client. Each runs the endpoint on
47
+ // the server API with the request's headers, copies the cookies it sets onto
48
+ // the response and answers the endpoint's body.
49
+
50
+ // The server API of an instance with every plugin a procedure here calls
51
+ // into. `roles` is `Record<string, ...>` so a role is a `string`, as the
52
+ // consumer's own roles are: the default instance types it as owner, admin or
53
+ // member.
54
+ type FullApi = ReturnType<
55
+ typeof betterAuth<{
56
+ plugins: [
57
+ ReturnType<typeof emailOTP>,
58
+ ReturnType<typeof magicLink>,
59
+ ReturnType<typeof oauthProvider>,
60
+ ReturnType<typeof apiKey>,
61
+ DefaultOrganizationPlugin<{
62
+ roles: Record<string, ReturnType<typeof buildAcRole>>;
63
+ }>,
64
+ ];
65
+ }>
66
+ >["api"];
67
+
68
+ // What the procedures read off the request context. `tenancy` exists only
69
+ // with organizations on, and only the organization procedures use it.
70
+ export type AuthProcedureFactory = ProcedureFactory<
71
+ {
72
+ tenancy: Tenancy;
73
+ oauth: OAuth;
74
+ reqHeaders: Headers;
75
+ resHeaders: Headers;
76
+ auth: { api: FullApi };
77
+ _rateLimiter?: AuthRateLimiter;
78
+ _devMode?: boolean;
79
+ _trustedOrigins?: readonly string[];
80
+ },
81
+ Record<string, readonly string[]>
82
+ >;
83
+
84
+ interface CallContext {
85
+ reqHeaders: Headers;
86
+ resHeaders: Headers;
87
+ }
88
+
89
+ interface CallOptions {
90
+ headers: Headers;
91
+ returnHeaders: true;
92
+ }
93
+
94
+ const ORPC_CODES: Record<number, ORPCError<string, unknown>["code"]> = {
95
+ 400: "BAD_REQUEST",
96
+ 401: "UNAUTHORIZED",
97
+ 403: "FORBIDDEN",
98
+ 404: "NOT_FOUND",
99
+ 429: "TOO_MANY_REQUESTS",
100
+ };
101
+
102
+ // A better-auth refusal keeps its status, message and `code`; its other body
103
+ // fields (a form's `fieldErrors`) ride along as the error's data.
104
+ function refusal(error: unknown): unknown {
105
+ if (!isAPIError(error)) return error;
106
+ const { message, cause, ...data } = error.body ?? {};
107
+ return new ORPCError(
108
+ ORPC_CODES[error.statusCode] ?? "INTERNAL_SERVER_ERROR",
109
+ {
110
+ message: message ?? error.message,
111
+ data,
112
+ },
113
+ );
114
+ }
115
+
116
+ // Runs one endpoint as the caller: its `set-cookie` headers go to the
117
+ // response, its body comes back, its `APIError` becomes an `ORPCError`.
118
+ async function callAuth<R>(
119
+ context: CallContext,
120
+ endpoint: (
121
+ options: CallOptions,
122
+ ) => Promise<{ headers: Headers | undefined; response: R }>,
123
+ ): Promise<R> {
124
+ try {
125
+ const { headers, response } = await endpoint({
126
+ headers: context.reqHeaders,
127
+ returnHeaders: true,
128
+ });
129
+ // A hook that answers for the endpoint (a device key standing in for
130
+ // the session on `get-session`) sets no headers.
131
+ for (const cookie of headers?.getSetCookie() ?? []) {
132
+ context.resHeaders.append("set-cookie", cookie);
133
+ }
134
+ return response;
135
+ } catch (error) {
136
+ throw refusal(error);
137
+ }
138
+ }
139
+
140
+ // The per-email limit shared with the `fetch` handler: docs/architecture/plugins/auth.md, "Rate limiting".
141
+ async function limitEmail(
142
+ context: {
143
+ _rateLimiter?: AuthRateLimiter;
144
+ _devMode?: boolean;
145
+ },
146
+ email: string,
147
+ ): Promise<void> {
148
+ const limiter = context._rateLimiter?.email;
149
+ if (!limiter || context._devMode) return;
150
+ const { success } = await limiter.limit({ key: emailKey(email) });
151
+ if (!success) {
152
+ throw new ORPCError("TOO_MANY_REQUESTS", {
153
+ message: "Rate limit exceeded. Please try again later.",
154
+ });
155
+ }
156
+ }
157
+
158
+ // The calls here run on the server API without the request, which skips
159
+ // better-auth's origin check; a redirect the member's link carries is checked
160
+ // here against the origins the instance trusts (a path on the app always
161
+ // passes). With none known, only paths pass.
162
+ function assertRedirects(
163
+ context: { _trustedOrigins?: readonly string[] },
164
+ input: RedirectInput,
165
+ ): void {
166
+ const field = unsafeCallbackField(input, context._trustedOrigins ?? []);
167
+ if (field) {
168
+ throw new ORPCError("BAD_REQUEST", {
169
+ message: `\`${field}\` must be a path on this app or a URL on a trusted origin.`,
170
+ data: { code: "INVALID_CALLBACK_URL", field },
171
+ });
172
+ }
173
+ }
174
+
175
+ const EMAIL = z.email();
176
+
177
+ // With `mcp`, an authorization sends the member to the app's sign-in,
178
+ // organization and consent pages carrying a signed query. Better Auth's
179
+ // OAuth provider client plugin copies it (`buildSignedOAuthQuery` of the
180
+ // page's search) into the body of every non-GET call as `oauth_query`; the
181
+ // provider's hooks verify it and, once a call signs the member in, answer
182
+ // `{ redirect: true, url }` for the app to follow. `oauthQuery` is that
183
+ // string, passed to the endpoint as `oauth_query`.
184
+ const OAUTH_QUERY = z.string().min(1).optional();
185
+
186
+ // The answer of a call made inside an authorization.
187
+ export interface OAuthRedirect {
188
+ redirect: true;
189
+ url: string;
190
+ }
191
+
192
+ function withOAuthQuery<T extends object>(
193
+ body: T,
194
+ oauthQuery: string | undefined,
195
+ ) {
196
+ return { ...body, oauth_query: oauthQuery };
197
+ }
198
+ // Metadata is the app's own JSON; the endpoint stores it as given.
199
+ const METADATA = z.record(z.string(), z.unknown());
200
+
201
+ // ---------- always on ----------
202
+
203
+ export function sessionProcedures(factory: AuthProcedureFactory) {
204
+ return {
205
+ session: factory({ reads: ["session"] })
206
+ .input(
207
+ z.object({ disableCookieCache: z.boolean().optional() }).optional(),
208
+ )
209
+ .query(({ input, context }) =>
210
+ callAuth(context, (options) =>
211
+ context.auth.api.getSession({
212
+ ...options,
213
+ query: { disableCookieCache: input?.disableCookieCache },
214
+ }),
215
+ ),
216
+ ),
217
+ signOut: factory({ writes: ["session"] }).mutation(({ context }) =>
218
+ callAuth(context, (options) => context.auth.api.signOut(options)),
219
+ ),
220
+ user: {
221
+ update: factory({ auth: true, writes: ["session", "member"] })
222
+ .input(
223
+ z.object({
224
+ name: z.string().min(1).optional(),
225
+ image: z.string().nullable().optional(),
226
+ }),
227
+ )
228
+ .mutation(({ input, context }) =>
229
+ callAuth(context, (options) =>
230
+ context.auth.api.updateUser({ ...options, body: input }),
231
+ ),
232
+ ),
233
+ },
234
+ };
235
+ }
236
+
237
+ // ---------- emailOtp ----------
238
+
239
+ // The code's digits, which the plugin pins to the same length.
240
+ export const OTP_LENGTH = 6;
241
+
242
+ const VERIFY_OTP_INPUT = z.object({
243
+ email: EMAIL,
244
+ otp: z.string().length(OTP_LENGTH),
245
+ name: z.string().optional(),
246
+ image: z.string().optional(),
247
+ });
248
+
249
+ export function emailOtpProcedures(factory: AuthProcedureFactory) {
250
+ return {
251
+ sendOtp: factory()
252
+ .input(z.object({ email: EMAIL }))
253
+ .mutation(async ({ input, context }) => {
254
+ await limitEmail(context, input.email);
255
+ return callAuth(context, (options) =>
256
+ context.auth.api.sendVerificationOTP({
257
+ ...options,
258
+ body: { email: input.email, type: "sign-in" },
259
+ }),
260
+ );
261
+ }),
262
+ verifyOtp: factory({ writes: ["session"] })
263
+ .input(VERIFY_OTP_INPUT)
264
+ .mutation(({ input, context }) =>
265
+ callAuth(context, (options) =>
266
+ context.auth.api.signInEmailOTP({ ...options, body: input }),
267
+ ),
268
+ ),
269
+ };
270
+ }
271
+
272
+ // With `mcp`: `verifyOtp` takes the page's signed query and may answer the
273
+ // redirect that resumes the authorization.
274
+ export function emailOtpOauthProcedures(factory: AuthProcedureFactory) {
275
+ return {
276
+ ...emailOtpProcedures(factory),
277
+ verifyOtp: factory({ writes: ["session"] })
278
+ .input(VERIFY_OTP_INPUT.extend({ oauthQuery: OAUTH_QUERY }))
279
+ .mutation(({ input: { oauthQuery, ...input }, context }) =>
280
+ callAuth<
281
+ Awaited<ReturnType<FullApi["signInEmailOTP"]>> | OAuthRedirect
282
+ >(context, (options) =>
283
+ context.auth.api.signInEmailOTP({
284
+ ...options,
285
+ body: withOAuthQuery(input, oauthQuery),
286
+ }),
287
+ ),
288
+ ),
289
+ };
290
+ }
291
+
292
+ // ---------- magicLink ----------
293
+
294
+ const MAGIC_LINK_INPUT = z.object({
295
+ email: EMAIL,
296
+ name: z.string().optional(),
297
+ callbackURL: z.string().optional(),
298
+ newUserCallbackURL: z.string().optional(),
299
+ errorCallbackURL: z.string().optional(),
300
+ metadata: METADATA.optional(),
301
+ });
302
+
303
+ export function magicLinkProcedures(factory: AuthProcedureFactory) {
304
+ return {
305
+ magicLink: factory()
306
+ .input(MAGIC_LINK_INPUT)
307
+ .mutation(async ({ input, context }) => {
308
+ assertRedirects(context, input);
309
+ await limitEmail(context, input.email);
310
+ return callAuth(context, (options) =>
311
+ context.auth.api.signInMagicLink({ ...options, body: input }),
312
+ );
313
+ }),
314
+ };
315
+ }
316
+
317
+ // With `mcp`, as `emailOtpOauthProcedures`.
318
+ export function magicLinkOauthProcedures(factory: AuthProcedureFactory) {
319
+ return {
320
+ magicLink: factory()
321
+ .input(MAGIC_LINK_INPUT.extend({ oauthQuery: OAUTH_QUERY }))
322
+ .mutation(async ({ input: { oauthQuery, ...input }, context }) => {
323
+ assertRedirects(context, input);
324
+ await limitEmail(context, input.email);
325
+ return callAuth<
326
+ Awaited<ReturnType<FullApi["signInMagicLink"]>> | OAuthRedirect
327
+ >(context, (options) =>
328
+ context.auth.api.signInMagicLink({
329
+ ...options,
330
+ body: withOAuthQuery(input, oauthQuery),
331
+ }),
332
+ );
333
+ }),
334
+ };
335
+ }
336
+
337
+ // ---------- organization ----------
338
+
339
+ // Better Auth takes any non-empty slug and refuses a taken one; the one this
340
+ // derives from a name is its lowercase words (accents folded away) joined by
341
+ // hyphens.
342
+ function slugOf(name: string): string {
343
+ return name
344
+ .normalize("NFKD")
345
+ .replace(/\p{M}/gu, "")
346
+ .toLowerCase()
347
+ .replace(/[^a-z0-9]+/g, "-")
348
+ .replace(/^-+|-+$/g, "");
349
+ }
350
+
351
+ // A name with no letter or digit derives no slug, and the caller names one.
352
+ function slugFor(input: { name: string; slug?: string }): string {
353
+ const slug = input.slug ?? slugOf(input.name);
354
+ if (slug === "") {
355
+ const message = "Choose an address: the name gives none.";
356
+ throw new ORPCError("BAD_REQUEST", {
357
+ message,
358
+ data: {
359
+ code: "ORGANIZATION_SLUG_REQUIRED",
360
+ fieldErrors: { slug: message },
361
+ },
362
+ });
363
+ }
364
+ return slug;
365
+ }
366
+
367
+ const ORGANIZATION_FIELDS = {
368
+ name: z.string().min(1),
369
+ slug: z.string().min(1),
370
+ logo: z.string().nullable().optional(),
371
+ metadata: METADATA.optional(),
372
+ };
373
+
374
+ const ORGANIZATION_ID = z.string().min(1);
375
+
376
+ const SET_ACTIVE_INPUT = z.object({
377
+ organizationId: ORGANIZATION_ID.nullable().optional(),
378
+ organizationSlug: z.string().min(1).optional(),
379
+ });
380
+
381
+ export function organizationProcedures(factory: AuthProcedureFactory) {
382
+ return {
383
+ organization: {
384
+ list: factory({ auth: true, reads: ["organization", "member"] }).query(
385
+ ({ context }) =>
386
+ callAuth(context, (options) =>
387
+ context.auth.api.listOrganizations(options),
388
+ ),
389
+ ),
390
+ create: factory({
391
+ auth: true,
392
+ writes: ["organization", "member", "session"],
393
+ })
394
+ .input(
395
+ z.object({
396
+ name: ORGANIZATION_FIELDS.name,
397
+ slug: ORGANIZATION_FIELDS.slug.optional(),
398
+ logo: ORGANIZATION_FIELDS.logo,
399
+ metadata: ORGANIZATION_FIELDS.metadata,
400
+ keepCurrentActiveOrganization: z.boolean().optional(),
401
+ }),
402
+ )
403
+ .mutation(({ input, context }) =>
404
+ callAuth(context, (options) =>
405
+ context.auth.api.createOrganization({
406
+ ...options,
407
+ body: { ...input, slug: slugFor(input) },
408
+ }),
409
+ ),
410
+ ),
411
+ update: factory({ auth: true, writes: ["organization"] })
412
+ .input(
413
+ z.object({
414
+ name: ORGANIZATION_FIELDS.name.optional(),
415
+ slug: ORGANIZATION_FIELDS.slug.optional(),
416
+ logo: ORGANIZATION_FIELDS.logo,
417
+ metadata: ORGANIZATION_FIELDS.metadata,
418
+ organizationId: ORGANIZATION_ID.optional(),
419
+ }),
420
+ )
421
+ .mutation(({ input: { organizationId, ...data }, context }) =>
422
+ callAuth(context, (options) =>
423
+ context.auth.api.updateOrganization({
424
+ ...options,
425
+ body: { data, organizationId },
426
+ }),
427
+ ),
428
+ ),
429
+ delete: factory({
430
+ auth: true,
431
+ writes: ["organization", "member", "session"],
432
+ })
433
+ .input(z.object({ organizationId: ORGANIZATION_ID }))
434
+ .mutation(({ input, context }) =>
435
+ callAuth(context, (options) =>
436
+ context.auth.api.deleteOrganization({ ...options, body: input }),
437
+ ),
438
+ ),
439
+ setActive: factory({ auth: true, writes: ["session"] })
440
+ .input(SET_ACTIVE_INPUT)
441
+ .mutation(({ input, context }) =>
442
+ callAuth<ActiveOrganization | null>(context, (options) =>
443
+ context.auth.api.setActiveOrganization({ ...options, body: input }),
444
+ ),
445
+ ),
446
+ activeMember: factory({ auth: true, reads: ["member", "session"] }).query(
447
+ ({ context }) =>
448
+ callAuth(context, (options) =>
449
+ context.auth.api.getActiveMember(options),
450
+ ),
451
+ ),
452
+ members: {
453
+ updateRole: factory({ auth: true, writes: ["member"] })
454
+ .input(
455
+ z.object({
456
+ memberId: z.string().min(1),
457
+ role: z.string().min(1),
458
+ organizationId: ORGANIZATION_ID.optional(),
459
+ }),
460
+ )
461
+ .mutation(({ input, context }) =>
462
+ callAuth(context, (options) =>
463
+ context.auth.api.updateMemberRole({ ...options, body: input }),
464
+ ),
465
+ ),
466
+ remove: factory({ auth: true, writes: ["member"] })
467
+ .input(
468
+ z.object({
469
+ memberIdOrEmail: z.string().min(1),
470
+ organizationId: ORGANIZATION_ID.optional(),
471
+ }),
472
+ )
473
+ .mutation(({ input, context }) =>
474
+ callAuth(context, (options) =>
475
+ context.auth.api.removeMember({ ...options, body: input }),
476
+ ),
477
+ ),
478
+ },
479
+ invitations: {
480
+ create: factory({ auth: true, writes: ["invitation"] })
481
+ .input(
482
+ z.object({
483
+ email: EMAIL,
484
+ role: z.string().min(1),
485
+ organizationId: ORGANIZATION_ID.optional(),
486
+ resend: z.boolean().optional(),
487
+ }),
488
+ )
489
+ .mutation(({ input, context }) =>
490
+ callAuth<Invitation>(context, (options) =>
491
+ context.auth.api.createInvitation({ ...options, body: input }),
492
+ ),
493
+ ),
494
+ cancel: factory({ auth: true, writes: ["invitation"] })
495
+ .input(z.object({ invitationId: z.string().min(1) }))
496
+ .mutation(({ input, context }) =>
497
+ callAuth<Invitation | null>(context, (options) =>
498
+ context.auth.api.cancelInvitation({ ...options, body: input }),
499
+ ),
500
+ ),
501
+ accept: factory({
502
+ auth: true,
503
+ writes: ["invitation", "member", "organization", "session"],
504
+ })
505
+ .input(z.object({ invitationId: z.string().min(1) }))
506
+ .mutation(({ input, context }) =>
507
+ callAuth<AcceptedInvitation>(context, (options) =>
508
+ context.auth.api.acceptInvitation({ ...options, body: input }),
509
+ ),
510
+ ),
511
+ reject: factory({ auth: true, writes: ["invitation"] })
512
+ .input(z.object({ invitationId: z.string().min(1) }))
513
+ .mutation(({ input, context }) =>
514
+ callAuth<RejectedInvitation>(context, (options) =>
515
+ context.auth.api.rejectInvitation({ ...options, body: input }),
516
+ ),
517
+ ),
518
+ },
519
+ },
520
+ };
521
+ }
522
+
523
+ // With `mcp`, `setActive` replaces the organization one: inside an
524
+ // authorization it takes the page's signed query and may answer the redirect
525
+ // that resumes it.
526
+ export function setActiveOauthProcedure(factory: AuthProcedureFactory) {
527
+ return factory({ auth: true, writes: ["session"] })
528
+ .input(SET_ACTIVE_INPUT.extend({ oauthQuery: OAUTH_QUERY }))
529
+ .mutation(({ input: { oauthQuery, ...input }, context }) =>
530
+ callAuth<ActiveOrganization | null | OAuthRedirect>(context, (options) =>
531
+ context.auth.api.setActiveOrganization({
532
+ ...options,
533
+ body: withOAuthQuery(input, oauthQuery),
534
+ }),
535
+ ),
536
+ );
537
+ }
538
+
539
+ // ---------- auth.orgRules and auth.scope.<name>.bySlug ----------
540
+
541
+ // A slug names the organization on its own; below it, a slug is unique only
542
+ // within its parent, whose id comes along.
543
+ const ORGANIZATION_LOOKUP = z.object({ slug: z.string().min(1) });
544
+ const SCOPE_LOOKUP = z.object({
545
+ slug: z.string().min(1),
546
+ parentId: z.string().min(1),
547
+ });
548
+
549
+ // The entities a scope's lookup reads: each table of its chain by its SQL
550
+ // name, which is its entity when the schema exports the table under that
551
+ // name, and the membership the organization tier resolves.
552
+ function scopeReads(scope: Scope): string[] {
553
+ const reads = ["member"];
554
+ for (let level: Scope | undefined = scope; level; level = level.parent?.[0]) {
555
+ reads.push(getTableName(level.table));
556
+ }
557
+ return reads.sort();
558
+ }
559
+
560
+ // `orgRules` reads `member`: docs/architecture/plugins/query.md, "Abilities".
561
+ export function orgRulesProcedure(
562
+ factory: AuthProcedureFactory,
563
+ roles: Record<string, unknown>,
564
+ ) {
565
+ return factory({
566
+ auth: true,
567
+ scope: organizationScope,
568
+ reads: ["member"],
569
+ }).query(async ({ context }): Promise<{ rules: PackedRuleSet }> => {
570
+ const grants = resolveGrants(context.member.role, roles);
571
+ const ability = createMongoAbility(compileStatements(grants));
572
+ return { rules: packAbility(ability) };
573
+ });
574
+ }
575
+
576
+ // A scope's lookup: the slug within its parent, answered by the chain's rows
577
+ // and the caller's `member`.
578
+ export type ScopeLookup<S extends Scope> = Procedure<
579
+ { slug: string } | { slug: string; parentId: string },
580
+ ScopeContext<S>
581
+ >;
582
+
583
+ // A scope lookup is invalidated by writes on its chain: docs/architecture/plugins/auth.md, "Scopes".
584
+ export function bySlugProcedure<S extends Scope>(
585
+ factory: AuthProcedureFactory,
586
+ scope: S,
587
+ ): ScopeLookup<S> {
588
+ return factory({ auth: true, reads: scopeReads(scope) })
589
+ .input(scope.parent ? SCOPE_LOOKUP : ORGANIZATION_LOOKUP)
590
+ .query(async ({ input, context }) => {
591
+ const found = await context.tenancy.bySlug(
592
+ scope,
593
+ input.slug,
594
+ "parentId" in input && typeof input.parentId === "string"
595
+ ? input.parentId
596
+ : undefined,
597
+ context.user.id,
598
+ );
599
+ if (!found) {
600
+ throw noSuch(scope);
601
+ }
602
+ return found;
603
+ });
604
+ }
605
+
606
+ // ---------- mcp ----------
607
+
608
+ export function oauthProcedures(factory: AuthProcedureFactory) {
609
+ return {
610
+ oauth: {
611
+ client: factory({ auth: true })
612
+ .input(z.object({ clientId: z.string().min(1) }))
613
+ .query(({ input, context }) =>
614
+ callAuth<OAuthClientPublic>(context, (options) =>
615
+ context.auth.api.getOAuthClientPublic({
616
+ ...options,
617
+ query: { client_id: input.clientId },
618
+ }),
619
+ ),
620
+ ),
621
+ consent: factory({ auth: true, writes: ["oauthConsent"] })
622
+ .input(
623
+ z.object({
624
+ accept: z.boolean(),
625
+ scope: z.string().optional(),
626
+ oauthQuery: OAUTH_QUERY,
627
+ }),
628
+ )
629
+ .mutation(({ input: { oauthQuery, ...input }, context }) =>
630
+ callAuth(context, (options) =>
631
+ context.auth.api.oauth2Consent({
632
+ ...options,
633
+ body: withOAuthQuery(input, oauthQuery),
634
+ }),
635
+ ),
636
+ ),
637
+ grants: {
638
+ list: factory({
639
+ auth: true,
640
+ reads: ["oauthConsent", "oauthClient"],
641
+ }).query(
642
+ ({ context }): Promise<OAuthGrant[]> =>
643
+ context.oauth.listGrants(context.user.id),
644
+ ),
645
+ // A grant that is not the caller's answers as one that does not exist.
646
+ revoke: factory({ auth: true, writes: ["oauthConsent"] })
647
+ .input(z.object({ id: z.string().min(1) }))
648
+ .mutation(async ({ input, context }) => {
649
+ if (!(await context.oauth.revokeGrant(input.id, context.user.id))) {
650
+ throw new ORPCError("NOT_FOUND");
651
+ }
652
+ }),
653
+ },
654
+ },
655
+ };
656
+ }
657
+
658
+ // ---------- devices ----------
659
+
660
+ // The key row as the plugin lists it, reduced to what `Device` shows.
661
+ interface KeyRow {
662
+ id: string;
663
+ name: string | null;
664
+ start: string | null;
665
+ createdAt: Date;
666
+ expiresAt: Date | null;
667
+ lastRequest: Date | null;
668
+ }
669
+
670
+ function deviceOf(row: KeyRow): Device {
671
+ return {
672
+ id: row.id,
673
+ name: row.name ?? "",
674
+ start: row.start ?? "",
675
+ createdAt: row.createdAt,
676
+ expiresAt: row.expiresAt,
677
+ lastUsedAt: row.lastRequest,
678
+ };
679
+ }
680
+
681
+ const SECONDS_PER_DAY = 86_400;
682
+
683
+ // Device key procedures: docs/architecture/plugins/auth.md, "Devices".
684
+ export function deviceProcedures(factory: AuthProcedureFactory) {
685
+ return {
686
+ devices: {
687
+ list: factory({ auth: true, reads: ["apikey"] }).query(
688
+ async ({ context }): Promise<Device[]> => {
689
+ const { apiKeys } = await callAuth(context, (options) =>
690
+ context.auth.api.listApiKeys(options),
691
+ );
692
+ return apiKeys
693
+ .map(deviceOf)
694
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
695
+ },
696
+ ),
697
+ create: factory({ auth: true, writes: ["apikey"] })
698
+ .input(
699
+ z.object({
700
+ name: z.string().trim().min(1).max(DEVICE_NAME_MAX),
701
+ // Omitted, the key does not expire.
702
+ expiresInDays: z
703
+ .number()
704
+ .int()
705
+ .min(1)
706
+ .max(DEVICE_EXPIRES_MAX_DAYS)
707
+ .optional(),
708
+ }),
709
+ )
710
+ // The limit is counted after the key is made, so two creates that
711
+ // race past it both see the other's key; one over the limit is
712
+ // deleted before it is answered.
713
+ .mutation(async ({ input, context }): Promise<CreatedDevice> => {
714
+ const created = await callAuth(context, (options) =>
715
+ context.auth.api.createApiKey({
716
+ ...options,
717
+ body: {
718
+ name: input.name,
719
+ ...(input.expiresInDays
720
+ ? { expiresIn: input.expiresInDays * SECONDS_PER_DAY }
721
+ : {}),
722
+ },
723
+ }),
724
+ );
725
+ const { apiKeys } = await callAuth(context, (options) =>
726
+ context.auth.api.listApiKeys(options),
727
+ );
728
+ const now = Date.now();
729
+ const live = apiKeys.filter(
730
+ (row) => !row.expiresAt || row.expiresAt.getTime() > now,
731
+ );
732
+ if (live.length > DEVICES_MAX) {
733
+ await callAuth(context, (options) =>
734
+ context.auth.api.deleteApiKey({
735
+ ...options,
736
+ body: { keyId: created.id },
737
+ }),
738
+ );
739
+ throw new ORPCError("BAD_REQUEST", {
740
+ message: `At most ${DEVICES_MAX} devices at once. Revoke one first.`,
741
+ data: { code: "DEVICE_LIMIT" },
742
+ });
743
+ }
744
+ return { device: deviceOf(created), key: created.key };
745
+ }),
746
+ revoke: factory({ auth: true, writes: ["apikey"] })
747
+ .input(z.object({ id: z.string().min(1) }))
748
+ .mutation(({ input, context }) =>
749
+ callAuth(context, (options) =>
750
+ context.auth.api.deleteApiKey({
751
+ ...options,
752
+ body: { keyId: input.id },
753
+ }),
754
+ ),
755
+ ),
756
+ },
757
+ };
758
+ }