@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
package/src/scope.ts ADDED
@@ -0,0 +1,135 @@
1
+ import type { BaseContext } from "@slotform/api/runtime";
2
+ import type {
3
+ InferSelectModel,
4
+ SQL,
5
+ SQLiteColumn,
6
+ SQLiteTable,
7
+ } from "@slotform/db/orm";
8
+ import {
9
+ type member,
10
+ organization as organizationTable,
11
+ } from "./schema/organization.ts";
12
+
13
+ // A tenancy tier is a descriptor: docs/architecture/plugins/api.md, "Scope".
14
+
15
+ type ScopeTable = SQLiteTable & { id: SQLiteColumn };
16
+
17
+ export interface Scope<
18
+ TName extends string = string,
19
+ TContext = unknown,
20
+ TSlug extends SQLiteColumn | null = SQLiteColumn | null,
21
+ > {
22
+ readonly name: TName;
23
+ readonly table: ScopeTable;
24
+ // The scope above and the column on this table holding its id; null at
25
+ // the organization, the root.
26
+ readonly parent: readonly [Scope, SQLiteColumn] | null;
27
+ // The column a URL names the row by, unique within its parent. A scope
28
+ // without one is addressed by id.
29
+ readonly slug: TSlug;
30
+ // Whether the row is visible to the member the root resolved: a fragment
31
+ // over this scope's table, correlated to whatever it needs. Null when
32
+ // every row of the member's organization is visible, as at the root.
33
+ readonly where: ((member: MemberRow) => SQL) | null;
34
+ // Phantom: what resolving the chain adds to a procedure's context.
35
+ readonly __context?: TContext;
36
+ }
37
+
38
+ export type ScopeContext<S> = S extends Scope<string, infer C> ? C : never;
39
+
40
+ export type OrganizationRow = InferSelectModel<typeof organizationTable>;
41
+ export type MemberRow = InferSelectModel<typeof member>;
42
+
43
+ export const organization: Scope<
44
+ "organization",
45
+ { organization: OrganizationRow; member: MemberRow },
46
+ SQLiteColumn
47
+ > = {
48
+ name: "organization",
49
+ table: organizationTable,
50
+ parent: null,
51
+ slug: organizationTable.slug,
52
+ where: null,
53
+ };
54
+
55
+ // Which `member` rows count as a membership: docs/architecture/plugins/auth.md, "Scopes".
56
+ export interface Membership {
57
+ readonly kind: "membership";
58
+ readonly where: SQL;
59
+ }
60
+
61
+ export function defineMembership(where: SQL): Membership {
62
+ return { kind: "membership", where };
63
+ }
64
+
65
+ // Scope names refused: keys of the `api` plugin's base context, checked against its type: docs/architecture/plugins/auth.md, "Scopes".
66
+ type BaseContextKey = keyof {
67
+ [K in keyof BaseContext as string extends K ? never : K]: unknown;
68
+ };
69
+ const BASE_CONTEXT: Record<BaseContextKey, true> = {
70
+ env: true,
71
+ httpRequest: true,
72
+ reqHeaders: true,
73
+ resHeaders: true,
74
+ executionCtx: true,
75
+ };
76
+ // ...and the keys the runtimes and middlewares add before a scope resolves: docs/architecture/plugins/auth.md, "Scopes".
77
+ const RESERVED = new Set([
78
+ ...Object.keys(BASE_CONTEXT),
79
+ "_devMode",
80
+ "db",
81
+ "auth",
82
+ "tenancy",
83
+ "_rateLimiter",
84
+ "_trustedOrigins",
85
+ "user",
86
+ "session",
87
+ "organization",
88
+ "member",
89
+ // The MCP endpoint's verified caller, and the OAuth capability with `mcp`.
90
+ "_caller",
91
+ "oauth",
92
+ ]);
93
+
94
+ export function defineScope<
95
+ const TName extends string,
96
+ TTable extends ScopeTable,
97
+ TParent extends Scope,
98
+ const TSlug extends SQLiteColumn | undefined = undefined,
99
+ >(def: {
100
+ name: TName;
101
+ table: TTable;
102
+ parent: readonly [TParent, SQLiteColumn];
103
+ slug?: TSlug;
104
+ where?: (member: MemberRow) => SQL;
105
+ }): Scope<
106
+ TName,
107
+ ScopeContext<TParent> & { [K in TName]: InferSelectModel<TTable> },
108
+ TSlug extends SQLiteColumn ? TSlug : null
109
+ > {
110
+ if (RESERVED.has(def.name)) {
111
+ throw new Error(
112
+ `defineScope: "${def.name}" is a key of the procedure context; pick another scope name.`,
113
+ );
114
+ }
115
+ for (const [role, column] of [
116
+ ["parent", def.parent[1]],
117
+ ["slug", def.slug],
118
+ ] as const) {
119
+ if (column && column.table !== def.table) {
120
+ throw new Error(
121
+ `defineScope("${def.name}"): the ${role} column belongs to another table.`,
122
+ );
123
+ }
124
+ }
125
+ return {
126
+ name: def.name,
127
+ table: def.table,
128
+ parent: def.parent,
129
+ // `TSlug` is the column when `def.slug` is given and `undefined`
130
+ // otherwise, so this is the conditional return type's own value; tsc
131
+ // cannot reduce that conditional while `TSlug` is open.
132
+ slug: (def.slug ?? null) as TSlug extends SQLiteColumn ? TSlug : null,
133
+ where: def.where ?? null,
134
+ };
135
+ }
@@ -0,0 +1,149 @@
1
+ import type { Fixtures } from "@slotform/screens/fixtures";
2
+ import { session, user } from "./screens-session.ts";
3
+ import {
4
+ DEVICE_KEY_LENGTH,
5
+ DEVICE_KEY_PREFIX,
6
+ type Device,
7
+ type OAuthGrant,
8
+ } from "./worker/outputs.ts";
9
+ import type {
10
+ deviceProcedures,
11
+ emailOtpProcedures,
12
+ magicLinkProcedures,
13
+ oauthProcedures,
14
+ organizationProcedures,
15
+ sessionProcedures,
16
+ } from "./worker/procedures.ts";
17
+
18
+ // The MCP clients a member's list shows: one with a name and an address, one
19
+ // known by its client id alone.
20
+ const grants: OAuthGrant[] = [
21
+ {
22
+ id: "grant_claude",
23
+ name: "Claude",
24
+ uri: "https://claude.ai",
25
+ organizationId: "org_screens",
26
+ scopes: ["mcp", "offline_access"],
27
+ createdAt: new Date("2026-02-12T10:00:00.000Z"),
28
+ },
29
+ {
30
+ id: "grant_inspector",
31
+ name: "https://inspector.example/client.json",
32
+ uri: null,
33
+ organizationId: "org_screens",
34
+ scopes: ["mcp"],
35
+ createdAt: new Date("2026-02-01T08:00:00.000Z"),
36
+ },
37
+ ];
38
+
39
+ // The device keys a member's list shows in the screens workbench: one in use,
40
+ // one never used, one that expired, so a list draws each of its forms.
41
+ const devices: Device[] = [
42
+ {
43
+ id: "device_studio",
44
+ name: "Studio laptop",
45
+ start: `${DEVICE_KEY_PREFIX}stud`,
46
+ createdAt: new Date("2026-02-10T09:00:00.000Z"),
47
+ expiresAt: null,
48
+ lastUsedAt: new Date("2026-02-28T18:30:00.000Z"),
49
+ },
50
+ {
51
+ id: "device_booth",
52
+ name: "Booth laptop",
53
+ start: `${DEVICE_KEY_PREFIX}boot`,
54
+ createdAt: new Date("2026-02-20T09:00:00.000Z"),
55
+ expiresAt: new Date("2099-01-01T00:00:00.000Z"),
56
+ lastUsedAt: null,
57
+ },
58
+ {
59
+ id: "device_old",
60
+ name: "Old desktop",
61
+ start: `${DEVICE_KEY_PREFIX}oldd`,
62
+ createdAt: new Date("2025-06-01T09:00:00.000Z"),
63
+ expiresAt: new Date("2025-12-01T09:00:00.000Z"),
64
+ lastUsedAt: new Date("2025-11-30T12:00:00.000Z"),
65
+ },
66
+ ];
67
+
68
+ const organization = {
69
+ id: "org_screens",
70
+ name: "Studio",
71
+ slug: "studio",
72
+ createdAt: new Date("2026-01-05T09:00:00.000Z"),
73
+ logo: null,
74
+ metadata: undefined,
75
+ };
76
+
77
+ const activeOrganization = { ...organization, members: [], invitations: [] };
78
+
79
+ // The workbench's `auth.*` fixtures: docs/architecture/plugins/auth.md, "Screens".
80
+ const fixtures = {
81
+ auth: {
82
+ session: () => ({ session, user }),
83
+ // The sign-in steps, answered as a sent code or link and a verified code.
84
+ signIn: {
85
+ sendOtp: () => ({ success: true }),
86
+ verifyOtp: () => ({ token: session.token, user }),
87
+ magicLink: () => ({ status: true }),
88
+ },
89
+ signOut: () => ({ success: true, url: undefined, redirect: undefined }),
90
+ // The client an MCP connect page asks consent for.
91
+ oauth: {
92
+ client: () => ({
93
+ client_id: "client_screens",
94
+ client_name: "Claude",
95
+ client_uri: "https://claude.ai",
96
+ }),
97
+ consent: () => ({ redirect: true, url: "https://example.com/callback" }),
98
+ grants: {
99
+ list: (): OAuthGrant[] => grants,
100
+ revoke: () => undefined,
101
+ },
102
+ },
103
+ user: { update: () => ({ status: true }) },
104
+ organization: {
105
+ list: () => [organization],
106
+ setActive: () => activeOrganization,
107
+ create: () => ({ ...activeOrganization, metadata: undefined }),
108
+ delete: () => organization,
109
+ invitations: {
110
+ create: ({ email, role }) => ({
111
+ id: "invitation_screens",
112
+ organizationId: organization.id,
113
+ email,
114
+ role,
115
+ status: "pending" as const,
116
+ inviterId: user.id,
117
+ expiresAt: new Date("2099-01-01T00:00:00.000Z"),
118
+ createdAt: new Date("2026-03-01T09:00:00.000Z"),
119
+ }),
120
+ },
121
+ },
122
+ devices: {
123
+ list: (): Device[] => devices,
124
+ // The one key the answer shows, as the member copies it.
125
+ create: ({ name }) => ({
126
+ device: {
127
+ id: "device_new",
128
+ name,
129
+ start: `${DEVICE_KEY_PREFIX}scre`,
130
+ createdAt: new Date("2026-03-01T09:00:00.000Z"),
131
+ expiresAt: null,
132
+ lastUsedAt: null,
133
+ },
134
+ key: `${DEVICE_KEY_PREFIX}${"screens".padEnd(DEVICE_KEY_LENGTH, "0123456789abcdef")}`,
135
+ }),
136
+ revoke: () => ({ success: true }),
137
+ },
138
+ },
139
+ } satisfies Fixtures<{
140
+ auth: ReturnType<typeof sessionProcedures> &
141
+ ReturnType<typeof deviceProcedures> &
142
+ ReturnType<typeof oauthProcedures> & {
143
+ signIn: ReturnType<typeof emailOtpProcedures> &
144
+ ReturnType<typeof magicLinkProcedures>;
145
+ organization: ReturnType<typeof organizationProcedures>["organization"];
146
+ };
147
+ }>;
148
+
149
+ export default fixtures;
@@ -0,0 +1,26 @@
1
+ import type { Session, User } from "better-auth";
2
+
3
+ // The signed-in session the screens workbench answers with, in one place for
4
+ // both ways a screen reads it: better-auth's `get-session` endpoint
5
+ // (`./screens.ts`) and the `auth.session` procedure (`./screens-fixtures.ts`).
6
+ // Typed by better-auth's own session and user, so a field it adds fails here.
7
+ export const user: User = {
8
+ id: "user_screens",
9
+ name: "Alex Morgan",
10
+ email: "alex.morgan@example.com",
11
+ emailVerified: true,
12
+ image: null,
13
+ createdAt: new Date("2026-01-05T09:00:00.000Z"),
14
+ updatedAt: new Date("2026-01-05T09:00:00.000Z"),
15
+ };
16
+
17
+ export const session: Session = {
18
+ id: "session_screens",
19
+ token: "screens",
20
+ userId: user.id,
21
+ ipAddress: null,
22
+ userAgent: null,
23
+ createdAt: new Date("2026-01-05T09:00:00.000Z"),
24
+ updatedAt: new Date("2026-01-05T09:00:00.000Z"),
25
+ expiresAt: new Date("2099-01-01T00:00:00.000Z"),
26
+ };
package/src/screens.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { HttpResponse, http } from "@slotform/screens/msw";
2
+ import { session, user } from "./screens-session.ts";
3
+ import { AUTH_PREFIX } from "./types.ts";
4
+
5
+ // The workbench's `get-session` handlers: docs/architecture/plugins/auth.md, "Screens".
6
+ export default [
7
+ http.get(`*${AUTH_PREFIX}/get-session`, () =>
8
+ HttpResponse.json({ session, user }),
9
+ ),
10
+ ];
package/src/serve.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type ExtraControls, FIXTURE_PREFIX } from "@slotform/screens/serve";
2
+ import { AUTH_PREFIX } from "./types.ts";
3
+ import { isSafeCallbackURL } from "./worker/callback-url.ts";
4
+
5
+ // The served app's `/fixture/link`: docs/architecture/plugins/auth.md, "Screens".
6
+ export default async function link(
7
+ request: Request,
8
+ context: Parameters<ExtraControls>[1],
9
+ ): Promise<Response | undefined> {
10
+ const url = new URL(request.url);
11
+ if (url.pathname !== `${FIXTURE_PREFIX}/link`) return undefined;
12
+ // `ExtraControls` types `env` as `unknown`: the served worker's bindings.
13
+ const vars = context.env as Record<string, unknown>;
14
+ const email = vars.SLOTFORM_SERVE_EMAIL;
15
+ const code = vars.SLOTFORM_SERVE_CODE;
16
+ if (typeof email !== "string" || typeof code !== "string")
17
+ return new Response("fixture link: the app has no fixture member", {
18
+ status: 404,
19
+ });
20
+ const post = (path: string, body: unknown) =>
21
+ context.app(
22
+ new Request(`${url.origin}${AUTH_PREFIX}${path}`, {
23
+ method: "POST",
24
+ headers: { "content-type": "application/json", origin: url.origin },
25
+ body: JSON.stringify(body),
26
+ }),
27
+ );
28
+ const sent = await post("/email-otp/send-verification-otp", {
29
+ email,
30
+ type: "sign-in",
31
+ });
32
+ if (!sent.ok)
33
+ return new Response(`fixture link: the code was refused: ${sent.status}`, {
34
+ status: 502,
35
+ });
36
+ const signed = await post("/sign-in/email-otp", { email, otp: code });
37
+ if (!signed.ok)
38
+ return new Response(`fixture link: sign-in was refused: ${signed.status}`, {
39
+ status: 502,
40
+ });
41
+ const to = url.searchParams.get("to") ?? "/";
42
+ const headers = new Headers({
43
+ // A path on the app only, as a sign-in link's redirect is held to.
44
+ location: isSafeCallbackURL(to, []) ? to : "/",
45
+ });
46
+ for (const cookie of signed.headers.getSetCookie())
47
+ headers.append("set-cookie", cookie);
48
+ return new Response(null, { status: 302, headers });
49
+ }
package/src/types.ts ADDED
@@ -0,0 +1,313 @@
1
+ import { z } from "zod";
2
+
3
+ // The path better-auth mounts under inside the worker. Shared so the runtime
4
+ // and the codegen contribution to `api.slots.routePrefixes` can never drift.
5
+ export const AUTH_PREFIX = "/api/auth";
6
+
7
+ // Discovery prefixes of the authorization server and the protected resource: docs/architecture/plugins/auth.md, "MCP OAuth".
8
+ export const OAUTH_DISCOVERY_PREFIXES = [
9
+ "/.well-known/oauth-authorization-server",
10
+ "/.well-known/oauth-protected-resource",
11
+ ] as const;
12
+
13
+ // The header Cloudflare sets to the client's address. It is unspoofable behind
14
+ // the edge, which `X-Forwarded-For` is not.
15
+ export const CLIENT_IP_HEADER = "cf-connecting-ip";
16
+
17
+ interface RateLimiterConfig {
18
+ binding: string;
19
+ limit: number;
20
+ period: number;
21
+ }
22
+
23
+ // Limiter defaults and the 10 or 60 s period: docs/architecture/plugins/auth.md, "Rate limiting".
24
+ // The agent limiter is one bucket per grant, bound only while `mcp` is on.
25
+ const RATE_LIMITER_DEFAULTS: Record<
26
+ "ip" | "email" | "agent",
27
+ RateLimiterConfig
28
+ > = {
29
+ ip: { binding: "RATE_LIMITER_IP", limit: 100, period: 60 },
30
+ email: { binding: "RATE_LIMITER_EMAIL", limit: 3, period: 60 },
31
+ agent: { binding: "RATE_LIMITER_AGENT", limit: 120, period: 60 },
32
+ };
33
+
34
+ function rateLimiterSchema(defaults: RateLimiterConfig) {
35
+ return z
36
+ .object({
37
+ binding: z.string().default(defaults.binding),
38
+ limit: z
39
+ .number()
40
+ .positive({
41
+ error: "auth: rateLimiter.limit must be a positive number",
42
+ })
43
+ .default(defaults.limit),
44
+ period: z
45
+ .number()
46
+ .positive({
47
+ error: "auth: rateLimiter.period must be a positive number",
48
+ })
49
+ .default(defaults.period),
50
+ })
51
+ .default(defaults);
52
+ }
53
+
54
+ const organizationObjectSchema = z.object({
55
+ ac: z.unknown().optional(),
56
+ roles: z.record(z.string(), z.unknown()).optional(),
57
+ });
58
+
59
+ const socialProviderConfigSchema = z.object({
60
+ clientIdVar: z.string().optional(),
61
+ clientSecretVar: z.string().optional(),
62
+ });
63
+
64
+ const appleProviderConfigSchema = socialProviderConfigSchema.extend({
65
+ // Native (Expo) Apple Sign-In issues the ID token to the app bundle id;
66
+ // Better Auth needs it to validate native tokens. Optional — the
67
+ // browser-redirect OAuth flow doesn't require it.
68
+ appBundleIdentifier: z.string().optional(),
69
+ });
70
+
71
+ const passkeyObjectSchema = z.object({
72
+ // The WebAuthn relying-party id: the domain credentials are bound to.
73
+ // Defaults to `app.domain`, a registrable suffix of every derived origin.
74
+ rpID: z.string().optional(),
75
+ // The name the authenticator shows the user. Defaults to `app.name`.
76
+ rpName: z.string().optional(),
77
+ // Origins a ceremony may come from. Defaults to the worker's resolved
78
+ // production CORS list.
79
+ origin: z.union([z.string(), z.array(z.string())]).optional(),
80
+ // Passed through to the registration options; better-auth's defaults are
81
+ // `residentKey: "preferred"` and `userVerification: "preferred"`.
82
+ authenticatorSelection: z
83
+ .object({
84
+ authenticatorAttachment: z
85
+ .enum(["platform", "cross-platform"])
86
+ .optional(),
87
+ requireResidentKey: z.boolean().optional(),
88
+ residentKey: z.enum(["discouraged", "preferred", "required"]).optional(),
89
+ userVerification: z
90
+ .enum(["discouraged", "preferred", "required"])
91
+ .optional(),
92
+ })
93
+ .optional(),
94
+ });
95
+
96
+ export const authOptionsSchema = z
97
+ .object({
98
+ cookies: z
99
+ .object({
100
+ prefix: z.string().optional(),
101
+ domain: z.string().optional(),
102
+ })
103
+ .optional(),
104
+ session: z
105
+ .object({
106
+ expiresIn: z
107
+ .number()
108
+ .positive({
109
+ error: "auth: session.expiresIn must be a positive number",
110
+ })
111
+ .optional(),
112
+ updateAge: z.number().optional(),
113
+ // How recently the session must have been created for better-auth to
114
+ // treat it as fresh; account deletion without email confirmation needs
115
+ // a fresh session. 0 disables the check entirely, so any stolen
116
+ // session cookie of any age can delete the account. Passwordless
117
+ // consumers should implement the `sendDeleteVerification` callback
118
+ // (email confirmation, no freshness requirement) instead of 0.
119
+ freshAge: z
120
+ .number()
121
+ .nonnegative({
122
+ error: "auth: session.freshAge must be zero or a positive number",
123
+ })
124
+ .optional(),
125
+ })
126
+ .optional(),
127
+ user: z
128
+ .object({
129
+ // Account deletion (App Store 5.1.1(v) requires it for a native app).
130
+ // Off unless asked for: the endpoint destroys rows. The consumer's
131
+ // `beforeDelete` callback vetoes or cleans up. With the
132
+ // `sendDeleteVerification` callback implemented, deletion goes
133
+ // through an emailed confirmation link; without it, a session older
134
+ // than `session.freshAge` is refused.
135
+ deleteUser: z.boolean().optional(),
136
+ })
137
+ .optional(),
138
+ organization: z.union([z.boolean(), organizationObjectSchema]).optional(),
139
+ // Email one-time-password sign-in. On by default; OAuth-only consumers set
140
+ // `false` to drop the email-OTP plugin and its required callback file.
141
+ emailOtp: z.boolean().default(true),
142
+ // Magic-link sign-in. Off by default; on, the consumer's `sendMagicLink`
143
+ // callback is required. The token lives 5 minutes, is stored hashed and
144
+ // is spent on its first verification; an unknown address signs up.
145
+ magicLink: z.boolean().default(false),
146
+ // OAuth social providers. `true` enables a provider with conventional env
147
+ // var names (e.g. GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET); an object
148
+ // overrides the var names. The runtime reads credentials from env at request
149
+ // time — only the var names are baked into the generated worker.
150
+ socialProviders: z
151
+ .object({
152
+ google: z.union([z.boolean(), socialProviderConfigSchema]).optional(),
153
+ apple: z.union([z.boolean(), appleProviderConfigSchema]).optional(),
154
+ })
155
+ .optional(),
156
+ // Native (Expo) consumer flag: docs/architecture/plugins/auth.md, "Native client".
157
+ expo: z
158
+ .union([z.boolean(), z.object({ scheme: z.string().min(1) })])
159
+ .optional(),
160
+ // Passkey (WebAuthn) sign-in through `@better-auth/passkey`. Off by
161
+ // default; `{}` enables it with every field derived. The consumer migrates
162
+ // the `passkey` table by re-exporting `@slotform/auth/schema/passkey`.
163
+ passkey: z.union([z.literal(false), passkeyObjectSchema]).default(false),
164
+ // An OAuth authorization server for MCP clients (`@better-auth/mcp`): an
165
+ // agent connects by signing in, never by a pasted secret. Needs
166
+ // `organization`; the consumer migrates the OAuth and JWT tables by
167
+ // re-exporting `@slotform/auth/schema/oauth`.
168
+ mcp: z.boolean().default(false),
169
+ // Device credentials: long-lived, named, revocable bearer keys a signed-in
170
+ // member makes for a machine that has no browser (an agent daemon, a sync
171
+ // client). A key acts as its member on the API, `/ws` and the server's
172
+ // own routes. The consumer migrates the `apikey` table by re-exporting
173
+ // `@slotform/auth/schema/devices`.
174
+ devices: z.boolean().default(false),
175
+ // Who may create an account, on every way in (code, link, OAuth). `open`:
176
+ // anyone. `invite`: only an address holding a pending organization
177
+ // invitation. `first`: the first account, then as `invite`: a single-owner
178
+ // app. Both closed modes need `organization`: the invitations are its.
179
+ signUp: z.enum(["open", "invite", "first"]).default("open"),
180
+ secretVar: z.string().default("AUTH_SECRET"),
181
+ appUrlVar: z.string().default("APP_URL"),
182
+ rateLimiter: z
183
+ .object({
184
+ ip: rateLimiterSchema(RATE_LIMITER_DEFAULTS.ip),
185
+ email: rateLimiterSchema(RATE_LIMITER_DEFAULTS.email),
186
+ agent: rateLimiterSchema(RATE_LIMITER_DEFAULTS.agent),
187
+ })
188
+ .default(RATE_LIMITER_DEFAULTS),
189
+ })
190
+ .refine((options) => options.signUp === "open" || options.organization, {
191
+ error:
192
+ 'auth: `signUp: "invite"` and `"first"` need `organization`: the invitations are its.',
193
+ path: ["signUp"],
194
+ })
195
+ .refine((options) => !options.mcp || options.organization, {
196
+ error:
197
+ "auth: `mcp` needs `organization`: an agent's grant is to one organization.",
198
+ path: ["mcp"],
199
+ });
200
+
201
+ // Input type: user-supplied options (defaults remain optional at input).
202
+ export type AuthOptions = z.input<typeof authOptionsSchema>;
203
+
204
+ // Post-validation view: every schema default is materialised.
205
+ export type ResolvedAuthOptions = z.output<typeof authOptionsSchema>;
206
+
207
+ export type SocialProviderName = "google" | "apple";
208
+
209
+ export interface ResolvedSocialProvider {
210
+ clientIdVar: string;
211
+ clientSecretVar: string;
212
+ appBundleIdentifier?: string;
213
+ }
214
+
215
+ const CONVENTIONAL_PROVIDER_VARS: Record<
216
+ SocialProviderName,
217
+ { clientIdVar: string; clientSecretVar: string }
218
+ > = {
219
+ google: {
220
+ clientIdVar: "GOOGLE_CLIENT_ID",
221
+ clientSecretVar: "GOOGLE_CLIENT_SECRET",
222
+ },
223
+ apple: {
224
+ clientIdVar: "APPLE_CLIENT_ID",
225
+ clientSecretVar: "APPLE_CLIENT_SECRET",
226
+ },
227
+ };
228
+
229
+ // Superset of both provider config shapes — Google never sets
230
+ // `appBundleIdentifier`, so accepting it as optional lets a single typed helper
231
+ // handle both without a cast.
232
+ type ProviderConfigOverrides = {
233
+ clientIdVar?: string;
234
+ clientSecretVar?: string;
235
+ appBundleIdentifier?: string;
236
+ };
237
+
238
+ function resolveProvider(
239
+ cfg: boolean | ProviderConfigOverrides | undefined,
240
+ conventional: { clientIdVar: string; clientSecretVar: string },
241
+ ): ResolvedSocialProvider | undefined {
242
+ if (!cfg) return undefined;
243
+ const overrides = cfg === true ? undefined : cfg;
244
+ const resolved: ResolvedSocialProvider = {
245
+ clientIdVar: overrides?.clientIdVar ?? conventional.clientIdVar,
246
+ clientSecretVar: overrides?.clientSecretVar ?? conventional.clientSecretVar,
247
+ };
248
+ if (overrides?.appBundleIdentifier) {
249
+ resolved.appBundleIdentifier = overrides.appBundleIdentifier;
250
+ }
251
+ return resolved;
252
+ }
253
+
254
+ // Normalize `socialProviders` into env-var references: docs/architecture/plugins/auth.md, "Social providers".
255
+ export function resolveSocialProviders(
256
+ input: ResolvedAuthOptions["socialProviders"],
257
+ ): Partial<Record<SocialProviderName, ResolvedSocialProvider>> {
258
+ const out: Partial<Record<SocialProviderName, ResolvedSocialProvider>> = {};
259
+ if (!input) return out;
260
+ const google = resolveProvider(
261
+ input.google,
262
+ CONVENTIONAL_PROVIDER_VARS.google,
263
+ );
264
+ if (google) out.google = google;
265
+ const apple = resolveProvider(input.apple, CONVENTIONAL_PROVIDER_VARS.apple);
266
+ if (apple) out.apple = apple;
267
+ return out;
268
+ }
269
+
270
+ // better-auth's own `user` row as the deletion hook receives it. Mirrors
271
+ // `BaseUser` (@better-auth/core's `userSchema`).
272
+ export interface AuthUser {
273
+ id: string;
274
+ email: string;
275
+ emailVerified: boolean;
276
+ name: string;
277
+ image?: string | null;
278
+ createdAt: Date;
279
+ updatedAt: Date;
280
+ }
281
+
282
+ // Why better-auth asks for an OTP. Only "sign-in" reaches a consumer that
283
+ // runs email-OTP alone, but the override sees all four.
284
+ export type OtpType =
285
+ | "sign-in"
286
+ | "email-verification"
287
+ | "forget-password"
288
+ | "change-email";
289
+
290
+ // The callback file's payload shapes: docs/architecture/plugins/auth.md, "Callbacks".
291
+ export interface AuthCallbackPayloads<TEnv = unknown> {
292
+ sendOTP: { email: string; code: string; type: OtpType; env: TEnv };
293
+ // `url` is the link to send; `token` is the plain token it carries.
294
+ sendMagicLink: { email: string; url: string; token: string; env: TEnv };
295
+ // `invitationId` is what the accept link carries: the invitee signs in and
296
+ // accepts the invitation by id.
297
+ sendInvitation: {
298
+ invitationId: string;
299
+ email: string;
300
+ role: string;
301
+ organization: { id: string; name: string; slug: string };
302
+ inviter: { id: string; name: string; email: string };
303
+ env: TEnv;
304
+ };
305
+ beforeDelete: { user: AuthUser; request?: Request; env: TEnv };
306
+ sendDeleteVerification: {
307
+ user: AuthUser;
308
+ url: string;
309
+ token: string;
310
+ env: TEnv;
311
+ };
312
+ generateOTP: { email: string; type: OtpType; env: TEnv };
313
+ }