@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,174 @@
1
+ // Record-scoped authorization and the statement compile: a typed wrapper over CASL's `MongoAbility`.
2
+ // Access control: docs/architecture/plugins/auth.md, "Access control".
3
+ import type {
4
+ AnyMongoAbility,
5
+ ForcedSubject,
6
+ MongoAbility,
7
+ MongoQuery,
8
+ RawRuleOf,
9
+ } from "@casl/ability";
10
+ import {
11
+ AbilityBuilder,
12
+ subject as caslSubject,
13
+ createMongoAbility,
14
+ } from "@casl/ability";
15
+ import { type PackRule, packRules, unpackRules } from "@casl/ability/extra";
16
+ import { ORPCError } from "@orpc/server";
17
+
18
+ // ---------- Subject vocabulary ----------
19
+
20
+ // Instance-checked subjects declare the row fields their conditions may
21
+ // read (e.g. `{ Expense: { paidById: string } }`). An abstract (string-only)
22
+ // subject maps to `never` — the bottom type is assignable to any field
23
+ // record, so `never` satisfies this constraint while making conditions on
24
+ // that subject impossible to type (see `ConditionsTail` below).
25
+ type AbilitySubjects = Record<string, Record<string, unknown>>;
26
+
27
+ // The subject union CASL's ability actually checks against: an abstract
28
+ // subject stays a bare string; an instance subject is either the bare
29
+ // string (unconditional grants, e.g. `can("read", "Report")`) or a row
30
+ // tagged via `subject(name, row)` (see `ForcedSubject`).
31
+ type SubjectUnion<Subjects extends AbilitySubjects> = {
32
+ [K in keyof Subjects & string]: [Subjects[K]] extends [never]
33
+ ? K
34
+ : K | (Subjects[K] & ForcedSubject<K>);
35
+ }[keyof Subjects & string];
36
+
37
+ type AbilityFor<
38
+ Subjects extends AbilitySubjects,
39
+ Actions extends string = string,
40
+ > = MongoAbility<[Actions, SubjectUnion<Subjects>]>;
41
+
42
+ // Optional 3rd argument to `can`/`cannot`: a `MongoQuery` over the subject's
43
+ // declared fields for an instance subject, or an empty tuple (no argument
44
+ // accepted) for an abstract one — passing conditions there is a type error.
45
+ type ConditionsTail<Fields> = [Fields] extends [never]
46
+ ? []
47
+ : [conditions?: MongoQuery<Fields>];
48
+
49
+ type CanFn<Subjects extends AbilitySubjects, Actions extends string> = <
50
+ K extends keyof Subjects & string,
51
+ >(
52
+ action: Actions,
53
+ subjectType: K,
54
+ ...conditions: ConditionsTail<Subjects[K]>
55
+ ) => void;
56
+
57
+ // ---------- defineAbility ----------
58
+
59
+ export function defineAbility<
60
+ Subjects extends AbilitySubjects,
61
+ Actions extends string = string,
62
+ >(): {
63
+ can: CanFn<Subjects, Actions>;
64
+ cannot: CanFn<Subjects, Actions>;
65
+ build: () => AbilityFor<Subjects, Actions>;
66
+ } {
67
+ const builder = new AbilityBuilder<AbilityFor<Subjects, Actions>>(
68
+ createMongoAbility,
69
+ );
70
+ return {
71
+ // The builder's real `can`/`cannot` already do the right thing at
72
+ // runtime (push `{ action, subject, conditions }`); only the static
73
+ // type narrows here, to the simpler action+subject+conditions shape
74
+ // this module commits to (no per-field rules).
75
+ can: builder.can as unknown as CanFn<Subjects, Actions>,
76
+ cannot: builder.cannot as unknown as CanFn<Subjects, Actions>,
77
+ build: () => builder.build(),
78
+ };
79
+ }
80
+
81
+ export function subject<
82
+ Fields extends Record<string, unknown>,
83
+ TSubjectType extends string,
84
+ >(
85
+ subjectType: TSubjectType,
86
+ row: Fields,
87
+ ): Fields & ForcedSubject<TSubjectType> {
88
+ return caslSubject(subjectType, row);
89
+ }
90
+
91
+ // ---------- assertCan ----------
92
+
93
+ // `opts.cloak` is for a consumer's own procedures, which `guide/abilities.md`
94
+ // documents; the framework passes no option.
95
+ export function assertCan<TAbility extends AnyMongoAbility>(
96
+ ability: TAbility,
97
+ action: Parameters<TAbility["can"]>[0],
98
+ subjectArg: Parameters<TAbility["can"]>[1],
99
+ opts?: { cloak?: boolean; message?: string },
100
+ ): void {
101
+ if (ability.can(action, subjectArg)) return;
102
+ // `message` is the denial copy the client renders, so a consumer whose UI
103
+ // is not in English can pass its own. Cloaked denials ignore it: their
104
+ // whole point is to be indistinguishable from a missing record.
105
+ if (opts?.cloak) {
106
+ throw new ORPCError("NOT_FOUND");
107
+ }
108
+ throw new ORPCError("FORBIDDEN", {
109
+ message: opts?.message ?? "Insufficient permissions",
110
+ });
111
+ }
112
+
113
+ // ---------- pack / unpack ----------
114
+
115
+ // Wire format of packed rules: docs/architecture/plugins/auth.md, "Ability wire format".
116
+ export type PackedRules<TAbility extends AnyMongoAbility = AnyMongoAbility> =
117
+ PackRule<TAbility["rules"][number]>[];
118
+
119
+ type PackedConditions = Record<string, unknown> | 0 | undefined;
120
+
121
+ // Packed rules written out for any subject: docs/architecture/plugins/auth.md, "Ability wire format".
122
+ type PackedRule =
123
+ | [string, string]
124
+ | [string, string, PackedConditions]
125
+ | [string, string, PackedConditions, 1]
126
+ | [string, string, PackedConditions, 1 | 0, string]
127
+ | [string, string, PackedConditions, 1 | 0, string | 0, string];
128
+
129
+ export type PackedRuleSet = PackedRule[];
130
+
131
+ export function packAbility<TAbility extends AnyMongoAbility>(
132
+ ability: TAbility,
133
+ ): PackedRules<TAbility> {
134
+ return packRules(ability.rules) as PackedRules<TAbility>;
135
+ }
136
+
137
+ export function unpackAbility<TAbility extends AnyMongoAbility>(
138
+ packed: PackedRules<TAbility>,
139
+ ): TAbility {
140
+ // `TAbility["rules"][number]` and `RawRuleOf<TAbility>` are the same type
141
+ // once TAbility resolves, but tsc can't reduce the indexed access while
142
+ // the generic is open; one cast bridges it.
143
+ return createMongoAbility<TAbility>(
144
+ unpackRules(packed) as RawRuleOf<TAbility>[],
145
+ );
146
+ }
147
+
148
+ // ---------- compileStatements ----------
149
+
150
+ // Statements compile one way into CASL rules: docs/architecture/plugins/auth.md, "Access control".
151
+ const FORBIDDEN_ACTION = "manage";
152
+ const FORBIDDEN_SUBJECT = "all";
153
+
154
+ export function compileStatements(
155
+ grants: Record<string, readonly string[]>,
156
+ ): { action: string; subject: string }[] {
157
+ const rules: { action: string; subject: string }[] = [];
158
+ for (const [resource, actions] of Object.entries(grants)) {
159
+ if (resource === FORBIDDEN_SUBJECT) {
160
+ throw new Error(
161
+ `compileStatements: resource "${FORBIDDEN_SUBJECT}" is a CASL wildcard subject (matches every subject), but better-auth statements treat it as a literal resource name. Compiling it would over-grant client-side — use a specific resource name instead.`,
162
+ );
163
+ }
164
+ for (const action of actions) {
165
+ if (action === FORBIDDEN_ACTION) {
166
+ throw new Error(
167
+ `compileStatements: action "${FORBIDDEN_ACTION}" is a CASL wildcard action (matches every action), but better-auth statements treat it as a literal action name. Compiling it would over-grant client-side — use a specific action name instead.`,
168
+ );
169
+ }
170
+ rules.push({ action, subject: resource });
171
+ }
172
+ }
173
+ return rules;
174
+ }
package/src/access.ts ADDED
@@ -0,0 +1,45 @@
1
+ export interface Role {
2
+ [resource: string]: readonly string[];
3
+ }
4
+
5
+ export function createAccessControl<
6
+ T extends Record<string, readonly string[]>,
7
+ >(statements: T) {
8
+ return {
9
+ statements,
10
+ newRole(
11
+ permissions: {
12
+ [K in keyof T]?: readonly T[K][number][];
13
+ },
14
+ ): Role {
15
+ // Each key holds a list of action names, which `Role` spells as `readonly string[]`.
16
+ return permissions as Role;
17
+ },
18
+ };
19
+ }
20
+
21
+ // Default organization statements: docs/architecture/slot-catalog.md, "`api.slots.*` (the `api` plugin)".
22
+ export const defaultOrgStatements = {
23
+ organization: ["update", "delete"],
24
+ member: ["create", "update", "delete"],
25
+ invitation: ["create", "cancel"],
26
+ team: ["create", "update", "delete"],
27
+ } as const;
28
+
29
+ const orgAc = createAccessControl(defaultOrgStatements);
30
+
31
+ export const defaultOrgRoles = {
32
+ owner: orgAc.newRole(defaultOrgStatements),
33
+ admin: orgAc.newRole({
34
+ organization: ["update"],
35
+ member: ["create", "update", "delete"],
36
+ invitation: ["create", "cancel"],
37
+ team: ["create", "update", "delete"],
38
+ }),
39
+ member: orgAc.newRole({
40
+ organization: [],
41
+ member: [],
42
+ invitation: [],
43
+ team: [],
44
+ }),
45
+ } as const;
@@ -0,0 +1,45 @@
1
+ // Deploy check over the scaffold's TODO markers: docs/architecture/plugins/auth.md, "Callbacks".
2
+
3
+ export const CALLBACK_MARKERS = {
4
+ sendOTP: "// TODO: send OTP email",
5
+ sendInvitation: "// TODO: send invitation email linking to your accept page",
6
+ sendMagicLink: "// TODO: send the magic link email",
7
+ } as const;
8
+
9
+ type StubbedCallback = keyof typeof CALLBACK_MARKERS;
10
+
11
+ // The callbacks the options make required, in the order a consumer meets them.
12
+ export function requiredCallbacks(options: {
13
+ emailOtp?: boolean;
14
+ magicLink?: boolean;
15
+ organization?: unknown;
16
+ }): StubbedCallback[] {
17
+ return [
18
+ ...(options.emailOtp === false ? [] : (["sendOTP"] as const)),
19
+ ...(options.magicLink ? (["sendMagicLink"] as const) : []),
20
+ ...(options.organization ? (["sendInvitation"] as const) : []),
21
+ ];
22
+ }
23
+
24
+ export function pendingCallbacks(
25
+ source: string,
26
+ required: readonly StubbedCallback[],
27
+ ): StubbedCallback[] {
28
+ return required.filter((name) => source.includes(CALLBACK_MARKERS[name]));
29
+ }
30
+
31
+ export function stubbedCallbacksMessage(
32
+ path: string,
33
+ pending: readonly StubbedCallback[],
34
+ ): string {
35
+ const names = pending.map((name) => `\`${name}\``).join(", ");
36
+ const markers = pending
37
+ .map((name) => `"${CALLBACK_MARKERS[name]}"`)
38
+ .join(", ");
39
+ return (
40
+ `auth: \`${path}\` still holds the scaffolded stub for ${names} ` +
41
+ `(the ${markers} marker). Implement ${pending.length > 1 ? "them" : "it"} ` +
42
+ "to send the email, then delete the marker: the stub sends nothing and " +
43
+ "throws outside dev, so no sign-in would complete."
44
+ );
45
+ }
package/src/client.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { oauthProviderClient } from "@better-auth/oauth-provider/client";
2
+ import { passkeyClient } from "@better-auth/passkey/client";
3
+ import {
4
+ emailOTPClient,
5
+ magicLinkClient,
6
+ organizationClient,
7
+ } from "better-auth/client/plugins";
8
+ import {
9
+ type AccessControl,
10
+ createAccessControl,
11
+ type Role,
12
+ role,
13
+ } from "better-auth/plugins/access";
14
+ import {
15
+ createAuthClient as createBetterAuthClient,
16
+ type ReactAuthClient,
17
+ } from "better-auth/react";
18
+
19
+ // Organization access control as codegen bakes it: docs/architecture/plugins/auth.md, "Access control".
20
+ export interface OrganizationAccess {
21
+ statements?: Record<string, readonly string[]>;
22
+ roles?: Record<string, Record<string, readonly string[]>>;
23
+ }
24
+
25
+ // The web client: docs/architecture/plugins/auth.md, "Web client".
26
+ export interface AuthClientOptions {
27
+ // Origin of the worker's `/api/auth`. Omitted, the client calls `/api/auth`
28
+ // on the page's own origin.
29
+ baseURL?: string;
30
+ // `auth({ passkey })`: adds the passkey sign-in and management methods.
31
+ passkey?: boolean;
32
+ // `auth({ emailOtp })`, on by default on both sides.
33
+ emailOtp?: boolean;
34
+ // `auth({ magicLink })`, off by default on both sides.
35
+ magicLink?: boolean;
36
+ // `auth({ organization })`: adds the organization, member and invitation
37
+ // methods. With the consumer's access control, its roles are the roles
38
+ // the methods take (`inviteMember({ role })`); `true` keeps better-auth's
39
+ // default owner, admin and member, as the worker does.
40
+ organization?: boolean | OrganizationAccess;
41
+ // `auth({ mcp: true })`: adds the OAuth provider's methods, which resume
42
+ // an authorization after sign-in, after the organization choice, and at
43
+ // consent (`oauth2.continue`, `oauth2.consent`, `oauth2.publicClient`),
44
+ // and attach the authorization's signed query to every request the login
45
+ // page makes.
46
+ mcp?: boolean;
47
+ }
48
+
49
+ // better-auth's client options for the access control, typed by it: the
50
+ // role names are the keys of `roles`.
51
+ type OrganizationClientAccess<A extends OrganizationAccess> = {
52
+ ac: A["statements"] extends Record<string, readonly string[]>
53
+ ? AccessControl<A["statements"]>
54
+ : undefined;
55
+ roles: A["roles"] extends Record<string, unknown>
56
+ ? { [K in keyof A["roles"]]: Role }
57
+ : undefined;
58
+ };
59
+
60
+ type ClientPlugins<O extends AuthClientOptions> = [
61
+ ...(O["passkey"] extends true ? [ReturnType<typeof passkeyClient>] : []),
62
+ ...(O["emailOtp"] extends false ? [] : [ReturnType<typeof emailOTPClient>]),
63
+ ...(O["magicLink"] extends true ? [ReturnType<typeof magicLinkClient>] : []),
64
+ // Instantiated with the options it is called with: the bare `ReturnType`
65
+ // takes the options constraint, whose conditionals erase every
66
+ // organization method from the client type.
67
+ ...(O["organization"] extends true
68
+ ? [ReturnType<typeof organizationClient<Record<never, never>>>]
69
+ : O["organization"] extends infer A extends OrganizationAccess
70
+ ? [ReturnType<typeof organizationClient<OrganizationClientAccess<A>>>]
71
+ : []),
72
+ ...(O["mcp"] extends true ? [ReturnType<typeof oauthProviderClient>] : []),
73
+ ];
74
+
75
+ // Named, not inferred: the inferred type reaches better-auth's own zod copy,
76
+ // which declaration emit cannot name from this package.
77
+ type BetterAuthClient<O extends AuthClientOptions> = ReactAuthClient<{
78
+ baseURL: string | undefined;
79
+ plugins: ClientPlugins<O>;
80
+ }>;
81
+
82
+ // The client checks a role's permissions through `.authorize()`, which the
83
+ // baked records do not carry.
84
+ function organizationPlugin(access: true | OrganizationAccess) {
85
+ if (access === true) return organizationClient();
86
+ return organizationClient({
87
+ ...(access.statements
88
+ ? { ac: createAccessControl(access.statements) }
89
+ : {}),
90
+ ...(access.roles
91
+ ? {
92
+ roles: Object.fromEntries(
93
+ Object.entries(access.roles).map(([name, grants]) => [
94
+ name,
95
+ role(grants),
96
+ ]),
97
+ ),
98
+ }
99
+ : {}),
100
+ });
101
+ }
102
+
103
+ export function createAuthClient<const O extends AuthClientOptions>(
104
+ options: O,
105
+ ): BetterAuthClient<O> {
106
+ // The array's element types are the union of every plugin; `ClientPlugins<O>`
107
+ // keeps only those `O` switched on.
108
+ const plugins = [
109
+ ...(options.passkey ? [passkeyClient()] : []),
110
+ ...(options.emailOtp === false ? [] : [emailOTPClient()]),
111
+ ...(options.magicLink ? [magicLinkClient()] : []),
112
+ ...(options.organization ? [organizationPlugin(options.organization)] : []),
113
+ ...(options.mcp ? [oauthProviderClient()] : []),
114
+ ] as ClientPlugins<O>;
115
+ return createBetterAuthClient({ baseURL: options.baseURL, plugins });
116
+ }
117
+
118
+ export type AuthClient<O extends AuthClientOptions = AuthClientOptions> =
119
+ ReturnType<typeof createAuthClient<O>>;
package/src/expo.tsx ADDED
@@ -0,0 +1,275 @@
1
+ import { expoClient } from "@better-auth/expo/client";
2
+ import { emailOTPClient } from "better-auth/client/plugins";
3
+ import { createAuthClient as createBetterAuthClient } from "better-auth/react";
4
+ import { createContext, type ReactNode, useContext } from "react";
5
+
6
+ // Secure-storage shape derived from `expoClient`'s option: docs/architecture/plugins/auth.md, "Native client".
7
+ type ExpoClientStorage = NonNullable<
8
+ Parameters<typeof expoClient>[0]
9
+ >["storage"];
10
+
11
+ export interface AuthClientConfig {
12
+ // Base URL of the Better Auth worker (e.g. https://api.example.com). A function
13
+ // is read whenever the client is used, so an app whose server is chosen while it
14
+ // runs changes the address with no restart: the client built for the old address
15
+ // (and its session) is dropped and the next call builds one for the new. Sign the
16
+ // viewer out of the old server first.
17
+ baseURL: string | (() => string);
18
+ // Deep-link scheme for the OAuth redirect back into the app. Matches the
19
+ // Expo app `scheme` (and the `expo` plugin's `scheme` option).
20
+ scheme: string;
21
+ // Secure key-value store tokens persist in: docs/architecture/plugins/auth.md, "Native client".
22
+ storage: ExpoClientStorage;
23
+ // Prefix for stored keys. Defaults to the scheme.
24
+ storagePrefix?: string;
25
+ // Prefix of the session cookies the worker sets: docs/architecture/plugins/auth.md, "Cookie prefix".
26
+ cookiePrefix?: string;
27
+ }
28
+
29
+ function build(config: AuthClientConfig, baseURL: string) {
30
+ return createBetterAuthClient({
31
+ baseURL,
32
+ plugins: [
33
+ expoClient({
34
+ scheme: config.scheme,
35
+ storagePrefix: config.storagePrefix ?? config.scheme,
36
+ storage: config.storage,
37
+ cookiePrefix: config.cookiePrefix,
38
+ }),
39
+ // Passwordless email sign-in alongside the social providers. The server
40
+ // enables it via `emailOtp` (on by default); screens drive it through the
41
+ // `sendEmailOtp` / `signInWithEmailOtp` helpers below.
42
+ emailOTPClient(),
43
+ ],
44
+ });
45
+ }
46
+
47
+ export type AuthClient = ReturnType<typeof build>;
48
+
49
+ export function createAuthClient(config: AuthClientConfig): AuthClient {
50
+ const { baseURL } = config;
51
+ if (typeof baseURL === "string") return build(config, baseURL);
52
+ // Better Auth fixes the address when it builds a client, so the client the
53
+ // caller holds is a stand-in for the one built for the address now: a property
54
+ // read asks for the address and, when it moved, builds the client again.
55
+ let at: string | undefined;
56
+ let current: AuthClient | undefined;
57
+ const now = (): AuthClient => {
58
+ const url = baseURL();
59
+ if (current === undefined || url !== at) {
60
+ at = url;
61
+ current = build(config, url);
62
+ }
63
+ return current;
64
+ };
65
+ return new Proxy({} as AuthClient, {
66
+ get: (_, key) => Reflect.get(now(), key),
67
+ has: (_, key) => Reflect.has(now(), key),
68
+ });
69
+ }
70
+
71
+ const AuthClientContext = createContext<AuthClient | null>(null);
72
+
73
+ export interface AuthProviderProps {
74
+ client: AuthClient;
75
+ children: ReactNode;
76
+ }
77
+
78
+ // Auth client provider: docs/architecture/plugins/auth.md, "Native client".
79
+ export function AuthProvider(props: AuthProviderProps) {
80
+ return (
81
+ <AuthClientContext.Provider value={props.client}>
82
+ {props.children}
83
+ </AuthClientContext.Provider>
84
+ );
85
+ }
86
+
87
+ export function useAuthClient(): AuthClient {
88
+ const client = useContext(AuthClientContext);
89
+ if (!client) {
90
+ throw new Error("useAuthClient must be used within <AuthProvider>.");
91
+ }
92
+ return client;
93
+ }
94
+
95
+ export interface SocialSignInOptions {
96
+ // In-app path to land on once the OAuth redirect completes.
97
+ callbackURL?: string;
98
+ }
99
+
100
+ // An OAuth-only native consumer signs in through Apple and Google; these wrap `signIn.social` so screens don't repeat the
101
+ // provider string. The server decides which providers are actually configured.
102
+ export function signInWithApple(
103
+ client: AuthClient,
104
+ options?: SocialSignInOptions,
105
+ ) {
106
+ return client.signIn.social({
107
+ provider: "apple",
108
+ callbackURL: options?.callbackURL,
109
+ });
110
+ }
111
+
112
+ export function signInWithGoogle(
113
+ client: AuthClient,
114
+ options?: SocialSignInOptions,
115
+ ) {
116
+ return client.signIn.social({
117
+ provider: "google",
118
+ callbackURL: options?.callbackURL,
119
+ });
120
+ }
121
+
122
+ // ── Native ID-token sign-in ─────────────────────────────────────────
123
+ //
124
+ // Native ID-token helpers: docs/architecture/plugins/auth.md, "Native client".
125
+
126
+ interface GoogleSigninModule {
127
+ GoogleSignin: {
128
+ configure(config: {
129
+ webClientId: string;
130
+ iosClientId?: string;
131
+ scopes?: string[];
132
+ offlineAccess?: boolean;
133
+ }): void;
134
+ hasPlayServices(options: {
135
+ showPlayServicesUpdateDialog: boolean;
136
+ }): Promise<boolean>;
137
+ signIn(): Promise<unknown>;
138
+ };
139
+ isSuccessResponse(
140
+ response: unknown,
141
+ ): response is { data: { idToken: string | null } };
142
+ }
143
+
144
+ interface AppleAuthenticationModule {
145
+ AppleAuthenticationScope: { FULL_NAME: number; EMAIL: number };
146
+ isAvailableAsync(): Promise<boolean>;
147
+ signInAsync(options: { nonce?: string; requestedScopes: number[] }): Promise<{
148
+ identityToken: string | null;
149
+ email: string | null;
150
+ fullName: { givenName: string | null; familyName: string | null } | null;
151
+ }>;
152
+ }
153
+
154
+ export interface NativeGoogleSignInConfig {
155
+ // Google "Web application" OAuth client id: docs/architecture/plugins/auth.md, "Native client".
156
+ webClientId: string;
157
+ // Google "iOS" OAuth client id (recommended on iOS).
158
+ iosClientId?: string;
159
+ scopes?: string[];
160
+ offlineAccess?: boolean;
161
+ }
162
+
163
+ export async function signInWithGoogleNative(
164
+ client: AuthClient,
165
+ config: NativeGoogleSignInConfig,
166
+ ) {
167
+ // biome-ignore lint/suspicious/noTsIgnore: an optional peer, missing from an app that signs in by the browser
168
+ // @ts-ignore: cannot find module, where the app has not installed it
169
+ const module = await import("@react-native-google-signin/google-signin");
170
+ const { GoogleSignin, isSuccessResponse } =
171
+ module as unknown as GoogleSigninModule;
172
+ GoogleSignin.configure({
173
+ webClientId: config.webClientId,
174
+ iosClientId: config.iosClientId,
175
+ scopes: config.scopes,
176
+ offlineAccess: config.offlineAccess,
177
+ });
178
+ // No-op on iOS; on Android it surfaces the Play Services update prompt before
179
+ // the account sheet.
180
+ await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
181
+ const response = await GoogleSignin.signIn();
182
+ if (!isSuccessResponse(response)) {
183
+ throw new Error("Google sign-in was cancelled.");
184
+ }
185
+ const { idToken } = response.data;
186
+ if (!idToken) {
187
+ throw new Error("Google sign-in returned no id token.");
188
+ }
189
+ return client.signIn.social({
190
+ provider: "google",
191
+ idToken: { token: idToken },
192
+ });
193
+ }
194
+
195
+ export interface NativeAppleSignInOptions {
196
+ // Raw nonce bound into the Apple ID token; Better Auth accepts the raw value
197
+ // or its SHA-256 when present. Omit to skip nonce binding.
198
+ nonce?: string;
199
+ // `AppleAuthentication.AppleAuthenticationScope.FULL_NAME` and `.EMAIL`.
200
+ requestedScopes?: number[];
201
+ }
202
+
203
+ export async function signInWithAppleNative(
204
+ client: AuthClient,
205
+ options?: NativeAppleSignInOptions,
206
+ ) {
207
+ // biome-ignore lint/suspicious/noTsIgnore: an optional peer, missing from an app that signs in by the browser
208
+ // @ts-ignore: cannot find module, where the app has not installed it
209
+ const module = await import("expo-apple-authentication");
210
+ const AppleAuthentication = module as unknown as AppleAuthenticationModule;
211
+ // Sign in with Apple is iOS-only; on Android fall back to the browser flow so
212
+ // the provider still works cross-platform.
213
+ if (!(await AppleAuthentication.isAvailableAsync())) {
214
+ return client.signIn.social({ provider: "apple" });
215
+ }
216
+ const credential = await AppleAuthentication.signInAsync({
217
+ nonce: options?.nonce,
218
+ requestedScopes: options?.requestedScopes ?? [
219
+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
220
+ AppleAuthentication.AppleAuthenticationScope.EMAIL,
221
+ ],
222
+ });
223
+ const idToken = credential.identityToken;
224
+ if (!idToken) {
225
+ throw new Error("Apple sign-in returned no identity token.");
226
+ }
227
+ // Apple returns name/email only on the FIRST authorization — forward them so
228
+ // the server can persist them; later sign-ins rely on the ID token `sub`.
229
+ const user =
230
+ credential.fullName || credential.email
231
+ ? {
232
+ name: credential.fullName
233
+ ? {
234
+ firstName: credential.fullName.givenName ?? undefined,
235
+ lastName: credential.fullName.familyName ?? undefined,
236
+ }
237
+ : undefined,
238
+ email: credential.email ?? undefined,
239
+ }
240
+ : undefined;
241
+ return client.signIn.social({
242
+ provider: "apple",
243
+ idToken: { token: idToken, nonce: options?.nonce, user },
244
+ });
245
+ }
246
+
247
+ // ── Email OTP sign-in ───────────────────────────────────────────────
248
+ //
249
+ // A passwordless email option alongside the social providers: the worker emails
250
+ // a one-time code (via the consumer's `sendOTP` callback), the user enters it,
251
+ // and a session is issued. No deep link or native module — works in Expo Go and
252
+ // before OAuth credentials exist. Enabled on the server by `emailOtp` (on by
253
+ // default); `emailOTPClient()` (wired above) exposes the client methods.
254
+
255
+ export function sendEmailOtp(client: AuthClient, email: string) {
256
+ return client.emailOtp.sendVerificationOtp({ email, type: "sign-in" });
257
+ }
258
+
259
+ export interface EmailOtpSignInOptions {
260
+ email: string;
261
+ otp: string;
262
+ // Display name, used only when this email registers for the first time.
263
+ name?: string;
264
+ }
265
+
266
+ export function signInWithEmailOtp(
267
+ client: AuthClient,
268
+ options: EmailOtpSignInOptions,
269
+ ) {
270
+ return client.signIn.emailOtp({
271
+ email: options.email,
272
+ otp: options.otp,
273
+ ...(options.name ? { name: options.name } : {}),
274
+ });
275
+ }