@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,97 @@
1
+ # MCP connections
2
+
3
+ `auth({ mcp: true })` makes the worker an authorization server for MCP clients: a member connects
4
+ a client by signing in, choosing an organization and approving it, and the client holds a 1-hour
5
+ access token bound to `${APP_URL}/mcp` and a rotating 30-day refresh token. It needs
6
+ `organization`. A client is known by its metadata document
7
+ (the URL it uses as its client id); one that only registers dynamically cannot connect.
8
+
9
+ ```ts
10
+ // slotform.config.ts
11
+ auth({ organization: true, mcp: true }),
12
+ // src/schema/index.ts
13
+ export * from "@slotform/auth/schema/oauth"; // the grant and signing-key tables
14
+ ```
15
+
16
+ The worker serves the discovery documents under `/.well-known/` and limits calls per grant
17
+ (`rateLimiter.agent` in [config](./config.md)). The scopes are `mcp` (the whole tool list) and
18
+ `offline_access` (the refresh token); a request without a `resource` gets a token the verifier
19
+ refuses.
20
+
21
+ ## The pages the app builds
22
+
23
+ The authorization sends the member to three addresses, each carrying a signed query:
24
+
25
+ | Page | Does |
26
+ | --- | --- |
27
+ | `/sign-in` | Signs in by code through `orpc.auth.signIn.sendOtp` and `verifyOtp({ email, otp, oauthQuery })`, whose answer is `{ redirect: true, url }` that the page follows |
28
+ | `/connect/organization` | Asked only of a member of several organizations, or of none; a member of exactly one organization goes from sign-in straight to consent. Then `orpc.auth.organization.setActive({ organizationId, oauthQuery })`, the active one too: it resumes the authorization to consent, answering `{ redirect: true, url }` that the page follows. A member of none sees an empty state whose Deny calls `auth.oauth.consent({ accept: false, oauthQuery })`, which answers the client `access_denied` |
29
+ | `/connect/consent` | Reads the client with `orpc.auth.oauth.client({ clientId })`, shows the session's active organization, and calls `auth.oauth.consent({ accept, oauthQuery })` |
30
+
31
+ `oauthQuery` is the signed part of the page's query string: the `sig` parameter and the parameters
32
+ named by `ba_param`, which the page builds from `location.search` and passes to each of these calls.
33
+ `signIn.verifyOtp`, `signIn.magicLink` and `organization.setActive` take it, and answer the redirect
34
+ beside their own result, only while `mcp` is on. The page leaves to the redirect itself
35
+ (`window.location.assign(url)`). `auth.oauth.client` and `auth.oauth.consent` exist only with `mcp`.
36
+
37
+ Consent is asked on every authorization. The grant is for the session's active organization, which
38
+ must still resolve for the member when they allow: if it no longer does (an expired external
39
+ member, an unknown id), the grant is refused `403` with code `ORGANIZATION_NOT_RESOLVED`. A session
40
+ with no active organization gets the member's one organization, and with two or none is refused the
41
+ same way.
42
+
43
+ ## The endpoint
44
+
45
+ `src/worker/mcp.ts` lists the procedures an agent may call, and the worker serves them at
46
+ `POST /mcp` behind this verification (api's `mcp` page). `mcp` is then a
47
+ reserved organization slug.
48
+
49
+ ## Verifying a call
50
+
51
+ `context.oauth` is on a procedure's context beside `tenancy`. `verify(request)` reads only the
52
+ `Authorization` header and answers the grant's member, or the `Response` the client reads:
53
+
54
+ ```ts
55
+ const verified = await context.oauth.verify(request);
56
+ if (verified instanceof Response) return verified; // 401, 403 or 429, with WWW-Authenticate
57
+ const { user, session, member, grant, tenancy } = verified;
58
+ ```
59
+
60
+ `user` is the member's user row with `agent: true`, `session.id` is the grant's id, and `tenancy`
61
+ resolves the grant's organization and no other. `grant` is
62
+ `{ id, clientId, organizationId, scopes }`. A drizzle read of a grant row's `scopes` answers JSON
63
+ text; `scopesOf` from `@slotform/auth/schema/oauth` returns the list. A token is refused when
64
+ it fails its checks, lacks `mcp` (`403`), or outlives its grant's consent or the member's membership.
65
+
66
+ `revokeGrant(id, userId?)` deletes a grant's consent and tokens and answers whether it existed (with
67
+ `userId`, only that member's); `listGrants(userId)` lists a member's grants. Removing a member, a
68
+ member leaving and deleting an organization end their grants there. Reconnecting a revoked client
69
+ starts a new grant.
70
+
71
+ ## Showing a member their connections
72
+
73
+ `auth.oauth.grants.list` answers the caller's grants, newest first, and `auth.oauth.grants.revoke({ id })` ends one,
74
+ tokens included:
75
+
76
+ ```ts
77
+ const grants = orpc.auth.oauth.grants.list.read(); // { id, name, uri, organizationId, scopes, createdAt }[]
78
+ const revoke = orpc.auth.oauth.grants.revoke.mutationOptions(); // { id }; the list refreshes
79
+ ```
80
+
81
+ `name` is the client's name, or its client id when it has none; `uri` is its address or `null`. The
82
+ list holds the member's grants in every organization, so one client connected to two organizations
83
+ is two rows, told apart by `organizationId`. A grant that is not the caller's, or does not exist, is
84
+ `NOT_FOUND` from `revoke`, so a member cannot learn another's grant ids. Better Auth's own consent
85
+ routes (`/oauth2/get-consent` and the others) stay closed.
86
+
87
+ ## Rules
88
+
89
+ - One grant per client, member and organization: the same client connected twice to one
90
+ organization shares it.
91
+ - A client holds one token per server address, so connecting it to a second organization replaces
92
+ the first in the client; both grants stand.
93
+ - A refresh token reused after its 30-second window revokes every refresh token of that client for
94
+ the member.
95
+
96
+ **Check:** `slotform generate`, `slotform db generate`, then an MCP client connects a member and `verify`
97
+ answers their organization.
@@ -0,0 +1,114 @@
1
+ # Organizations and roles
2
+
3
+ `auth({ organization: true })` gives the app organizations, members with a role each, and
4
+ invitations. Re-export the organization tables (see [config](./config.md)). A procedure acts in
5
+ one organization by taking its `scope` (see [scopes](./scopes.md)), and checks the caller's role
6
+ with `can`.
7
+
8
+ ## Roles
9
+
10
+ With `organization: true` the roles are Better Auth's `owner`, `admin` and `member`, over the
11
+ statements `organization: [update, delete]`, `member: [create, update, delete]`,
12
+ `invitation: [create, cancel]` and `team: [create, update, delete]`. An `owner` holds them all, an
13
+ `admin` all but deleting the organization, a `member` none.
14
+
15
+ Your own permissions take an access control and its roles, declared once in a module the config
16
+ and the web client both import:
17
+
18
+ ```ts
19
+ // src/shared/access.ts
20
+ import { createAccessControl } from "@slotform/auth/access";
21
+
22
+ export const ac = createAccessControl({
23
+ organization: ["update", "delete"],
24
+ member: ["create", "update", "delete"],
25
+ invitation: ["create", "cancel"],
26
+ project: ["create", "update", "delete"],
27
+ });
28
+
29
+ export const roles = {
30
+ owner: ac.newRole({
31
+ organization: ["update", "delete"],
32
+ member: ["create", "update", "delete"],
33
+ invitation: ["create", "cancel"],
34
+ project: ["create", "update", "delete"],
35
+ }),
36
+ editor: ac.newRole({ project: ["create", "update"] }),
37
+ };
38
+ ```
39
+
40
+ ```ts
41
+ // slotform.config.ts
42
+ import { ac, roles } from "./src/shared/access.ts";
43
+ auth({ organization: { ac, roles } }),
44
+
45
+ // src/app/lib/auth.ts
46
+ import { createAuthClient } from "@slotform/auth/client";
47
+ import { ac, roles } from "#/shared/access.ts";
48
+ export const authClient = createAuthClient({
49
+ organization: { statements: ac.statements, roles },
50
+ });
51
+ ```
52
+
53
+ `roles` replaces the default roles. Its statements name what `procedure({ can })` autocompletes.
54
+ A role is a `string` in the calls below: the roles are yours, so a name Better Auth does not know
55
+ is refused by the server, not the type.
56
+
57
+ ## Rules
58
+
59
+ - Keep an `owner` role: Better Auth makes an organization's creator its owner.
60
+ - Keep the `organization`, `member` and `invitation` statements, granted to whoever manages them:
61
+ Better Auth's own endpoints check them.
62
+ - Gate a procedure with `can: [action, resource]`, never by reading `member.role` in the handler.
63
+ - Never read the session's active organization: the organization comes from the scope's input.
64
+ - Delete an organization through `orpc.auth.organization.delete`, which removes its members
65
+ and invitations first; your tables that reference `organization.id` with
66
+ `onDelete: "cascade"` go with it. A raw `DELETE` fails on the foreign keys.
67
+ - Never call `"all"` a resource or `"manage"` an action: both are wildcards to the ability layer
68
+ and throw.
69
+
70
+ ## Slugs
71
+
72
+ An organization is served at `/<slug>`, so the server refuses a slug the app holds: the reserved
73
+ words (`admin`, `api`, `system`, `auth`, `new`, `settings`) and every top-level route of the app.
74
+ `auth.organization.create` and an `auth.organization.update` that sets a slug
75
+ answer it with `BAD_REQUEST` whose `data` holds the code `ORGANIZATION_SLUG_RESERVED` and
76
+ `fieldErrors: { slug }`. A form with a
77
+ `slug` field shows it there; a form that derives the slug from a name maps it onto the name.
78
+
79
+ ## The web app's calls
80
+
81
+ `orpc.auth.organization.*` is the web app's way to manage organizations, members and invitations; each
82
+ needs a session, and a mutation invalidates the queries that read what it writes.
83
+
84
+ | Procedure | Input | Answers |
85
+ | --- | --- | --- |
86
+ | `list` (query) | none | the caller's organizations; reads `organization`, `member` |
87
+ | `create` | `{ name, slug?, logo?, metadata?, keepCurrentActiveOrganization? }`; a missing `slug` is the name's lowercase words joined by hyphens, and a name with no letter or digit needs one (`BAD_REQUEST` `ORGANIZATION_SLUG_REQUIRED`, `fieldErrors: { slug }`) | the organization; writes `organization`, `member`, `session` |
88
+ | `update` | `{ name?, slug?, logo?, metadata?, organizationId? }` | the organization; writes `organization` |
89
+ | `delete` | `{ organizationId }` | writes `organization`, `member`, `session` |
90
+ | `setActive` | `{ organizationId?, organizationSlug? }` | the organization with its members and invitations; writes `session` |
91
+ | `activeMember` (query) | none | the caller's member (with its `role`) in the active organization; reads `member`, `session` |
92
+ | `members.updateRole` | `{ memberId, role, organizationId? }` | the member; writes `member` |
93
+ | `members.remove` | `{ memberIdOrEmail, organizationId? }` | `{ member }`, the removed one; writes `member` |
94
+ | `invitations.create` | `{ email, role, organizationId?, resend? }` | the invitation; writes `invitation` |
95
+ | `invitations.cancel` | `{ invitationId }` | the invitation; writes `invitation` |
96
+ | `invitations.accept` | `{ invitationId }` | `{ invitation, member }`; writes `invitation`, `member`, `organization`, `session` |
97
+ | `invitations.reject` | `{ invitationId }` | `{ invitation, member: null }`; writes `invitation` |
98
+
99
+ ```ts
100
+ const organizations = useQuery(orpc.auth.organization.list.queryOptions());
101
+ await orpc.auth.organization.create.call({ name });
102
+ await orpc.auth.organization.invitations.create.call({ email, role: "editor", organizationId });
103
+ ```
104
+
105
+ Better Auth checks the caller's role against the statements on each call, and a refusal reaches the
106
+ app as an `ORPCError` (`FORBIDDEN`, with Better Auth's `data.code`).
107
+
108
+ ## Abilities
109
+
110
+ `auth({ organization })` serves the caller's compiled rules per organization, and the client's
111
+ `useAbility(organizationId)` reads them (the query plugin's abilities page, `node_modules/@slotform/query/guide/abilities.md`).
112
+ Rules from a record's own data are in [abilities](./abilities.md).
113
+
114
+ **Check:** `slotform generate`, then `pnpm check` passes.
@@ -0,0 +1,29 @@
1
+ # Protect a procedure by scope
2
+
3
+ A procedure that acts on a tenant's data takes its scope, so only members of the organization
4
+ above it reach the handler. Work the steps in order; each names the page it needs and ends with
5
+ its check.
6
+
7
+ ## 1. Find or declare the scope
8
+
9
+ A procedure on an organization's own rows takes `organization`. A procedure on a row of a table
10
+ below it takes that table's scope: find it in `src/shared/scopes.ts`, or declare it with
11
+ `defineScope`. Page: [scopes](./scopes.md).
12
+
13
+ **Check:** `slotform generate`, then `pnpm check` passes.
14
+
15
+ ## 2. Set it on the procedure
16
+
17
+ Set `auth: true` and `scope`, give the procedure a `z.object` input, and read the rows from the
18
+ context, never from an id of the input's own. Add `can` when only some roles may act. Page: api's
19
+ procedures page (`node_modules/@slotform/api/guide/procedures.md`).
20
+
21
+ ```ts
22
+ rename: procedure({ auth: true, scope: project, can: ["update", "project"], writes: ["project"] })
23
+ .input(z.object({ name: z.string().min(1) }))
24
+ .mutation(async ({ input, context }) => {
25
+ // update context.project through context.db
26
+ }),
27
+ ```
28
+
29
+ **Check:** `pnpm check` passes, and the procedure's input requires `projectId`.
@@ -0,0 +1,87 @@
1
+ # Scopes
2
+
3
+ A scope is one tenancy tier a procedure acts inside. The organization is the root scope, exported
4
+ as `organization` from `@slotform/auth/scope`; a table of yours under it, or under another
5
+ scope, becomes one with `defineScope`. Scopes need `auth({ organization })`.
6
+
7
+ Declare every scope in `src/shared/scopes.ts`, a module the worker and the app both import:
8
+
9
+ ```ts
10
+ // src/shared/scopes.ts
11
+ import { member } from "@slotform/auth/schema/organization";
12
+ import { defineMembership, defineScope, organization } from "@slotform/auth/scope";
13
+ import { sql } from "@slotform/db/orm";
14
+ import * as schema from "../schema/index.ts";
15
+
16
+ const { membership } = schema;
17
+
18
+ export const unexpired = defineMembership(
19
+ sql`not exists (select 1 from ${membership} where ${membership.memberId} = ${member.id}
20
+ and ${membership.expiresAt} <= cast(unixepoch('subsecond') * 1000 as integer))`,
21
+ );
22
+
23
+ export const project = defineScope({
24
+ name: "project",
25
+ table: schema.project,
26
+ parent: [organization, schema.project.organizationId],
27
+ slug: schema.project.slug,
28
+ where: (m) => sql`${schema.project.ownerId} = ${m.userId}`,
29
+ });
30
+
31
+ export const page = defineScope({
32
+ name: "page",
33
+ table: schema.page,
34
+ parent: [project, schema.page.projectId],
35
+ });
36
+ ```
37
+
38
+ `procedure({ auth: true, scope: page })` then takes `pageId` in its input and loads, per request,
39
+ the page, its project, its organization and the caller's `member` row into the context as `page`,
40
+ `project`, `organization` and `member`, one indexed lookup per tier, plus one more for each tier
41
+ that declares `where`. The parents come from the rows, so a client cannot pair a page with another
42
+ project's id. A missing row and a caller who is no member of the organization both answer
43
+ `NOT_FOUND`. `can` checks that member's role: roles live on the organization membership, and every
44
+ scope below inherits them.
45
+
46
+ ## Who sees a row
47
+
48
+ Two optional predicates narrow resolution, both drizzle `sql` fragments so the module stays
49
+ isomorphic:
50
+
51
+ - `defineMembership(fragment)` decides which `member` rows count as a membership: a fragment over
52
+ `member`, correlated to your own tables. Export at most one; two fail at startup.
53
+ - A scope's `where` takes the caller's `member` row and returns a fragment over the scope's table:
54
+ whether that row is visible to them. Reuse the same function to filter your lists.
55
+
56
+ A failing predicate answers the same `NOT_FOUND` as a missing row, before `can` runs, in every
57
+ scoped procedure, `bySlug` and `auth.orgRules`. A tier below an invisible one is refused with it.
58
+ The refusal's message is `No such <scope>`, the scope's name in plain words: `lineItem` and
59
+ `line_item` read "No such line item".
60
+
61
+ ## Lookup by slug
62
+
63
+ Each scope with a `slug`, the organization included, gets a procedure that resolves a URL's slug
64
+ to its chain: `auth.scope.<name>.bySlug`, taking `{ slug }` for the organization and
65
+ `{ slug, parentId }` below it. It answers the same rows a scoped procedure loads, or `NOT_FOUND`.
66
+ The worker's `AppRouter` types it: `AppRouter["auth"]["scope"]` has a key for each scope with a
67
+ `slug`, and each `bySlug` answers `ScopeContext<typeof scope>`.
68
+ It declares `reads` on `member` and on each table of its chain by the table's SQL name, so a
69
+ mutation that declares `writes: ["project"]` refreshes it. A table only a predicate reads is not
70
+ among them.
71
+
72
+ In a handler, `context.tenancy.resolve(scope, id, userId)` and `bySlug(...)` answer the same rows
73
+ typed by the scope: `ScopeContext<typeof scope> | null`.
74
+
75
+ ## Rules
76
+
77
+ - The table has an `id` primary key; the parent column and the slug column are its own.
78
+ - A slug is unique within its parent: give the table a unique index on the parent column and the
79
+ slug.
80
+ - Export each scope's table from `src/schema/index.ts` under its SQL name (`project` for the table
81
+ `project`), so its entity matches the lookup's reads.
82
+ - A scope name is never a key the procedure context already carries (`env`, `httpRequest`, `reqHeaders`, `resHeaders`, `executionCtx`, `_devMode`, `db`, `auth`, `tenancy`, `_rateLimiter`, `_trustedOrigins`, `user`, `session`, `organization`, `member`, `_caller`, `oauth`): `defineScope` throws on one. Every scope name is unique.
83
+ - The parent column references the parent's `id` with `onDelete: "cascade"`, so a deleted
84
+ organization takes its scopes with it.
85
+ - Never resolve a tenancy tier by hand in a handler: declare the scope.
86
+
87
+ **Check:** `slotform generate`, then `pnpm check` passes.
@@ -0,0 +1,127 @@
1
+ # Sign-in
2
+
3
+ Email one-time codes are on by default; magic links, OAuth and passkeys are options of `auth()`. A web
4
+ app reads the session and signs in and out through the `orpc.auth.*` procedures
5
+ ([the web app's calls](#the-web-apps-calls)); Better Auth serves the emailed link's verification,
6
+ OAuth and passkeys under `/api/auth` on the worker.
7
+
8
+ ## Magic links
9
+
10
+ `magicLink: true` adds sign-in by emailed link and requires `sendMagicLink({ email, url, token, env })`
11
+ in the callbacks file ([callbacks](./callbacks.md)). The token expires in 5 minutes and is spent on
12
+ its first verification. An address with no user signs up when its link is first opened.
13
+
14
+ ```ts
15
+ auth({ magicLink: true }),
16
+ // a web app
17
+ await orpc.auth.signIn.magicLink.call({ email, callbackURL: "/home" });
18
+ ```
19
+
20
+ `callbackURL` is relative or on a trusted origin; the verify redirect refuses any other. A
21
+ spent, unknown or expired link redirects to `callbackURL` with `error=INVALID_TOKEN`.
22
+
23
+ ## OAuth
24
+
25
+ `socialProviders.google` and `.apple` take `true` for the conventional var names
26
+ (`GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`, `APPLE_CLIENT_ID` / `APPLE_CLIENT_SECRET`) or
27
+ `{ clientIdVar, clientSecretVar }` to rename them. Apple takes `appBundleIdentifier` for native
28
+ ID-token sign-in.
29
+
30
+ ```ts
31
+ auth({ emailOtp: false, socialProviders: { google: true, apple: true } }),
32
+ ```
33
+
34
+ `emailOtp: false` makes an OAuth-only app: no code sign-in and no required `sendOTP`.
35
+
36
+ ## Passkeys
37
+
38
+ `passkey: {}` turns them on with every setting derived: `rpID` from `app.domain`, `rpName` from
39
+ `app.name`, the accepted origins from the production CORS list. Set any of them, or
40
+ `authenticatorSelection`, on the same object. Re-export the `passkey` table
41
+ ([config](./config.md)). Under `slotform dev` the ceremony runs on `localhost`, so a passkey enrolled
42
+ in dev works only in dev. On a Node listener that serves an origin of its own, the ceremony runs at
43
+ that origin. Enrolling needs a session younger than `session.freshAge`: the user
44
+ signs in another way first, calls `passkey.addPasskey()`, and signs in with `signIn.passkey()`
45
+ after.
46
+
47
+ ## Who may sign up
48
+
49
+ Every way in makes an account for an address it has not seen: a code or link verified, an OAuth
50
+ callback. `signUp` closes that, with one rule for all of them.
51
+
52
+ | `signUp` | An address with no account may sign up when |
53
+ | --- | --- |
54
+ | `"open"` (default) | always |
55
+ | `"invite"` | it holds a pending, unexpired organization invitation |
56
+ | `"first"` | the app has no account yet; after that, as `"invite"` |
57
+
58
+ A single-owner app is `signUp: "first"` with `organization: true`: the owner signs in first,
59
+ creates the organization, and invites anyone else from it ([organizations](./organizations.md)).
60
+ An address that already has an account always signs in.
61
+
62
+ ```ts
63
+ auth({ organization: true, signUp: "first" }),
64
+ ```
65
+
66
+ A refused sign-up answers `FORBIDDEN` with code `SIGN_UP_CLOSED` (the `ORPCError`'s `data.code`)
67
+ and the sentence "Sign-up is closed. Ask for an invitation to join." in `message`, which a screen
68
+ shows. The code and link sends refuse it before an email goes out, so a closed app tells a stranger
69
+ whether an address has an account; an OAuth callback redirects with it as `error`.
70
+
71
+ ## The web app's calls
72
+
73
+ A web app never imports Better Auth's client for what the worker serves as procedures. Each is a
74
+ typed oRPC procedure under `auth`, present while its option is on and a type error to name
75
+ otherwise.
76
+
77
+ ```ts
78
+ const session = useQuery(orpc.auth.session.queryOptions()); // { user, session } | null
79
+ await orpc.auth.signIn.sendOtp.call({ email });
80
+ await orpc.auth.signIn.verifyOtp.call({ email, otp });
81
+ await orpc.auth.user.update.call({ name });
82
+ await orpc.auth.signOut.call();
83
+ ```
84
+
85
+ | Procedure | Option | Input | Answers |
86
+ | --- | --- | --- | --- |
87
+ | `auth.session` (query) | always | `{ disableCookieCache? }`, optional | `{ user, session } \| null`; reads `session` |
88
+ | `auth.signOut` | always | none | `{ success }`; writes `session` |
89
+ | `auth.user.update` | always, session | `{ name?, image? }` | `{ status }`; writes `session`, `member` |
90
+ | `auth.signIn.sendOtp` | `emailOtp` | `{ email }` | `{ success }` |
91
+ | `auth.signIn.verifyOtp` | `emailOtp` | `{ email, otp (six digits), name?, image?, oauthQuery? }` | `{ token, user }`, or `{ redirect: true, url }` inside an MCP authorization; writes `session` |
92
+ | `auth.signIn.magicLink` | `magicLink` | `{ email, name?, callbackURL?, newUserCallbackURL?, errorCallbackURL?, metadata?, oauthQuery? }` | `{ status }` |
93
+
94
+ Both sends are limited per email (`TOO_MANY_REQUESTS`). A refusal's `code` is the endpoint's
95
+ (`BAD_REQUEST` for a wrong code) and its `data.code` Better Auth's (`INVALID_OTP`). The
96
+ organization calls are in [organizations](./organizations.md); `oauthQuery` is
97
+ [mcp-oauth](./mcp-oauth.md)'s.
98
+
99
+ Social sign-in and passkeys have no procedure and stay on `createAuthClient` from
100
+ `@slotform/auth/client`, Better Auth's React client, given the flags the config sets:
101
+
102
+ ```ts
103
+ // src/app/lib/auth.ts
104
+ import { createAuthClient } from "@slotform/auth/client";
105
+
106
+ export const authClient = createAuthClient({ passkey: true });
107
+
108
+ await authClient.signIn.social({ provider: "google" });
109
+ ```
110
+
111
+ `baseURL` defaults to the page's origin.
112
+
113
+ ## The native client
114
+
115
+ The phone signs in through `@slotform/auth/expo`, set up by `auth({ expo: true })`: its
116
+ server option, scaffolded client and sign-in helpers are
117
+ `node_modules/@slotform/expo/guide/native-auth.md`.
118
+
119
+ ## Rules
120
+
121
+ - The server decides which providers exist: a call to a provider the config leaves off fails, and
122
+ its procedure is absent from `AppRouter`.
123
+ - Close sign-up with `signUp`, never a `sendOTP` that returns early or a hand-written hook: it
124
+ would leave OAuth open.
125
+ - Read the session through `orpc.auth.session`, never `authClient.useSession()`, in a web app.
126
+
127
+ **Check:** `pnpm check` passes, and under `pnpm dev` a sign-in sets the session cookie.
package/package.json CHANGED
@@ -1,6 +1,158 @@
1
1
  {
2
2
  "name": "@slotform/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Authentication for slotform: Better Auth with email codes, magic links, OAuth, passkeys, organizations, roles and record abilities.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/fcalell/slotform.git",
9
+ "directory": "plugins/auth"
10
+ },
11
+ "homepage": "https://github.com/fcalell/slotform/tree/master/plugins/auth#readme",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "engines": {
16
+ "node": ">=24.14.0"
17
+ },
18
+ "type": "module",
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./ability": {
26
+ "types": "./dist/ability/index.d.ts",
27
+ "default": "./dist/ability/index.js"
28
+ },
29
+ "./runtime": {
30
+ "types": "./dist/worker/index.d.ts",
31
+ "default": "./dist/worker/index.js"
32
+ },
33
+ "./schema": {
34
+ "types": "./dist/schema/index.d.ts",
35
+ "default": "./dist/schema/index.js"
36
+ },
37
+ "./schema/organization": {
38
+ "types": "./dist/schema/organization.d.ts",
39
+ "default": "./dist/schema/organization.js"
40
+ },
41
+ "./schema/oauth": {
42
+ "types": "./dist/schema/oauth.d.ts",
43
+ "default": "./dist/schema/oauth.js"
44
+ },
45
+ "./schema/passkey": {
46
+ "types": "./dist/schema/passkey.d.ts",
47
+ "default": "./dist/schema/passkey.js"
48
+ },
49
+ "./schema/devices": {
50
+ "types": "./dist/schema/devices.d.ts",
51
+ "default": "./dist/schema/devices.js"
52
+ },
53
+ "./expo": "./src/expo.tsx",
54
+ "./client": {
55
+ "types": "./dist/client.d.ts",
56
+ "default": "./dist/client.js"
57
+ },
58
+ "./scope": {
59
+ "types": "./dist/scope.d.ts",
60
+ "default": "./dist/scope.js"
61
+ },
62
+ "./access": {
63
+ "types": "./dist/access.d.ts",
64
+ "default": "./dist/access.js"
65
+ },
66
+ "./infer": {
67
+ "types": "./dist/infer.d.ts",
68
+ "default": "./dist/infer.js"
69
+ },
70
+ "./screens": {
71
+ "types": "./dist/screens.d.ts",
72
+ "default": "./dist/screens.js"
73
+ },
74
+ "./serve": {
75
+ "types": "./dist/serve.d.ts",
76
+ "default": "./dist/serve.js"
77
+ },
78
+ "./screens-fixtures": {
79
+ "types": "./dist/screens-fixtures.d.ts",
80
+ "default": "./dist/screens-fixtures.js"
81
+ }
82
+ },
83
+ "files": [
84
+ "dist",
85
+ "src",
86
+ "guide",
87
+ "templates",
88
+ "README.md",
89
+ "LICENSE",
90
+ "!src/**/*.test.ts",
91
+ "!src/**/__fixtures__",
92
+ "!dist/**/*.test.*"
93
+ ],
94
+ "dependencies": {
95
+ "@better-auth/cimd": "1.7.25",
96
+ "@better-auth/core": "1.7.25",
97
+ "@better-auth/expo": "1.7.25",
98
+ "@better-auth/mcp": "1.7.25",
99
+ "@slotform/cli": "^0.1.1",
100
+ "@slotform/api": "^0.1.1",
101
+ "@slotform/cloudflare": "^0.1.1",
102
+ "@slotform/db": "^0.1.1",
103
+ "@slotform/screens": "^0.1.1",
104
+ "ws": "^8.23.0"
105
+ },
106
+ "peerDependencies": {
107
+ "@better-auth/api-key": "1.7.25",
108
+ "@better-auth/oauth-provider": "1.7.25",
109
+ "@better-auth/passkey": "1.7.25",
110
+ "@casl/ability": "^7.1.3",
111
+ "@orpc/server": "^1.16.2",
112
+ "@react-native-google-signin/google-signin": "^17.0.0",
113
+ "better-auth": "1.7.25",
114
+ "drizzle-orm": "^0.45.4",
115
+ "expo-apple-authentication": ">=58.0.0",
116
+ "msw": "^3.0.6",
117
+ "react": "^19.3.0",
118
+ "zod": "^4.6.7"
119
+ },
120
+ "peerDependenciesMeta": {
121
+ "@react-native-google-signin/google-signin": {
122
+ "optional": true
123
+ },
124
+ "expo-apple-authentication": {
125
+ "optional": true
126
+ },
127
+ "react": {
128
+ "optional": true
129
+ },
130
+ "msw": {
131
+ "optional": true
132
+ }
133
+ },
134
+ "devDependencies": {
135
+ "@slotform/typescript-config": "^0.1.1",
136
+ "@types/node": "^26.6.6",
137
+ "@react-native-google-signin/google-signin": "^17.0.0",
138
+ "@types/react": "^19.3.0",
139
+ "expo-apple-authentication": "~58.0.3",
140
+ "react": "19.3.0",
141
+ "typescript": "^7.0.2",
142
+ "zod": "^4.6.7",
143
+ "@orpc/server": "^1.16.2",
144
+ "@casl/ability": "^7.1.3",
145
+ "better-auth": "1.7.25",
146
+ "@better-auth/api-key": "1.7.25",
147
+ "@better-auth/oauth-provider": "1.7.25",
148
+ "@better-auth/passkey": "1.7.25",
149
+ "drizzle-orm": "^0.45.4",
150
+ "msw": "^3.0.6"
151
+ },
152
+ "scripts": {
153
+ "build": "tsc -p tsconfig.build.json",
154
+ "check-types": "tsc --noEmit --pretty",
155
+ "clear": "rm -rf dist node_modules .turbo",
156
+ "test": "node --test 'src/**/*.test.ts'"
157
+ }
6
158
  }