@pithy-sh/auth 0.11.0 → 0.12.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 (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
@@ -0,0 +1,180 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { sha256Base64Url, timingSafeEqual } from "@pithy-sh/core/src/controlPlane/token/digest";
5
+ import { sqliteJson } from "@pithy-sh/core/src/data/codecs";
6
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { z } from "zod";
8
+ import { Verification } from "../data/betterAuth";
9
+ import type { AuthDatabase } from "../data/tables";
10
+
11
+ /**
12
+ * The one-time code that hands a redirect sign-in back to a native app.
13
+ *
14
+ * A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
15
+ * cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
16
+ * this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
17
+ *
18
+ * **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
19
+ * cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
20
+ * read off a URL log, or caught by another app claiming the same scheme, is still worth something.
21
+ *
22
+ * **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
23
+ * nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
24
+ * names the session by id, never by token, so the table holds no credential at all.
25
+ *
26
+ * **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
27
+ * app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
28
+ * code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
29
+ * the code is worth nothing to it. A code is never issued without a challenge.
30
+ *
31
+ * The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
32
+ * one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
33
+ * many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
34
+ * also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
35
+ */
36
+ export const HANDOFF_TTL_SECONDS = 60;
37
+
38
+ /** The most lapsed codes one issue deletes. The next issue takes the rest. */
39
+ export const HANDOFF_SWEEP_LIMIT = 50;
40
+
41
+ /** The identifier prefix that keeps these rows apart from every other verification. */
42
+ const IDENTIFIER_PREFIX = "pithy-handoff:";
43
+
44
+ /** An S256 challenge: the base64url SHA-256 of a verifier, unpadded, which is always 43 characters. */
45
+ const CHALLENGE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
46
+
47
+ /** An RFC 7636 code verifier: 43 to 128 characters, each unreserved (`A-Z a-z 0-9 - . _ ~`). */
48
+ const VERIFIER_SHAPE = /^[A-Za-z0-9\-._~]{43,128}$/;
49
+
50
+ /** Whether a value has the shape RFC 7636 gives a code verifier. */
51
+ export function isHandoffVerifier(value: string): boolean {
52
+ return VERIFIER_SHAPE.test(value);
53
+ }
54
+
55
+ /** Whether a value has the shape of an S256 challenge. */
56
+ export function isHandoffChallenge(value: string): boolean {
57
+ return CHALLENGE_SHAPE.test(value);
58
+ }
59
+
60
+ /** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
61
+ export function handoffChallengeOf(verifier: string): Promise<string> {
62
+ return sha256Base64Url(new TextEncoder().encode(verifier));
63
+ }
64
+
65
+ /** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
66
+ export const StoredHandoff = z
67
+ .object({
68
+ sessionId: z.string().describe("The id of the session the code stands for. Never its token."),
69
+ challenge: z
70
+ .string()
71
+ .regex(CHALLENGE_SHAPE)
72
+ .describe("The S256 challenge the app sent with the sign-in. The trade's verifier must hash to it."),
73
+ })
74
+ .describe("A handoff code's row value: the session and the challenge that binds the code to one app.");
75
+ export type StoredHandoff = z.output<typeof StoredHandoff>;
76
+
77
+ /** The `value` column as a handoff: JSON text in SQLite, validated both ways. */
78
+ const StoredHandoffValue = sqliteJson(StoredHandoff);
79
+
80
+ /** What issuing a code answers: the code itself, which is never stored, and when it lapses. */
81
+ export interface IssuedHandoff {
82
+ readonly code: string;
83
+ readonly expiresAt: Date;
84
+ }
85
+
86
+ /**
87
+ * What a redemption answers. `unknown` covers a code already spent and one never issued alike. The reasons are
88
+ * for the audit trail; the caller answers every refusal the same way.
89
+ */
90
+ export type HandoffRedemption =
91
+ | { readonly ok: true; readonly sessionId: string }
92
+ | { readonly ok: false; readonly reason: HandoffRefusal };
93
+
94
+ /** Why a code was refused. `malformed` is a verifier outside RFC 7636's shape, which no challenge was made from. */
95
+ export type HandoffRefusal = "expired" | "unknown" | "mismatch" | "malformed";
96
+
97
+ async function identifierOf(code: string): Promise<string> {
98
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code));
99
+ const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
100
+ return `${IDENTIFIER_PREFIX}${hex}`;
101
+ }
102
+
103
+ function randomCode(): string {
104
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
105
+ let binary = "";
106
+ for (const byte of bytes) binary += String.fromCharCode(byte);
107
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
108
+ }
109
+
110
+ /** Delete up to {@link HANDOFF_SWEEP_LIMIT} codes that lapsed by `now`. */
111
+ async function sweepLapsed(db: AuthDatabase, now: Date): Promise<void> {
112
+ await db
113
+ .deleteFrom("pithyAuthVerifications")
114
+ .where("id", "in", (lapsed) =>
115
+ lapsed
116
+ .selectFrom("pithyAuthVerifications")
117
+ .select("id")
118
+ .where("identifier", "like", `${IDENTIFIER_PREFIX}%`)
119
+ .where("expiresAt", "<=", Verification.shape.expiresAt.encode(now))
120
+ .limit(HANDOFF_SWEEP_LIMIT),
121
+ )
122
+ .execute();
123
+ }
124
+
125
+ /**
126
+ * Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
127
+ * other shape throws: an unbound code is never written.
128
+ */
129
+ export async function issueHandoff(
130
+ db: AuthDatabase,
131
+ input: { sessionId: string; challenge: string; now: Date },
132
+ ): Promise<IssuedHandoff> {
133
+ if (!isHandoffChallenge(input.challenge)) {
134
+ throw new InternalError({ detail: "a handoff code was asked for without an S256 challenge to bind it to" });
135
+ }
136
+ await sweepLapsed(db, input.now);
137
+ const code = randomCode();
138
+ const expiresAt = new Date(input.now.getTime() + HANDOFF_TTL_SECONDS * 1000);
139
+ await db
140
+ .insertInto("pithyAuthVerifications")
141
+ .values(
142
+ Verification.encode({
143
+ id: crypto.randomUUID(),
144
+ identifier: await identifierOf(code),
145
+ value: z.string().parse(StoredHandoffValue.encode({ sessionId: input.sessionId, challenge: input.challenge })),
146
+ expiresAt,
147
+ createdAt: input.now,
148
+ updatedAt: input.now,
149
+ }),
150
+ )
151
+ .execute();
152
+ return { code, expiresAt };
153
+ }
154
+
155
+ /**
156
+ * Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
157
+ * presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
158
+ */
159
+ export async function redeemHandoff(
160
+ db: AuthDatabase,
161
+ input: { code: string; verifier: string },
162
+ now: Date,
163
+ ): Promise<HandoffRedemption> {
164
+ const row = await db
165
+ .deleteFrom("pithyAuthVerifications")
166
+ .where("identifier", "=", await identifierOf(input.code))
167
+ .returning(["value", "expiresAt"])
168
+ .executeTakeFirst();
169
+ if (!row) return { ok: false, reason: "unknown" };
170
+ const parsed = StoredHandoffValue.safeParse(row.value);
171
+ if (!parsed.success) return { ok: false, reason: "unknown" };
172
+ const stored = parsed.data;
173
+ const expiresAt = Verification.shape.expiresAt.parse(row.expiresAt);
174
+ if (expiresAt.getTime() <= now.getTime()) return { ok: false, reason: "expired" };
175
+ if (!isHandoffVerifier(input.verifier)) return { ok: false, reason: "malformed" };
176
+ if (!timingSafeEqual(await handoffChallengeOf(input.verifier), stored.challenge)) {
177
+ return { ok: false, reason: "mismatch" };
178
+ }
179
+ return { ok: true, sessionId: stored.sessionId };
180
+ }
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.11.0";
16
+ export const PACKAGE_VERSION = "0.12.1";