@riffdb/better-auth 0.0.0-stage → 0.2.0

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 (91) hide show
  1. package/DESIGN.md +197 -0
  2. package/LICENSE-APACHE +201 -0
  3. package/LICENSE-MIT +27 -0
  4. package/README.md +191 -2
  5. package/dist/adapter.d.ts +28 -0
  6. package/dist/adapter.d.ts.map +1 -0
  7. package/dist/adapter.js +1262 -0
  8. package/dist/adapter.js.map +1 -0
  9. package/dist/generated/client.d.ts +1925 -0
  10. package/dist/generated/client.d.ts.map +1 -0
  11. package/dist/generated/client.js +2044 -0
  12. package/dist/generated/client.js.map +1 -0
  13. package/dist/index.d.ts +5 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +5 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/profile-contract.d.ts +60 -0
  18. package/dist/profile-contract.d.ts.map +1 -0
  19. package/dist/profile-contract.js +535 -0
  20. package/dist/profile-contract.js.map +1 -0
  21. package/dist/profile-plan.d.ts +69 -0
  22. package/dist/profile-plan.d.ts.map +1 -0
  23. package/dist/profile-plan.js +180 -0
  24. package/dist/profile-plan.js.map +1 -0
  25. package/dist/profile.d.ts +47 -0
  26. package/dist/profile.d.ts.map +1 -0
  27. package/dist/profile.js +131 -0
  28. package/dist/profile.js.map +1 -0
  29. package/dist/testing.d.ts +11 -0
  30. package/dist/testing.d.ts.map +1 -0
  31. package/dist/testing.js +12 -0
  32. package/dist/testing.js.map +1 -0
  33. package/generated/go/client.go +1996 -0
  34. package/generated/mcp/tools.json +12352 -0
  35. package/generated/python/client.py +3877 -0
  36. package/generated/riffdb.application.exact.json +1 -0
  37. package/generated/riffdb.contract.bundle +0 -0
  38. package/generated/rust/client.rs +6028 -0
  39. package/package.json +62 -4
  40. package/profiles/organization-security/materialization.json +48 -0
  41. package/profiles/organization-security/riffdb/contract.riff +766 -0
  42. package/profiles/organization-security/riffdb/queries/find_account_by_id.riffq +18 -0
  43. package/profiles/organization-security/riffdb/queries/find_invitation_by_email.riffq +17 -0
  44. package/profiles/organization-security/riffdb/queries/find_invitation_by_id.riffq +18 -0
  45. package/profiles/organization-security/riffdb/queries/find_invitation_by_organization_id.riffq +17 -0
  46. package/profiles/organization-security/riffdb/queries/find_member_by_id.riffq +18 -0
  47. package/profiles/organization-security/riffdb/queries/find_member_by_user_id.riffq +17 -0
  48. package/profiles/organization-security/riffdb/queries/find_organization_by_id.riffq +16 -0
  49. package/profiles/organization-security/riffdb/queries/find_organization_by_slug.riffq +16 -0
  50. package/profiles/organization-security/riffdb/queries/find_session_by_id.riffq +18 -0
  51. package/profiles/organization-security/riffdb/queries/find_session_by_token.riffq +16 -0
  52. package/profiles/organization-security/riffdb/queries/find_team_by_id.riffq +18 -0
  53. package/profiles/organization-security/riffdb/queries/find_team_member_by_id.riffq +18 -0
  54. package/profiles/organization-security/riffdb/queries/find_team_member_by_team_id.riffq +17 -0
  55. package/profiles/organization-security/riffdb/queries/find_two_factor_by_id.riffq +18 -0
  56. package/profiles/organization-security/riffdb/queries/find_two_factor_by_secret.riffq +17 -0
  57. package/profiles/organization-security/riffdb/queries/find_user_by_email.riffq +16 -0
  58. package/profiles/organization-security/riffdb/queries/find_user_by_id.riffq +16 -0
  59. package/profiles/organization-security/riffdb/queries/find_verification_by_id.riffq +16 -0
  60. package/profiles/organization-security/riffdb/queries/find_verification_by_identifier.riffq +17 -0
  61. package/profiles/organization-security/riffdb.application.json +167 -0
  62. package/profiles/organization-security/riffdb.toml +7 -0
  63. package/profiles/organization-security.profile.json +954 -0
  64. package/riffdb/contract.riff +489 -0
  65. package/riffdb/queries/admin_users_all_email_asc.riffq +24 -0
  66. package/riffdb/queries/admin_users_contains_asc.riffq +24 -0
  67. package/riffdb/queries/admin_users_contains_desc.riffq +24 -0
  68. package/riffdb/queries/admin_users_email_contains_created_desc.riffq +24 -0
  69. package/riffdb/queries/admin_users_email_contains_image_asc.riffq +24 -0
  70. package/riffdb/queries/admin_users_ends_with_asc.riffq +24 -0
  71. package/riffdb/queries/admin_users_ends_with_desc.riffq +24 -0
  72. package/riffdb/queries/admin_users_starts_with_asc.riffq +24 -0
  73. package/riffdb/queries/admin_users_starts_with_desc.riffq +24 -0
  74. package/riffdb/queries/find_account_by_id.riffq +24 -0
  75. package/riffdb/queries/find_account_by_provider.riffq +26 -0
  76. package/riffdb/queries/find_accounts_by_user_id.riffq +25 -0
  77. package/riffdb/queries/find_accounts_by_user_provider.riffq +27 -0
  78. package/riffdb/queries/find_active_sessions_by_user_id.riffq +23 -0
  79. package/riffdb/queries/find_expired_verification_ids.riffq +17 -0
  80. package/riffdb/queries/find_latest_verification.riffq +20 -0
  81. package/riffdb/queries/find_session_by_id.riffq +20 -0
  82. package/riffdb/queries/find_session_by_token.riffq +20 -0
  83. package/riffdb/queries/find_sessions_by_token_set.riffq +20 -0
  84. package/riffdb/queries/find_sessions_by_user_id.riffq +21 -0
  85. package/riffdb/queries/find_user_by_email.riffq +16 -0
  86. package/riffdb/queries/find_user_by_id.riffq +15 -0
  87. package/riffdb/queries/find_verification_by_id.riffq +19 -0
  88. package/riffdb/queries/find_verifications_by_identifier.riffq +21 -0
  89. package/riffdb.application.json +107 -0
  90. package/riffdb.application.lock.json +1 -0
  91. package/scripts/real-riffdb-runner.mjs +333 -0
