@pithy-sh/auth 0.1.2 → 0.1.4

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 (122) hide show
  1. package/dist/admin/users.d.ts +157 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +207 -0
  4. package/dist/audit/actions.d.ts +68 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +68 -0
  7. package/dist/audit/emit.d.ts +103 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +172 -0
  10. package/dist/capability.d.ts +62 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +171 -0
  13. package/dist/client/api.d.ts +301 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +387 -0
  16. package/dist/client/projection.d.ts +53 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +2 -0
  19. package/dist/data/betterAuth.d.ts +77 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +94 -0
  22. package/dist/data/device.d.ts +38 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +35 -0
  25. package/dist/data/kitFields.d.ts +80 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +79 -0
  28. package/dist/data/rotatedToken.d.ts +22 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +24 -0
  31. package/dist/data/tables.d.ts +106 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +32 -0
  34. package/dist/device/registry.d.ts +56 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +87 -0
  37. package/dist/email/send.d.ts +40 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +50 -0
  40. package/dist/http/adminRoutes.d.ts +11 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +276 -0
  43. package/dist/http/baseUrl.d.ts +43 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +98 -0
  46. package/dist/http/csrf.d.ts +20 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +83 -0
  49. package/dist/http/devLoginRoute.d.ts +44 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +114 -0
  52. package/dist/http/errors.d.ts +26 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +69 -0
  55. package/dist/http/guards.d.ts +105 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +150 -0
  58. package/dist/http/middleware.d.ts +19 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +49 -0
  61. package/dist/http/rateLimit.d.ts +19 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +33 -0
  64. package/dist/http/resolve.d.ts +11 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +94 -0
  67. package/dist/http/responses.d.ts +154 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +123 -0
  70. package/dist/http/routes.d.ts +36 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +270 -0
  73. package/dist/http/schemas.d.ts +68 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +61 -0
  76. package/dist/http/views.d.ts +55 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +88 -0
  79. package/dist/i18n/errorCopy.d.ts +26 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +33 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +35 -0
  84. package/dist/i18n/errorCopy.js +93 -0
  85. package/dist/index.d.ts +16 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +10 -0
  88. package/dist/instance/auth.d.ts +1124 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +178 -0
  91. package/dist/instance/plugins.d.ts +89 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +118 -0
  94. package/dist/instance/providers.d.ts +119 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +113 -0
  97. package/dist/instance/secrets.d.ts +165 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +171 -0
  100. package/dist/migrations/0001_init.d.ts +35 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +79 -0
  103. package/dist/migrations/pluginTables.d.ts +128 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +235 -0
  106. package/dist/seeds/devSession.d.ts +126 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +213 -0
  109. package/dist/seeds/example.d.ts +14 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +32 -0
  112. package/dist/test-utils/liveApp.d.ts +229 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +242 -0
  115. package/dist/token/rotation.d.ts +58 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +70 -0
  118. package/dist/version.generated.d.ts +7 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +9 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * `pithy_auth_devices` — the device registry, a Pithy-specific table with no Better-Auth equivalent.