package/DESIGN.md ADDED
@@ -0,0 +1,197 @@
1
+ # Design boundary
2
+
3
+ ## Package responsibility
4
+
5
+ `@riffdb/better-auth` owns Better Auth schema interpretation, profile
6
+ generation, adapter method mapping, and Better Auth conformance tests. RiffDB
7
+ owns database semantics, compiled operations, authorization, durability,
8
+ idempotency, and the Rust-backed TypeScript transport.
9
+
10
+ ## Better Auth 1.6.29 method inventory
11
+
12
+ The adapter project must cover the current `createAdapterFactory` interface:
13
+
14
+ - `create`
15
+ - `update`
16
+ - `updateMany`
17
+ - `delete`
18
+ - `deleteMany`
19
+ - `consumeOne`
20
+ - `findOne`
21
+ - `findMany`
22
+ - `count`
23
+ - `incrementOne`
24
+
25
+ The Better Auth API presents these as generic model/where/update requests.
26
+ The RiffDB adapter must instead recognize a finite reviewed call shape and
27
+ dispatch to one generated named command or query. An unmatched combination
28
+ is an unsupported-profile error, never a dynamic RiffQL expression or generic
29
+ storage callback.
30
+
31
+ The core profile implements exact user `count` and bounded user windows for a
32
+ finite set of UUID and email predicates. Numeric offset, exact total, text
33
+ matching, independent order, and nullable order are declared in the compiled
34
+ query. The result page and total therefore share one provider epoch; the
35
+ adapter neither drains pages nor recounts client-side.
36
+
37
+ `consumeOne` maps to one atomic delete-and-return compiled command. The same
38
+ command executes immediately when Better Auth invokes `consumeOne` inside its
39
+ verification cleanup callback, so two racers cannot both observe a token and
40
+ the loser receives `null`. Any remaining identifier-scoped verification rows
41
+ are removed afterward by the bounded compiled set command. Signup and OAuth
42
+ transactions remain single-command atomic graphs; unknown callback shapes fail
43
+ closed.
44
+
45
+ Mutable core records carry internal monotonically increasing revisions. The
46
+ adapter reads that compiler-owned revision, sends it to an exact update
47
+ command, and retries a bounded stale outcome. This preserves partial-update
48
+ semantics without allowing a client-side read/modify/write race to overwrite
49
+ an unrelated concurrent change. Revisions are not exposed as Better Auth
50
+ model fields.
51
+
52
+ Password-only account updates use the same revision protocol. The adapter
53
+ queries the bounded `(organization_id, user_id, provider_id)` index, submits
54
+ every observed revision to `UpdateAccountPasswords`, and retries a stale whole
55
+ command. An OAuth refresh therefore cannot restore a password from an older
56
+ account snapshot.
57
+
58
+ ## Upstream patterns adopted
59
+
60
+ The adapter follows Better Auth's documented `createAdapterFactory` boundary
61
+ and lets that factory own its standard model/field mapping and value
62
+ transformations. It uses the current `@better-auth/test-utils/adapter`
63
+ conformance harness rather than reproducing the upstream tests.
64
+
65
+ Community adapters are useful compatibility references, especially the
66
+ non-relational Convex, Firestore, InstantDB, and DynamoDB implementations. The
67
+ patterns worth retaining are:
68
+
69
+ - declare storage capabilities explicitly in the adapter factory;
70
+ - keep transport/storage mechanics behind a small typed seam;
71
+ - derive and validate schema metadata before serving requests;
72
+ - exercise the adapter through Better Auth's own conformance suite; and
73
+ - treat pagination, uniqueness, and atomic consumption as database semantics,
74
+ not incidental adapter conveniences.
75
+
76
+ RiffDB intentionally does not copy their generic CRUD dispatch, unbounded
77
+ page-draining, sequential multi-row mutation, or callback-transaction
78
+ patterns. Its seam consists of generated named operations for a compiled
79
+ profile, with explicit bounds and idempotency identity.
80
+
81
+ ## Profile planning boundary
82
+
83
+ Better Auth's `createSchema` hook is exposed through a generation-only adapter.
84
+ It captures Better Auth's resolved tables after plugins, additional fields,
85
+ and storage-name overrides have been applied. The deterministic plan records
86
+ only bounded declarative metadata and never connects to RiffDB.
87
+
88
+ A plan is not a runtime database schema. Materializing it requires a reviewed
89
+ RiffDB contract, finite named queries and commands for the call shapes used by
90
+ that Better Auth configuration, generated bindings, and equivalent conformance
91
+ tests. This separation makes the profile customizable without turning schema
92
+ generation into a generic database or weakening the application-facing safety
93
+ boundary. The generation adapter rejects every runtime method.
94
+
95
+ ## Materialization
96
+
97
+ `materializeRiffDBBetterAuthProfile` turns a reviewed plan into the first two
98
+ of those artifacts: one contract and one named query per accepted call shape,
99
+ plus the application source binding them. It emits source for review and
100
+ compilation, never a deployment, and it never connects to RiffDB.
101
+
102
+ Rows partition on `tenant_id`. The column is deliberately not `organization_id`
103
+ because the organization plugin contributes a model of that name, whose
104
+ synthesized key column would collide. Each model's key column is likewise
105
+ resolved against the rest of its entity: Better Auth's `account` carries the
106
+ provider's own `accountId`, so that entity keys on `account_row_id`.
107
+
108
+ Aggregate assignment follows the reference graph. A model with no references is
109
+ a root; a model that references a root becomes that root's child, choosing the
110
+ first such reference in sorted field order so the assignment is deterministic;
111
+ anything else is its own root, because a RiffDB aggregate is one level deep and
112
+ a child cannot own children. A child's key is prefixed by its root's key, which
113
+ is what makes the aggregate provable.
114
+
115
+ Deletion follows from that shape. A root cascades to its children, naming each
116
+ relationship and the reverse index that serves it. SPEC DEL-004 bounds the
117
+ whole discovered graph at `root_count_maximum * (1 + sum(maxima)) <= 256`, so a
118
+ wide aggregate lowers its per-relationship maximum and its bulk-delete root
119
+ count rather than failing to compile: `user` owns five children and admits one
120
+ root per command, `organization` owns two and admits three.
121
+
122
+ The generator does not pretend to enforce what RiffDB cannot prove. A cascade
123
+ may not cross an aggregate (DEL-003) and must cover every inbound relationship
124
+ exactly once (DEL-002), so a join model that reaches two roots can declare only
125
+ the edge that owns it. Every other edge becomes an indexed `uuid` field and is
126
+ listed in the materialization report as an unenforced reference. For the
127
+ representative organization and two-factor plan those are
128
+ `invitation.organizationId`, `member.userId`, and `teamMember.teamId`; the
129
+ adapter, not the contract, is responsible for their integrity. A reviewer who
130
+ needs one of them enforced changes the aggregate assignment by hand.
131
+
132
+ `profiles/organization-security/` is the materialized fixture for the
133
+ representative plan, regenerated by `npm run profiles:materialize` and verified
134
+ byte-for-byte by `npm run profiles:check`. It ships its own `riffdb.toml`, so
135
+ the claim made about it is checkable directly: `riffdb application check` in
136
+ that directory compiles the contract and all nineteen queries.
137
+
138
+ References:
139
+
140
+ - <https://better-auth.com/docs/guides/create-a-db-adapter>
141
+ - <https://better-auth.com/docs/adapters/community-adapters>
142
+ - <https://github.com/get-convex/better-auth>
143
+ - <https://github.com/yultyyev/better-auth-firestore>
144
+ - <https://github.com/datar-platform/better-auth-dynamodb>
145
+
146
+ ## First-profile exclusions
147
+
148
+ - renamed models or fields;
149
+ - additional user/session fields;
150
+ - plugin models or plugin-added fields;
151
+ - numeric, serial, mixed, or database-generated identifiers;
152
+ - arbitrary joins, predicates, offsets beyond the compiled bound, or sort
153
+ combinations outside the named user-window queries;
154
+ - Better Auth database hooks that imply additional database mutations; and
155
+ - secondary storage implemented by RiffDB.
156
+
157
+ ## Closed RiffDB blockers
158
+
159
+ The loopback conformance run deploys the exact contract and role and connects
160
+ through `riffdb-driverd`. The initial empty `FindUserByEmail` result carries the
161
+ valid application head `0`; `@riffdb/client@0.2.0` preserves it
162
+ as `0n`. The adapter does not issue an unrelated warmup write, so the first
163
+ application-visible mutation remains the compiled signup graph.
164
+
165
+ RiffDB now supports bounded cascade deletion across the `Account` and `Session`
166
+ inbound relationships, so user deletion retains stored referential integrity
167
+ and executes as one compiled command.
168
+
169
+ Named RiffQL queries now support exact compiler-declared secret output leaves.
170
+ The application role derives dedicated secret-field visibility from each
171
+ selected immutable query, which closes the former `RDB-AUTH-0214` failure
172
+ without using read-only commands or broadening the role manually.
173
+
174
+ Unary compiled deletes can now return the exact transaction-revalidated
175
+ preimage, including explicitly authorized secret leaves. Verification
176
+ consumption therefore has one durable delete/result boundary rather than a
177
+ query followed by a delete.
178
+
179
+ RiffQL now supports finite exact text predicates, numeric offsets, exact totals,
180
+ independent ordering, and explicit null placement. The generated TypeScript
181
+ client also emits only reachable compact decoders, so it compiles under strict
182
+ consumer `noUnusedLocals` settings without generated-source suppressions.
183
+
184
+ These exclusions describe the first profile, not permanent product limits.
185
+ Each addition needs an explicit bounded contract and semantic tests.
186
+
187
+ ## Secrets and authority
188
+
189
+ Session tokens, verification values, passwords, OAuth access/refresh tokens,
190
+ and ID tokens require deliberate secret classification in the generated
191
+ RiffDB contract. Every named RiffQL result leaf that returns one carries an
192
+ exact `reveals` annotation. That declaration participates in immutable query
193
+ and role identity, while the generated Better Auth server role receives only
194
+ the corresponding secret-field visibility. These queries are typed SDK reads
195
+ and are omitted from MCP tool generation. End-user identity and session
196
+ semantics remain Better Auth's responsibility; the adapter must not turn them
197
+ into RiffDB capability administration.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright © 2026 Kevin O'Shea and O'Shea & Sons, LLC.
4
+
5
+ Permission is hereby granted, free of charge, to any
6
+ person obtaining a copy of this software and associated
7
+ documentation files (the "Software"), to deal in the
8
+ Software without restriction, including without
9
+ limitation the rights to use, copy, modify, merge,
10
+ publish, distribute, sublicense, and/or sell copies of
11
+ the Software, and to permit persons to whom the Software
12
+ is furnished to do so, subject to the following
13
+ conditions:
14
+
15
+ The above copyright notice and this permission notice
16
+ shall be included in all copies or substantial portions
17
+ of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
26
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,192 @@
1
- # Temporary Holding Version
1
+ # `@riffdb/better-auth`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An external Better Auth database adapter for RiffDB.
4
+
5
+ Status: v0.2.0. The core runtime profile is implemented and
6
+ passes Better Auth's pinned authentication-flow suite plus a real RiffDB
7
+ loopback suite. Profile planning is implemented for custom fields and plugins,
8
+ and a reviewed plan now materializes into a RiffDB contract, named queries, and
9
+ application source that compile. Binding a materialized profile to a running
10
+ adapter instance is not implemented: the adapter still dispatches only to the
11
+ core profile's generated client.
12
+
13
+ ## Architecture boundary
14
+
15
+ Better Auth-specific code lives in this repository, never in RiffDB. The
16
+ adapter dispatches only to generated named RiffDB commands and queries from a
17
+ reviewed compiled profile. It does not expose generic CRUD, accept arbitrary
18
+ transaction callbacks, perform client-side authorization filtering, or
19
+ silently fall back for unknown models, fields, joins, predicates, or plugins.
20
+
21
+ The shipped runtime profile is deliberately exact:
22
+
23
+ - Better Auth `1.6.29`;
24
+ - the four default core models and their default field names;
25
+ - UUID identifiers for every model;
26
+ - no runtime plugins or additional fields; and
27
+ - the bundled `RiffDBBetterAuthCore` contract and `BetterAuthServer` role.
28
+
29
+ Unsupported configuration fails before any RiffDB request. A custom or plugin
30
+ profile requires its own generated contract, named operations, client facade,
31
+ and conformance tests; `npm run profiles:materialize` generates the first two
32
+ from a reviewed plan. Adapter construction also verifies that the resolved
33
+ `better-auth` installation is exactly `1.6.29`; package-manager overrides do
34
+ not bypass that runtime check. Secret-bearing Better Auth debug logging is
35
+ rejected rather than forwarded to the factory logger.
36
+
37
+ ## Runtime use
38
+
39
+ ```ts
40
+ import { DriverApplicationTransport } from "@riffdb/client";
41
+ import { betterAuth } from "better-auth";
42
+ import { riffdbAdapter } from "@riffdb/better-auth";
43
+
44
+ const driver = await DriverApplicationTransport.connect({
45
+ socketPath,
46
+ identity,
47
+ });
48
+
49
+ export const auth = betterAuth({
50
+ database: riffdbAdapter({
51
+ driver,
52
+ organizationId: "018f5f7e-7b0c-7d9a-8f14-77f42f53c851",
53
+ }),
54
+ advanced: { database: { generateId: "uuid" } },
55
+ emailAndPassword: { enabled: true },
56
+ });
57
+ ```
58
+
59
+ The caller owns the RiffDB driver connection and application-defined
60
+ organization ID. Better Auth continues to own users, sessions, passwords,
61
+ sign-in, OAuth, and reset flows. The package contains the exact RiffDB
62
+ application source, lock, contract bundle, and generated artifacts required to
63
+ deploy the core profile.
64
+
65
+ ## Implemented core surface
66
+
67
+ The core profile supports:
68
+
69
+ - atomic email/password signup and OAuth user/account creation;
70
+ - user, account, session, and verification create/read/update/delete paths;
71
+ - revision-guarded partial updates with bounded stale retries;
72
+ - atomic delete-and-return single-use verification consumption;
73
+ - bounded dependent and cascade deletion;
74
+ - active-session, token-set, provider-account, and verification queries;
75
+ - exact user counts with an optional UUID or bounded email text predicate; and
76
+ - bounded user windows with numeric offsets and compiled email, creation-time,
77
+ or nullable-image ordering.
78
+
79
+ User windows accept at most 100 results and an offset no greater than 4096.
80
+ Email search supports `contains`, `starts_with`, and `ends_with`; every accepted
81
+ filter/order combination maps to a distinct generated RiffQL query. Unsupported
82
+ counts, fields, filters, orderings, joins, transaction graphs, and increments
83
+ fail closed.
84
+
85
+ Token-set session reads use one bounded compiled membership query. Combining a
86
+ token set with an expiry cutoff remains unsupported until that exact compound
87
+ predicate has its own reviewed named query. Verification listing accepts its
88
+ compiled default order, plus `createdAt desc` with `limit: 1`; every other
89
+ verification sort is rejected before a RiffDB request.
90
+
91
+ Secret account credentials, session tokens, and verification values are read
92
+ by named RiffQL queries whose exact returned leaves carry compiler-checked
93
+ `reveals` declarations. The generated role receives authority only for those
94
+ leaves. These reads remain queries, while commands are reserved for writes and
95
+ atomic state transitions. Secret-output queries are excluded from generated
96
+ MCP tools by RiffDB.
97
+
98
+ ## Planning a custom profile
99
+
100
+ `riffdbProfileAdapter` integrates with Better Auth's `createSchema` hook and
101
+ does not require a live database. It resolves the complete Better Auth schema,
102
+ including plugin models and additional fields, into a deterministic bounded
103
+ profile plan:
104
+
105
+ ```ts
106
+ import { betterAuth } from "better-auth";
107
+ import { organization, twoFactor } from "better-auth/plugins";
108
+ import { riffdbProfileAdapter } from "@riffdb/better-auth";
109
+
110
+ export const auth = betterAuth({
111
+ database: riffdbProfileAdapter({
112
+ name: "BetterAuthOrganizationSecurity",
113
+ contractLineage: "BetterAuthOrganizationSecurity",
114
+ applicationRole: "BetterAuthServer",
115
+ output: "riffdb/better-auth.profile.json",
116
+ }),
117
+ advanced: { database: { generateId: "uuid" } },
118
+ user: {
119
+ additionalFields: {
120
+ locale: { type: "string", required: false },
121
+ },
122
+ },
123
+ plugins: [organization({ teams: { enabled: true } }), twoFactor()],
124
+ });
125
+ ```
126
+
127
+ With that generation-only config, run the Better Auth CLI version matching the
128
+ pinned runtime:
129
+
130
+ ```bash
131
+ npx auth@1.6.29 generate --config ./auth.profile.ts --yes
132
+ ```
133
+
134
+ The output records resolved storage names, field types, required/unique/index
135
+ metadata, references, secret classification, default/update behavior, plugin
136
+ IDs, and finite profile bounds. It is an input to reviewed RiffDB profile
137
+ materialization, not a dynamically executable schema or migration. Runtime
138
+ methods on the generation-only adapter always fail.
139
+
140
+ The checked-in
141
+ [`profiles/organization-security.profile.json`](./profiles/organization-security.profile.json)
142
+ is a reproducible organization, teams, two-factor, and custom-user-field
143
+ example. Regenerate or verify it with:
144
+
145
+ ```bash
146
+ npm run profiles:write
147
+ npm run profiles:check
148
+ ```
149
+
150
+ ## Local development
151
+
152
+ ```bash
153
+ npm install
154
+ npm run check
155
+ ```
156
+
157
+ The lock is pinned to `@riffdb/client@0.2.0` and `@riffdb/cli@0.2.0`.
158
+
159
+ `npm run check` performs strict type checking, semantic and upstream tests,
160
+ profile-artifact freshness, a production build, and a package dry run.
161
+
162
+ ## Real loopback conformance
163
+
164
+ Run the real service/driver flow with:
165
+
166
+ ```bash
167
+ riffdb dev --run
168
+ ```
169
+
170
+ The included runner exercises signup, sign-in, password reset and replay
171
+ rejection, user/session/account/verification mutation paths, atomic OAuth
172
+ creation, exact counts, bounded search/offset windows, nullable ordering,
173
+ dependent cleanup, and read-after-commit fencing against the Rust service and
174
+ driver host.
175
+
176
+ See [DESIGN.md](./DESIGN.md) for the method and safety inventory. The adapter
177
+ follows Better Auth's
178
+ [database-adapter guide](https://better-auth.com/docs/guides/create-a-db-adapter)
179
+ and uses its official pinned conformance utilities.
180
+
181
+
182
+ ## RiffDB compatibility CI
183
+
184
+ This adapter owns its RiffDB compatibility checks. Pull requests compile the
185
+ application sources and verify existing locks and generated artifacts against
186
+ the full commit in `.github/riffdb-revision`. Scheduled checks use RiffDB
187
+ `main`; manual dispatch accepts a full commit or `main`. Failures are reported
188
+ here and do not block RiffDB itself. Framework conformance remains separate.
189
+
190
+ To upgrade, update the pin, migrate sources as needed, review the result of
191
+ `riffdb application lock --write`, and verify with `riffdb application check`.
192
+ Commit the pin and migration together in this repository.
@@ -0,0 +1,28 @@
1
+ import { type DriverApplicationTransport } from "@riffdb/client";
2
+ import { type AdapterFactory, type DBAdapterDebugLogOption } from "better-auth/adapters";
3
+ import type { BetterAuthOptions } from "better-auth";
4
+ import { RiffDBBetterAuthCoreClient } from "./generated/client.js";
5
+ export type RiffDBBetterAuthCallErrorCode = "invalid_configuration" | "unsupported_model" | "unsupported_call_shape" | "unsupported_transaction_shape" | "result_bound_exceeded" | "invalid_record_shape" | "declared_outcome";
6
+ export declare class RiffDBBetterAuthCallError extends Error {
7
+ readonly code: RiffDBBetterAuthCallErrorCode;
8
+ readonly operation: string;
9
+ readonly outcome?: string | undefined;
10
+ constructor(code: RiffDBBetterAuthCallErrorCode, operation: string, outcome?: string | undefined);
11
+ }
12
+ export interface RiffDBBetterAuthAdapterConfig {
13
+ readonly driver: DriverApplicationTransport;
14
+ readonly organizationId: string;
15
+ readonly commandAttemptBudget?: number;
16
+ readonly debugLogs?: DBAdapterDebugLogOption;
17
+ }
18
+ interface InternalAdapterConfig {
19
+ readonly client: RiffDBBetterAuthCoreClient;
20
+ readonly organizationId: string;
21
+ readonly debugLogs?: DBAdapterDebugLogOption;
22
+ readonly resetModelForTesting?: (model: string) => number | Promise<number>;
23
+ }
24
+ export declare function assertSupportedBetterAuthInstallation(installedVersion?: string): void;
25
+ export declare function buildRiffDBBetterAuthAdapter(config: InternalAdapterConfig): AdapterFactory<BetterAuthOptions>;
26
+ export declare function riffdbAdapter(config: RiffDBBetterAuthAdapterConfig): AdapterFactory<BetterAuthOptions>;
27
+ export {};
28
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAIA,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,cAAc,EAInB,KAAK,uBAAuB,EAE7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EACL,0BAA0B,EAe3B,MAAM,uBAAuB,CAAC;AAkD/B,MAAM,MAAM,6BAA6B,GACrC,uBAAuB,GACvB,mBAAmB,GACnB,wBAAwB,GACxB,+BAA+B,GAC/B,uBAAuB,GACvB,sBAAsB,GACtB,kBAAkB,CAAC;AAEvB,qBAAa,yBAA0B,SAAQ,KAAK;aAEhC,IAAI,EAAE,6BAA6B;aACnC,SAAS,EAAE,MAAM;aACjB,OAAO,CAAC,EAAE,MAAM;IAHlC,YACkB,IAAI,EAAE,6BAA6B,EACnC,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,MAAM,YAAA,EAQjC;CACF;AAED,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,SAAS,CAAC,EAAE,uBAAuB,CAAC;CAC9C;AAED,UAAU,qBAAqB;IAC7B,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,uBAAuB,CAAC;IAC7C,QAAQ,CAAC,oBAAoB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC7E;AAuBD,wBAAgB,qCAAqC,CACnD,gBAAgB,SAAsC,GACrD,IAAI,CAIN;AAo0CD,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,qBAAqB,GAC5B,cAAc,CAAC,iBAAiB,CAAC,CAuCnC;AAED,wBAAgB,aAAa,CAC3B,MAAM,EAAE,6BAA6B,GACpC,cAAc,CAAC,iBAAiB,CAAC,CAWnC"}