6
+ *
7
+ * One row per user-device, keyed on a client-generated stable id so the same physical device maps to
8
+ * one row across re-logins. Sessions link back via `pithy_auth_sessions.device_id`. This table is
9
+ * written by Pithy code (the `session.create` hook and the device routes) through our shared Kysely,
10
+ * so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
11
+ */
12
+ /** The platform a device runs. `web` covers any browser; mobile carries richer metadata. */
13
+ export declare const DevicePlatform: z.ZodEnum<{
14
+ android: "android";
15
+ ios: "ios";
16
+ web: "web";
17
+ }>;
18
+ export type DevicePlatform = z.output<typeof DevicePlatform>;
19
+ /** One registered device. */
20
+ export declare const Device: z.ZodObject<{
21
+ id: z.ZodString;
22
+ userId: z.ZodString;
23
+ platform: z.ZodEnum<{
24
+ android: "android";
25
+ ios: "ios";
26
+ web: "web";
27
+ }>;
28
+ name: z.ZodNullable<z.ZodString>;
29
+ model: z.ZodNullable<z.ZodString>;
30
+ osVersion: z.ZodNullable<z.ZodString>;
31
+ appVersion: z.ZodNullable<z.ZodString>;
32
+ pushToken: z.ZodNullable<z.ZodString>;
33
+ lastIp: z.ZodNullable<z.ZodString>;
34
+ lastSeenAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
35
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
36
+ }, z.core.$strip>;
37
+ export type Device = z.output<typeof Device>;
38
+ //# sourceMappingURL=device.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device.d.ts","sourceRoot":"","sources":["../../src/data/device.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;GAOG;AAEH,4FAA4F;AAC5F,eAAO,MAAM,cAAc;;;;EAEoC,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,6BAA6B;AAC7B,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;iBAiCkG,CAAC;AACtH,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,MAAM,CAAC,CAAC"}
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ //#region src/data/device.ts
6
+ /**
7
+ * `pithy_auth_devices` — the device registry, a Pithy-specific table with no Better-Auth equivalent.
8
+ *
9
+ * One row per user-device, keyed on a client-generated stable id so the same physical device maps to
10
+ * one row across re-logins. Sessions link back via `pithy_auth_sessions.device_id`. This table is
11
+ * written by Pithy code (the `session.create` hook and the device routes) through our shared Kysely,
12
+ * so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
13
+ */
14
+ /** The platform a device runs. `web` covers any browser; mobile carries richer metadata. */
15
+ const DevicePlatform = z.enum([
16
+ "ios",
17
+ "android",
18
+ "web"
19
+ ]).describe("The device platform: `ios`, `android`, or `web`.");
20
+ /** One registered device. */
21
+ const Device = z.object({
22
+ id: z.string().min(1).max(128).describe("Primary key. A client-generated stable id (UUID) so one physical device maps to one row across re-logins. Bounded because it arrives verbatim from the `x-pithy-device-id` header and becomes both a stored key and the tiebreak inside the device listing's keyset cursor — an unbounded id is an unbounded write, and it would also let one device push that cursor past the length the same route accepts on the way back in, making the registry unpageable past that row. Same reasoning as the control-plane `jti` bound."),
23
+ userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE. Indexed."),
24
+ platform: DevicePlatform.describe("The device platform, captured from login metadata."),
25
+ name: z.string().nullable().describe("A human label for the device (OS device name), shown in device-management UI. Nullable."),
26
+ model: z.string().nullable().describe("The hardware model, for device-management UI and support. Nullable."),
27
+ osVersion: z.string().nullable().describe("The device OS version at last sign-in. Nullable."),
28
+ appVersion: z.string().nullable().describe("The client app version at last sign-in. Nullable."),
29
+ pushToken: z.string().nullable().describe("The APNs/FCM push token, stored for the future push capability and updatable. Nullable."),
30
+ lastIp: z.string().nullable().describe("The client IP at the most recent sign-in, for `new sign-in from…` security signals. Nullable."),
31
+ lastSeenAt: SQLiteDate.describe("When this device was last seen (most recent sign-in). Ms-epoch in SQLite; a `Date` in app code."),
32
+ createdAt: SQLiteDate.describe("When this device was first registered. Ms-epoch in SQLite; a `Date` in app code.")
33
+ }).describe("A registered device in `pithy_auth_devices` — per-device sessions, security signals, and push routing.");
34
+ //#endregion
35
+ export { Device, DevicePlatform };
@@ -0,0 +1,80 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The columns Pithy adds to Better Auth's own tables, declared **once**.
5
+ *
6
+ * Better Auth owns every read and write to `pithy_auth_users` and `pithy_auth_sessions` through its
7
+ * Kysely adapter, and it writes only the fields its options declare. So a column that exists in the
8
+ * migration and in the `User` Zod object and *not* here is null forever and absent from every user
9
+ * object the instance returns — a migration and a schema field that silently did nothing.
10
+ *
11
+ * ## Why one module rather than two agreeing declarations
12
+ *
13
+ * These have to appear in two places: `makeAuth`'s live options (`../instance/auth.ts`) and the
14
+ * schema baseline `pluginSchemaDelta` subtracts each adopter plugin's schema from
15
+ * (`../migrations/pluginTables.ts`). Both were written out by hand, with a comment in each saying it
16
+ * "must match" the other and a test claiming to hold them together. The test did not: it compared the
17
+ * baseline against the `User` schema and never imported `makeAuth` at all, so reverting the live
18
+ * declaration left the whole suite green while Better Auth silently stopped writing the column (#441).
19
+ *
20
+ * `docs/CONVENTIONS.md` is explicit that removing an invariant beats watching it. There is one object
21
+ * now, imported by both, and the two cannot disagree because there is no second thing to disagree
22
+ * with. That is also why the consequence is worth restating rather than diluting: leave a kit column
23
+ * out of the baseline and `pluginSchemaDelta` reports it as something an adopter's plugin brought, so
24
+ * a plugin that also declares a user `locale` emits `ALTER TABLE … ADD COLUMN locale` against a table
25
+ * that already has one — a duplicate-column failure part-way through a migration D1 cannot roll back,
26
+ * because it has no transactional DDL.
27
+ */
28
+ /**
29
+ * The extra `pithy_auth_users` columns.
30
+ *
31
+ * **`locale` is `input: true`, deliberately, and that is the whole point of the column.** Every other
32
+ * extra field the kit declares is server-set — {@link KIT_SESSION_FIELDS} is `input: false` because a
33
+ * client that could name its own device or token family could name somebody else's. A locale is the
34
+ * opposite: it is the reader's own preference, and the flow it exists for is a signed-in reader
35
+ * switching language and having the choice follow them to their next device. Refusing client input
36
+ * would leave an admin route as the only way to store a preference, which is not a thing a reader has.
37
+ *
38
+ * **What makes that safe is the validator, not the type.** `type: "string"` alone would let a caller
39
+ * write any string into a column every read passes through `User.parse` — so one `updateUser` with a
40
+ * megabyte of junk would poison that row, and the admin listing that reads a page of rows would then
41
+ * throw for every operator rather than only for the author. Better Auth runs `validator.input` on the
42
+ * supplied value and answers 400 on a failure (`parseInputData`), so the same schema that guards the
43
+ * read guards the write, one hop earlier.
44
+ *
45
+ * **And it is `Locale.nullable()`, not `Locale`.** The column is nullable, the `User` field is
46
+ * nullable, `AdminUserView` is nullable, and every one of those says the same thing: null is "this
47
+ * reader has not chosen", which is what makes the server fall back to `Accept-Language`. A validator
48
+ * that accepted a tag but refused `null` would let a reader pick a language and never take it back —
49
+ * `updateUser({ locale: null })` answering 400 for the one state the schema calls ordinary.
50
+ */
51
+ export declare const KIT_USER_FIELDS: {
52
+ readonly locale: {
53
+ readonly type: "string";
54
+ readonly required: false;
55
+ readonly input: true;
56
+ readonly validator: {
57
+ readonly input: import("zod").ZodNullable<import("zod").ZodString>;
58
+ };
59
+ };
60
+ };
61
+ /**
62
+ * The extra `pithy_auth_sessions` columns — the bound device, and the refresh-token family carried
63
+ * across rotations.
64
+ *
65
+ * `input: false` on both: these are server-set facts about a session, and a client able to name its own
66
+ * device id or token family could name somebody else's.
67
+ */
68
+ export declare const KIT_SESSION_FIELDS: {
69
+ readonly deviceId: {
70
+ readonly type: "string";
71
+ readonly required: false;
72
+ readonly input: false;
73
+ };
74
+ readonly familyId: {
75
+ readonly type: "string";
76
+ readonly required: false;
77
+ readonly input: false;
78
+ };
79
+ };
80
+ //# sourceMappingURL=kitFields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kitFields.d.ts","sourceRoot":"","sources":["../../src/data/kitFields.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,eAAe;aAC1B,MAAM;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;iBAAQ,SAAS;qBAAI,KAAK;;;CAClE,CAAC;AAEX;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB;aAC7B,QAAQ;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;aAClD,QAAQ;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;CAC1C,CAAC"}
@@ -0,0 +1,79 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Locale } from "@pithy-sh/core/src/i18n/locale";
4
+ //#region src/data/kitFields.ts
5
+ /**
6
+ * The columns Pithy adds to Better Auth's own tables, declared **once**.
7
+ *
8
+ * Better Auth owns every read and write to `pithy_auth_users` and `pithy_auth_sessions` through its
9
+ * Kysely adapter, and it writes only the fields its options declare. So a column that exists in the
10
+ * migration and in the `User` Zod object and *not* here is null forever and absent from every user
11
+ * object the instance returns — a migration and a schema field that silently did nothing.
12
+ *
13
+ * ## Why one module rather than two agreeing declarations
14
+ *
15
+ * These have to appear in two places: `makeAuth`'s live options (`../instance/auth.ts`) and the
16
+ * schema baseline `pluginSchemaDelta` subtracts each adopter plugin's schema from
17
+ * (`../migrations/pluginTables.ts`). Both were written out by hand, with a comment in each saying it
18
+ * "must match" the other and a test claiming to hold them together. The test did not: it compared the
19
+ * baseline against the `User` schema and never imported `makeAuth` at all, so reverting the live
20
+ * declaration left the whole suite green while Better Auth silently stopped writing the column (#441).
21
+ *
22
+ * `docs/CONVENTIONS.md` is explicit that removing an invariant beats watching it. There is one object
23
+ * now, imported by both, and the two cannot disagree because there is no second thing to disagree
24
+ * with. That is also why the consequence is worth restating rather than diluting: leave a kit column
25
+ * out of the baseline and `pluginSchemaDelta` reports it as something an adopter's plugin brought, so
26
+ * a plugin that also declares a user `locale` emits `ALTER TABLE … ADD COLUMN locale` against a table
27
+ * that already has one — a duplicate-column failure part-way through a migration D1 cannot roll back,
28
+ * because it has no transactional DDL.
29
+ */
30
+ /**
31
+ * The extra `pithy_auth_users` columns.
32
+ *
33
+ * **`locale` is `input: true`, deliberately, and that is the whole point of the column.** Every other
34
+ * extra field the kit declares is server-set — {@link KIT_SESSION_FIELDS} is `input: false` because a
35
+ * client that could name its own device or token family could name somebody else's. A locale is the
36
+ * opposite: it is the reader's own preference, and the flow it exists for is a signed-in reader
37
+ * switching language and having the choice follow them to their next device. Refusing client input
38
+ * would leave an admin route as the only way to store a preference, which is not a thing a reader has.
39
+ *
40
+ * **What makes that safe is the validator, not the type.** `type: "string"` alone would let a caller
41
+ * write any string into a column every read passes through `User.parse` — so one `updateUser` with a
42
+ * megabyte of junk would poison that row, and the admin listing that reads a page of rows would then
43
+ * throw for every operator rather than only for the author. Better Auth runs `validator.input` on the
44
+ * supplied value and answers 400 on a failure (`parseInputData`), so the same schema that guards the
45
+ * read guards the write, one hop earlier.
46
+ *
47
+ * **And it is `Locale.nullable()`, not `Locale`.** The column is nullable, the `User` field is
48
+ * nullable, `AdminUserView` is nullable, and every one of those says the same thing: null is "this
49
+ * reader has not chosen", which is what makes the server fall back to `Accept-Language`. A validator
50
+ * that accepted a tag but refused `null` would let a reader pick a language and never take it back —
51
+ * `updateUser({ locale: null })` answering 400 for the one state the schema calls ordinary.
52
+ */
53
+ const KIT_USER_FIELDS = { locale: {
54
+ type: "string",
55
+ required: false,
56
+ input: true,
57
+ validator: { input: Locale.nullable() }
58
+ } };
59
+ /**
60
+ * The extra `pithy_auth_sessions` columns — the bound device, and the refresh-token family carried
61
+ * across rotations.
62
+ *
63
+ * `input: false` on both: these are server-set facts about a session, and a client able to name its own
64
+ * device id or token family could name somebody else's.
65
+ */
66
+ const KIT_SESSION_FIELDS = {
67
+ deviceId: {
68
+ type: "string",
69
+ required: false,
70
+ input: false
71
+ },
72
+ familyId: {
73
+ type: "string",
74
+ required: false,
75
+ input: false
76
+ }
77
+ };
78
+ //#endregion
79
+ export { KIT_SESSION_FIELDS, KIT_USER_FIELDS };
@@ -0,0 +1,22 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * `pithy_auth_rotated_tokens` — the reuse-detection ledger, a Pithy-specific table with no
6
+ * Better-Auth equivalent.
7
+ *
8
+ * One row per refresh token that has been consumed by a rotation. On `/auth/token/rotate` the
9
+ * presented session token is deleted and recorded here; presenting it again (after it no longer
10
+ * resolves to a live session) is a replayed refresh credential — the canonical compromise signal for
11
+ * rotated refresh tokens (OAuth refresh rotation, RFC 6819 §5.2.2.3). The row carries the `familyId`
12
+ * so the whole token family can be revoked on reuse. Written by Pithy code through our shared Kysely,
13
+ * so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
14
+ */
15
+ export declare const RotatedToken: z.ZodObject<{
16
+ token: z.ZodString;
17
+ familyId: z.ZodString;
18
+ userId: z.ZodString;
19
+ rotatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
20
+ }, z.core.$strip>;
21
+ export type RotatedToken = z.output<typeof RotatedToken>;
22
+ //# sourceMappingURL=rotatedToken.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rotatedToken.d.ts","sourceRoot":"","sources":["../../src/data/rotatedToken.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,YAAY;;;;;iBAqBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC"}
@@ -0,0 +1,24 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ //#region src/data/rotatedToken.ts
6
+ /**
7
+ * `pithy_auth_rotated_tokens` — the reuse-detection ledger, a Pithy-specific table with no
8
+ * Better-Auth equivalent.
9
+ *
10
+ * One row per refresh token that has been consumed by a rotation. On `/auth/token/rotate` the
11
+ * presented session token is deleted and recorded here; presenting it again (after it no longer
12
+ * resolves to a live session) is a replayed refresh credential — the canonical compromise signal for
13
+ * rotated refresh tokens (OAuth refresh rotation, RFC 6819 §5.2.2.3). The row carries the `familyId`
14
+ * so the whole token family can be revoked on reuse. Written by Pithy code through our shared Kysely,
15
+ * so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
16
+ */
17
+ const RotatedToken = z.object({
18
+ token: z.string().describe("Primary key. The consumed session token, recorded when a rotation revoked it. Presenting it again is reuse."),
19
+ familyId: z.string().describe("The refresh-token family this token belonged to. The unit revoked when reuse is detected — every session sharing it is signed out. Indexed."),
20
+ userId: z.string().describe("The owning user's id, for attributing the reuse audit event to the compromised account."),
21
+ rotatedAt: SQLiteDate.describe("When the token was consumed by a rotation. Ms-epoch in SQLite; a `Date` in app code. Drives retention pruning.")
22
+ }).describe("A consumed refresh token in `pithy_auth_rotated_tokens` — the ledger that powers refresh-token reuse detection and family revocation.");
23
+ //#endregion
24
+ export { RotatedToken };
@@ -0,0 +1,106 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
5
+ import type { Kysely } from "kysely";
6
+ /**
7
+ * The auth capability's table map: camelCase keys, so `CamelCasePlugin` emits the snake_case
8
+ * `pithy_auth_*` SQL. One source of truth shared by the capability wiring, the Better-Auth instance
9
+ * (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
10
+ *
11
+ * The first six tables are Better-Auth-managed; `pithyAuthDevices` and `pithyAuthRotatedTokens` are
12
+ * ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
13
+ * own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
14
+ */
15
+ export declare const authTables: {
16
+ pithyAuthUsers: import("zod").ZodObject<{
17
+ id: import("zod").ZodString;
18
+ name: import("zod").ZodString;
19
+ email: import("zod").ZodString;
20
+ emailVerified: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<0>, import("zod").ZodLiteral<1>, import("zod").ZodBoolean, import("zod").ZodString]>, import("zod").ZodBoolean>;
21
+ image: import("zod").ZodNullable<import("zod").ZodString>;
22
+ locale: import("zod").ZodNullable<import("zod").ZodString>;
23
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
24
+ updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
25
+ }, import("zod/v4/core").$strip>;
26
+ pithyAuthSessions: import("zod").ZodObject<{
27
+ id: import("zod").ZodString;
28
+ expiresAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
29
+ token: import("zod").ZodString;
30
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
31
+ updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
32
+ ipAddress: import("zod").ZodNullable<import("zod").ZodString>;
33
+ userAgent: import("zod").ZodNullable<import("zod").ZodString>;
34
+ userId: import("zod").ZodString;
35
+ deviceId: import("zod").ZodNullable<import("zod").ZodString>;
36
+ familyId: import("zod").ZodNullable<import("zod").ZodString>;
37
+ }, import("zod/v4/core").$strip>;
38
+ pithyAuthAccounts: import("zod").ZodObject<{
39
+ id: import("zod").ZodString;
40
+ issuer: import("zod").ZodString;
41
+ accountId: import("zod").ZodString;
42
+ providerId: import("zod").ZodString;
43
+ userId: import("zod").ZodString;
44
+ accessToken: import("zod").ZodNullable<import("zod").ZodString>;
45
+ refreshToken: import("zod").ZodNullable<import("zod").ZodString>;
46
+ idToken: import("zod").ZodNullable<import("zod").ZodString>;
47
+ accessTokenExpiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
48
+ refreshTokenExpiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
49
+ scope: import("zod").ZodNullable<import("zod").ZodString>;
50
+ password: import("zod").ZodNullable<import("zod").ZodString>;
51
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
52
+ updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
53
+ }, import("zod/v4/core").$strip>;
54
+ pithyAuthVerifications: import("zod").ZodObject<{
55
+ id: import("zod").ZodString;
56
+ identifier: import("zod").ZodString;
57
+ value: import("zod").ZodString;
58
+ expiresAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
59
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
60
+ updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
61
+ }, import("zod/v4/core").$strip>;
62
+ pithyAuthJwks: import("zod").ZodObject<{
63
+ id: import("zod").ZodString;
64
+ publicKey: import("zod").ZodString;
65
+ privateKey: import("zod").ZodString;
66
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
67
+ expiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
68
+ alg: import("zod").ZodNullable<import("zod").ZodString>;
69
+ crv: import("zod").ZodNullable<import("zod").ZodString>;
70
+ }, import("zod/v4/core").$strip>;
71
+ pithyAuthRateLimit: import("zod").ZodObject<{
72
+ id: import("zod").ZodString;
73
+ key: import("zod").ZodString;
74
+ count: import("zod").ZodNumber;
75
+ lastRequest: import("zod").ZodNumber;
76
+ }, import("zod/v4/core").$strip>;
77
+ pithyAuthDevices: import("zod").ZodObject<{
78
+ id: import("zod").ZodString;
79
+ userId: import("zod").ZodString;
80
+ platform: import("zod").ZodEnum<{
81
+ android: "android";
82
+ ios: "ios";
83
+ web: "web";
84
+ }>;
85
+ name: import("zod").ZodNullable<import("zod").ZodString>;
86
+ model: import("zod").ZodNullable<import("zod").ZodString>;
87
+ osVersion: import("zod").ZodNullable<import("zod").ZodString>;
88
+ appVersion: import("zod").ZodNullable<import("zod").ZodString>;
89
+ pushToken: import("zod").ZodNullable<import("zod").ZodString>;
90
+ lastIp: import("zod").ZodNullable<import("zod").ZodString>;
91
+ lastSeenAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
92
+ createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
93
+ }, import("zod/v4/core").$strip>;
94
+ pithyAuthRotatedTokens: import("zod").ZodObject<{
95
+ token: import("zod").ZodString;
96
+ familyId: import("zod").ZodString;
97
+ userId: import("zod").ZodString;
98
+ rotatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
99
+ }, import("zod/v4/core").$strip>;
100
+ };
101
+ export type AuthTables = typeof authTables;
102
+ /** The typed Kysely view over the auth tables — shared by the Better-Auth adapter and the device registry. */
103
+ export type AuthDatabase = Kysely<DatabaseSchema<AuthTables>>;
104
+ /** Build the auth Kysely over a D1 binding. Carries `CamelCasePlugin`, so query code stays camelCase. */
105
+ export declare function authDatabase(d1: D1Database): AuthDatabase;
106
+ //# sourceMappingURL=tables.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAKrC;;;;;;;;GAQG;AACH,eAAO,MAAM,UAAU;IACrB,cAAc;;;;;;;;;;IACd,iBAAiB;;;;;;;;;;;;IACjB,iBAAiB;;;;;;;;;;;;;;;;IACjB,sBAAsB;;;;;;;;IACtB,aAAa;;;;;;;;;IACb,kBAAkB;;;;;;IAClB,gBAAgB;;;;;;;;;;;;;;;;;IAChB,sBAAsB;;;;;;CACvB,CAAC;AACF,MAAM,MAAM,UAAU,GAAG,OAAO,UAAU,CAAC;AAE3C,8GAA8G;AAC9G,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;AAE9D,yGAAyG;AACzG,wBAAgB,YAAY,CAAC,EAAE,EAAE,UAAU,GAAG,YAAY,CAEzD"}
@@ -0,0 +1,32 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth.js";
4
+ import { Device } from "./device.js";
5
+ import { RotatedToken } from "./rotatedToken.js";
6
+ import { createDatabase } from "@pithy-sh/core/src/data/db";
7
+ //#region src/data/tables.ts
8
+ /**
9
+ * The auth capability's table map: camelCase keys, so `CamelCasePlugin` emits the snake_case
10
+ * `pithy_auth_*` SQL. One source of truth shared by the capability wiring, the Better-Auth instance
11
+ * (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
12
+ *
13
+ * The first six tables are Better-Auth-managed; `pithyAuthDevices` and `pithyAuthRotatedTokens` are
14
+ * ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
15
+ * own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
16
+ */
17
+ const authTables = {
18
+ pithyAuthUsers: User,
19
+ pithyAuthSessions: Session,
20
+ pithyAuthAccounts: Account,
21
+ pithyAuthVerifications: Verification,
22
+ pithyAuthJwks: Jwks,
23
+ pithyAuthRateLimit: RateLimit,
24
+ pithyAuthDevices: Device,
25
+ pithyAuthRotatedTokens: RotatedToken
26
+ };
27
+ /** Build the auth Kysely over a D1 binding. Carries `CamelCasePlugin`, so query code stays camelCase. */
28
+ function authDatabase(d1) {
29
+ return createDatabase(d1, authTables);
30
+ }
31
+ //#endregion
32
+ export { authDatabase, authTables };
@@ -0,0 +1,56 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Device, DevicePlatform } from "../data/device";
4
+ import type { AuthDatabase } from "../data/tables";
5
+ /**
6
+ * The device registry: parse optional device metadata off a sign-in request, upsert the
7
+ * `pithy_auth_devices` row, and resolve a device's sessions for revocation. All writes go through our
8
+ * shared Kysely + codecs (ms-epoch dates) — distinct from the Better-Auth-managed tables.
9
+ */
10
+ /** Request headers a client may send at sign-in to register/identify its device. */
11
+ export declare const DEVICE_HEADERS: {
12
+ readonly id: "x-pithy-device-id";
13
+ readonly platform: "x-pithy-platform";
14
+ readonly name: "x-pithy-device-name";
15
+ readonly model: "x-pithy-device-model";
16
+ readonly osVersion: "x-pithy-os-version";
17
+ readonly appVersion: "x-pithy-app-version";
18
+ readonly pushToken: "x-pithy-push-token";
19
+ };
20
+ /**
21
+ * Device metadata captured at sign-in. `id` is required; everything else is best-effort. `platform` is
22
+ * `null` when the header was absent — distinct from a supplied value — so a sparse re-login never
23
+ * overwrites a known platform with a default.
24
+ */
25
+ export interface DeviceMeta {
26
+ id: string;
27
+ platform: DevicePlatform | null;
28
+ name: string | null;
29
+ model: string | null;
30
+ osVersion: string | null;
31
+ appVersion: string | null;
32
+ pushToken: string | null;
33
+ }
34
+ /**
35
+ * Parse device metadata from request headers. Returns `undefined` when no `x-pithy-device-id` is
36
+ * present — a device-less login (a plain web session). `platform` is `null` when its header is absent
37
+ * or unrecognized; the default `web` is applied only on first registration, never on a sparse update.
38
+ */
39
+ export declare function parseDeviceMeta(headers: Headers): DeviceMeta | undefined;
40
+ /**
41
+ * Register-or-update a device for a user. Idempotent on the composite `(userId, id)` key: a re-login
42
+ * from the same device refreshes `lastSeenAt`/`lastIp` and any newly-supplied metadata, but never
43
+ * overwrites existing metadata with a sparse login and never resets `createdAt`.
44
+ */
45
+ export declare function registerDevice(db: AuthDatabase, meta: DeviceMeta, context: {
46
+ userId: string;
47
+ lastIp: string | null;
48
+ now: Date;
49
+ }): Promise<void>;
50
+ /** List a user's registered devices, most-recently-seen first. */
51
+ export declare function listDevices(db: AuthDatabase, userId: string): Promise<Device[]>;
52
+ /** Resolve the session tokens bound to one of a user's devices — the set a device-revoke must sign out. */
53
+ export declare function deviceSessionTokens(db: AuthDatabase, userId: string, deviceId: string): Promise<string[]>;
54
+ /** Delete a user's device row (after its sessions are revoked). Returns true if a row was removed. */
55
+ export declare function deleteDevice(db: AuthDatabase, userId: string, deviceId: string): Promise<boolean>;
56
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/device/registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;GAIG;AAEH,oFAAoF;AACpF,eAAO,MAAM,cAAc;aACzB,EAAE,EAAE,mBAAmB;aACvB,QAAQ,EAAE,kBAAkB;aAC5B,IAAI,EAAE,qBAAqB;aAC3B,KAAK,EAAE,sBAAsB;aAC7B,SAAS,EAAE,oBAAoB;aAC/B,UAAU,EAAE,qBAAqB;aACjC,SAAS,EAAE,oBAAoB;CACvB,CAAC;AAEX;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,cAAc,GAAG,IAAI,CAAC;IAChC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAOD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,UAAU,GAAG,SAAS,CAaxE;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,YAAY,EAChB,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,EAAE,IAAI,CAAA;CAAE,GAC5D,OAAO,CAAC,IAAI,CAAC,CAkCf;AAED,kEAAkE;AAClE,wBAAsB,WAAW,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAQrF;AAED,2GAA2G;AAC3G,wBAAsB,mBAAmB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAQ/G;AAED,sGAAsG;AACtG,wBAAsB,YAAY,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOvG"}
@@ -0,0 +1,87 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Device, DevicePlatform } from "../data/device.js";
4
+ //#region src/device/registry.ts
5
+ /**
6
+ * The device registry: parse optional device metadata off a sign-in request, upsert the
7
+ * `pithy_auth_devices` row, and resolve a device's sessions for revocation. All writes go through our
8
+ * shared Kysely + codecs (ms-epoch dates) — distinct from the Better-Auth-managed tables.
9
+ */
10
+ /** Request headers a client may send at sign-in to register/identify its device. */
11
+ const DEVICE_HEADERS = {
12
+ id: "x-pithy-device-id",
13
+ platform: "x-pithy-platform",
14
+ name: "x-pithy-device-name",
15
+ model: "x-pithy-device-model",
16
+ osVersion: "x-pithy-os-version",
17
+ appVersion: "x-pithy-app-version",
18
+ pushToken: "x-pithy-push-token"
19
+ };
20
+ function header(headers, name) {
21
+ const value = headers.get(name)?.trim();
22
+ return value ? value : null;
23
+ }
24
+ /**
25
+ * Parse device metadata from request headers. Returns `undefined` when no `x-pithy-device-id` is
26
+ * present — a device-less login (a plain web session). `platform` is `null` when its header is absent
27
+ * or unrecognized; the default `web` is applied only on first registration, never on a sparse update.
28
+ */
29
+ function parseDeviceMeta(headers) {
30
+ const id = header(headers, DEVICE_HEADERS.id);
31
+ if (!id) return void 0;
32
+ const platform = DevicePlatform.safeParse(header(headers, DEVICE_HEADERS.platform));
33
+ return {
34
+ id,
35
+ platform: platform.success ? platform.data : null,
36
+ name: header(headers, DEVICE_HEADERS.name),
37
+ model: header(headers, DEVICE_HEADERS.model),
38
+ osVersion: header(headers, DEVICE_HEADERS.osVersion),
39
+ appVersion: header(headers, DEVICE_HEADERS.appVersion),
40
+ pushToken: header(headers, DEVICE_HEADERS.pushToken)
41
+ };
42
+ }
43
+ /**
44
+ * Register-or-update a device for a user. Idempotent on the composite `(userId, id)` key: a re-login
45
+ * from the same device refreshes `lastSeenAt`/`lastIp` and any newly-supplied metadata, but never
46
+ * overwrites existing metadata with a sparse login and never resets `createdAt`.
47
+ */
48
+ async function registerDevice(db, meta, context) {
49
+ const record = Device.encode({
50
+ id: meta.id,
51
+ userId: context.userId,
52
+ platform: meta.platform ?? "web",
53
+ name: meta.name,
54
+ model: meta.model,
55
+ osVersion: meta.osVersion,
56
+ appVersion: meta.appVersion,
57
+ pushToken: meta.pushToken,
58
+ lastIp: context.lastIp,
59
+ lastSeenAt: context.now,
60
+ createdAt: context.now
61
+ });
62
+ const refreshed = {
63
+ lastSeenAt: record.lastSeenAt,
64
+ lastIp: record.lastIp
65
+ };
66
+ if (meta.platform !== null) refreshed.platform = record.platform;
67
+ if (meta.name !== null) refreshed.name = record.name;
68
+ if (meta.model !== null) refreshed.model = record.model;
69
+ if (meta.osVersion !== null) refreshed.osVersion = record.osVersion;
70
+ if (meta.appVersion !== null) refreshed.appVersion = record.appVersion;
71
+ if (meta.pushToken !== null) refreshed.pushToken = record.pushToken;
72
+ await db.insertInto("pithyAuthDevices").values(record).onConflict((oc) => oc.columns(["userId", "id"]).doUpdateSet(refreshed)).execute();
73
+ }
74
+ /** List a user's registered devices, most-recently-seen first. */
75
+ async function listDevices(db, userId) {
76
+ return (await db.selectFrom("pithyAuthDevices").selectAll().where("userId", "=", userId).orderBy("lastSeenAt", "desc").execute()).map((row) => Device.parse(row));
77
+ }
78
+ /** Resolve the session tokens bound to one of a user's devices — the set a device-revoke must sign out. */
79
+ async function deviceSessionTokens(db, userId, deviceId) {
80
+ return (await db.selectFrom("pithyAuthSessions").select("token").where("userId", "=", userId).where("deviceId", "=", deviceId).execute()).map((row) => row.token);
81
+ }
82
+ /** Delete a user's device row (after its sessions are revoked). Returns true if a row was removed. */
83
+ async function deleteDevice(db, userId, deviceId) {
84
+ return ((await db.deleteFrom("pithyAuthDevices").where("userId", "=", userId).where("id", "=", deviceId).executeTakeFirst()).numDeletedRows ?? 0n) > 0n;
85
+ }
86
+ //#endregion
87
+ export { DEVICE_HEADERS, deleteDevice, deviceSessionTokens, listDevices, parseDeviceMeta, registerDevice };
@@ -0,0 +1,40 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { EmailCapability } from "@pithy-sh/email/src/capability";
4
+ import type { SendAuthEmail } from "../instance/auth";
5
+ /**
6
+ * The email-delivery seam. Auth never assembles the email infrastructure — it calls the `enqueue` the
7
+ * email capability exposes (already bound to the request env by the caller), passing only the
8
+ * high-level input. The email capability owns the `DB`/`EMAIL_SENDER` bindings, the from-identity, and
9
+ * the theme. Delivery is the email Workflow's job; auth only enqueues.
10
+ */
11
+ /** An env-bound enqueue — the email capability's `enqueue`, partially applied with the request env. */
12
+ export type EnqueueEmail = (input: Parameters<EmailCapability["enqueue"]>[1]) => Promise<unknown>;
13
+ /**
14
+ * The language to write to this person in, resolved per message.
15
+ *
16
+ * A thunk over the address rather than a value, because the answer is a database read and most of
17
+ * what it is asked about is a sign-in that may not have an account yet. See {@link makeSendAuthEmail}.
18
+ */
19
+ export type ResolveRecipientLocale = (email: string) => Promise<string | null>;
20
+ /**
21
+ * Build the `sendEmail` the auth instance calls from its magic-link / OTP hooks.
22
+ *
23
+ * ## The locale
24
+ *
25
+ * A sign-in email is the first thing a project sends and the one it cannot afford to send in a
26
+ * language the reader does not have, because there is no password to fall back to: somebody who cannot
27
+ * find the button in an unfamiliar alphabet cannot get in at all. So `localeFor` is asked per message
28
+ * and the answer rides onto the job, where the send Workflow reads it back hours later.
29
+ *
30
+ * It resolves in two steps and the order matters. **A stored `pithy_auth_users.locale` wins**, because
31
+ * a person who has chosen a language has said something durable about themselves, and the device they
32
+ * happen to be signing in from tonight has not. Where there is no row — a first-time sign-up, which is
33
+ * exactly when a magic link matters most — the resolver falls back to the language this request
34
+ * negotiated, which is the only thing anyone knows about the reader yet. Null means neither answered,
35
+ * and null renders the kit's English rather than asserting English was chosen.
36
+ *
37
+ * Optional so that a composition without it (and every existing test harness) behaves as it did.
38
+ */
39
+ export declare function makeSendAuthEmail(enqueue: EnqueueEmail, expiresMinutes: number, localeFor?: ResolveRecipientLocale): SendAuthEmail;
40
+ //# sourceMappingURL=send.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send.d.ts","sourceRoot":"","sources":["../../src/email/send.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,KAAK,EAAoB,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAExE;;;;;GAKG;AAEH,uGAAuG;AACvG,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAElG;;;;;GAKG;AACH,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAE/E;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,YAAY,EACrB,cAAc,EAAE,MAAM,EACtB,SAAS,CAAC,EAAE,sBAAsB,GACjC,aAAa,CAmBf"}