@pithy-sh/auth 0.1.1 → 0.1.3
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.
- package/dist/admin/users.d.ts +155 -0
- package/dist/admin/users.d.ts.map +1 -0
- package/dist/admin/users.js +205 -0
- package/dist/audit/actions.d.ts +66 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +66 -0
- package/dist/audit/emit.d.ts +101 -0
- package/dist/audit/emit.d.ts.map +1 -0
- package/dist/audit/emit.js +170 -0
- package/dist/capability.d.ts +60 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +169 -0
- package/dist/client/api.d.ts +299 -0
- package/dist/client/api.d.ts.map +1 -0
- package/dist/client/api.js +385 -0
- package/dist/client/projection.d.ts +51 -0
- package/dist/client/projection.d.ts.map +1 -0
- package/dist/client/projection.js +0 -0
- package/dist/data/betterAuth.d.ts +75 -0
- package/dist/data/betterAuth.d.ts.map +1 -0
- package/dist/data/betterAuth.js +92 -0
- package/dist/data/device.d.ts +36 -0
- package/dist/data/device.d.ts.map +1 -0
- package/dist/data/device.js +33 -0
- package/dist/data/kitFields.d.ts +78 -0
- package/dist/data/kitFields.d.ts.map +1 -0
- package/dist/data/kitFields.js +77 -0
- package/dist/data/rotatedToken.d.ts +20 -0
- package/dist/data/rotatedToken.d.ts.map +1 -0
- package/dist/data/rotatedToken.js +22 -0
- package/dist/data/tables.d.ts +104 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +30 -0
- package/dist/device/registry.d.ts +54 -0
- package/dist/device/registry.d.ts.map +1 -0
- package/dist/device/registry.js +85 -0
- package/dist/email/send.d.ts +38 -0
- package/dist/email/send.d.ts.map +1 -0
- package/dist/email/send.js +48 -0
- package/dist/http/adminRoutes.d.ts +9 -0
- package/dist/http/adminRoutes.d.ts.map +1 -0
- package/dist/http/adminRoutes.js +274 -0
- package/dist/http/baseUrl.d.ts +41 -0
- package/dist/http/baseUrl.d.ts.map +1 -0
- package/dist/http/baseUrl.js +96 -0
- package/dist/http/csrf.d.ts +18 -0
- package/dist/http/csrf.d.ts.map +1 -0
- package/dist/http/csrf.js +81 -0
- package/dist/http/devLoginRoute.d.ts +42 -0
- package/dist/http/devLoginRoute.d.ts.map +1 -0
- package/dist/http/devLoginRoute.js +112 -0
- package/dist/http/errors.d.ts +24 -0
- package/dist/http/errors.d.ts.map +1 -0
- package/dist/http/errors.js +67 -0
- package/dist/http/guards.d.ts +103 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +148 -0
- package/dist/http/middleware.d.ts +17 -0
- package/dist/http/middleware.d.ts.map +1 -0
- package/dist/http/middleware.js +47 -0
- package/dist/http/rateLimit.d.ts +17 -0
- package/dist/http/rateLimit.d.ts.map +1 -0
- package/dist/http/rateLimit.js +31 -0
- package/dist/http/resolve.d.ts +9 -0
- package/dist/http/resolve.d.ts.map +1 -0
- package/dist/http/resolve.js +92 -0
- package/dist/http/responses.d.ts +152 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +121 -0
- package/dist/http/routes.d.ts +34 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +268 -0
- package/dist/http/schemas.d.ts +66 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +59 -0
- package/dist/http/views.d.ts +53 -0
- package/dist/http/views.d.ts.map +1 -0
- package/dist/http/views.js +86 -0
- package/dist/i18n/errorCopy.d.ts +24 -0
- package/dist/i18n/errorCopy.d.ts.map +1 -0
- package/dist/i18n/errorCopy.es.d.ts +31 -0
- package/dist/i18n/errorCopy.es.d.ts.map +1 -0
- package/dist/i18n/errorCopy.es.js +33 -0
- package/dist/i18n/errorCopy.js +91 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/instance/auth.d.ts +1122 -0
- package/dist/instance/auth.d.ts.map +1 -0
- package/dist/instance/auth.js +176 -0
- package/dist/instance/plugins.d.ts +87 -0
- package/dist/instance/plugins.d.ts.map +1 -0
- package/dist/instance/plugins.js +116 -0
- package/dist/instance/providers.d.ts +117 -0
- package/dist/instance/providers.d.ts.map +1 -0
- package/dist/instance/providers.js +111 -0
- package/dist/instance/secrets.d.ts +163 -0
- package/dist/instance/secrets.d.ts.map +1 -0
- package/dist/instance/secrets.js +169 -0
- package/dist/migrations/0001_init.d.ts +33 -0
- package/dist/migrations/0001_init.d.ts.map +1 -0
- package/dist/migrations/0001_init.js +77 -0
- package/dist/migrations/pluginTables.d.ts +126 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -0
- package/dist/migrations/pluginTables.js +233 -0
- package/dist/seeds/devSession.d.ts +124 -0
- package/dist/seeds/devSession.d.ts.map +1 -0
- package/dist/seeds/devSession.js +211 -0
- package/dist/seeds/example.d.ts +12 -0
- package/dist/seeds/example.d.ts.map +1 -0
- package/dist/seeds/example.js +30 -0
- package/dist/test-utils/liveApp.d.ts +227 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -0
- package/dist/test-utils/liveApp.js +240 -0
- package/dist/token/rotation.d.ts +56 -0
- package/dist/token/rotation.d.ts.map +1 -0
- package/dist/token/rotation.js +68 -0
- package/dist/version.generated.d.ts +5 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +7 -0
- package/package.json +24 -13
- package/src/version.generated.ts +1 -1
|
@@ -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,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
3
|
+
//#region src/data/device.ts
|
|
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
|
+
const DevicePlatform = z.enum([
|
|
14
|
+
"ios",
|
|
15
|
+
"android",
|
|
16
|
+
"web"
|
|
17
|
+
]).describe("The device platform: `ios`, `android`, or `web`.");
|
|
18
|
+
/** One registered device. */
|
|
19
|
+
const Device = z.object({
|
|
20
|
+
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."),
|
|
21
|
+
userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE. Indexed."),
|
|
22
|
+
platform: DevicePlatform.describe("The device platform, captured from login metadata."),
|
|
23
|
+
name: z.string().nullable().describe("A human label for the device (OS device name), shown in device-management UI. Nullable."),
|
|
24
|
+
model: z.string().nullable().describe("The hardware model, for device-management UI and support. Nullable."),
|
|
25
|
+
osVersion: z.string().nullable().describe("The device OS version at last sign-in. Nullable."),
|
|
26
|
+
appVersion: z.string().nullable().describe("The client app version at last sign-in. Nullable."),
|
|
27
|
+
pushToken: z.string().nullable().describe("The APNs/FCM push token, stored for the future push capability and updatable. Nullable."),
|
|
28
|
+
lastIp: z.string().nullable().describe("The client IP at the most recent sign-in, for `new sign-in from…` security signals. Nullable."),
|
|
29
|
+
lastSeenAt: SQLiteDate.describe("When this device was last seen (most recent sign-in). Ms-epoch in SQLite; a `Date` in app code."),
|
|
30
|
+
createdAt: SQLiteDate.describe("When this device was first registered. Ms-epoch in SQLite; a `Date` in app code.")
|
|
31
|
+
}).describe("A registered device in `pithy_auth_devices` — per-device sessions, security signals, and push routing.");
|
|
32
|
+
//#endregion
|
|
33
|
+
export { Device, DevicePlatform };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The columns Pithy adds to Better Auth's own tables, declared **once**.
|
|
3
|
+
*
|
|
4
|
+
* Better Auth owns every read and write to `pithy_auth_users` and `pithy_auth_sessions` through its
|
|
5
|
+
* Kysely adapter, and it writes only the fields its options declare. So a column that exists in the
|
|
6
|
+
* migration and in the `User` Zod object and *not* here is null forever and absent from every user
|
|
7
|
+
* object the instance returns — a migration and a schema field that silently did nothing.
|
|
8
|
+
*
|
|
9
|
+
* ## Why one module rather than two agreeing declarations
|
|
10
|
+
*
|
|
11
|
+
* These have to appear in two places: `makeAuth`'s live options (`../instance/auth.ts`) and the
|
|
12
|
+
* schema baseline `pluginSchemaDelta` subtracts each adopter plugin's schema from
|
|
13
|
+
* (`../migrations/pluginTables.ts`). Both were written out by hand, with a comment in each saying it
|
|
14
|
+
* "must match" the other and a test claiming to hold them together. The test did not: it compared the
|
|
15
|
+
* baseline against the `User` schema and never imported `makeAuth` at all, so reverting the live
|
|
16
|
+
* declaration left the whole suite green while Better Auth silently stopped writing the column (#441).
|
|
17
|
+
*
|
|
18
|
+
* `docs/CONVENTIONS.md` is explicit that removing an invariant beats watching it. There is one object
|
|
19
|
+
* now, imported by both, and the two cannot disagree because there is no second thing to disagree
|
|
20
|
+
* with. That is also why the consequence is worth restating rather than diluting: leave a kit column
|
|
21
|
+
* out of the baseline and `pluginSchemaDelta` reports it as something an adopter's plugin brought, so
|
|
22
|
+
* a plugin that also declares a user `locale` emits `ALTER TABLE … ADD COLUMN locale` against a table
|
|
23
|
+
* that already has one — a duplicate-column failure part-way through a migration D1 cannot roll back,
|
|
24
|
+
* because it has no transactional DDL.
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* The extra `pithy_auth_users` columns.
|
|
28
|
+
*
|
|
29
|
+
* **`locale` is `input: true`, deliberately, and that is the whole point of the column.** Every other
|
|
30
|
+
* extra field the kit declares is server-set — {@link KIT_SESSION_FIELDS} is `input: false` because a
|
|
31
|
+
* client that could name its own device or token family could name somebody else's. A locale is the
|
|
32
|
+
* opposite: it is the reader's own preference, and the flow it exists for is a signed-in reader
|
|
33
|
+
* switching language and having the choice follow them to their next device. Refusing client input
|
|
34
|
+
* would leave an admin route as the only way to store a preference, which is not a thing a reader has.
|
|
35
|
+
*
|
|
36
|
+
* **What makes that safe is the validator, not the type.** `type: "string"` alone would let a caller
|
|
37
|
+
* write any string into a column every read passes through `User.parse` — so one `updateUser` with a
|
|
38
|
+
* megabyte of junk would poison that row, and the admin listing that reads a page of rows would then
|
|
39
|
+
* throw for every operator rather than only for the author. Better Auth runs `validator.input` on the
|
|
40
|
+
* supplied value and answers 400 on a failure (`parseInputData`), so the same schema that guards the
|
|
41
|
+
* read guards the write, one hop earlier.
|
|
42
|
+
*
|
|
43
|
+
* **And it is `Locale.nullable()`, not `Locale`.** The column is nullable, the `User` field is
|
|
44
|
+
* nullable, `AdminUserView` is nullable, and every one of those says the same thing: null is "this
|
|
45
|
+
* reader has not chosen", which is what makes the server fall back to `Accept-Language`. A validator
|
|
46
|
+
* that accepted a tag but refused `null` would let a reader pick a language and never take it back —
|
|
47
|
+
* `updateUser({ locale: null })` answering 400 for the one state the schema calls ordinary.
|
|
48
|
+
*/
|
|
49
|
+
export declare const KIT_USER_FIELDS: {
|
|
50
|
+
readonly locale: {
|
|
51
|
+
readonly type: "string";
|
|
52
|
+
readonly required: false;
|
|
53
|
+
readonly input: true;
|
|
54
|
+
readonly validator: {
|
|
55
|
+
readonly input: import("zod").ZodNullable<import("zod").ZodString>;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
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
|
+
export declare const KIT_SESSION_FIELDS: {
|
|
67
|
+
readonly deviceId: {
|
|
68
|
+
readonly type: "string";
|
|
69
|
+
readonly required: false;
|
|
70
|
+
readonly input: false;
|
|
71
|
+
};
|
|
72
|
+
readonly familyId: {
|
|
73
|
+
readonly type: "string";
|
|
74
|
+
readonly required: false;
|
|
75
|
+
readonly input: false;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
//# 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,77 @@
|
|
|
1
|
+
import { Locale } from "@pithy-sh/core/src/i18n/locale";
|
|
2
|
+
//#region src/data/kitFields.ts
|
|
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
|
+
const KIT_USER_FIELDS = { locale: {
|
|
52
|
+
type: "string",
|
|
53
|
+
required: false,
|
|
54
|
+
input: true,
|
|
55
|
+
validator: { input: Locale.nullable() }
|
|
56
|
+
} };
|
|
57
|
+
/**
|
|
58
|
+
* The extra `pithy_auth_sessions` columns — the bound device, and the refresh-token family carried
|
|
59
|
+
* across rotations.
|
|
60
|
+
*
|
|
61
|
+
* `input: false` on both: these are server-set facts about a session, and a client able to name its own
|
|
62
|
+
* device id or token family could name somebody else's.
|
|
63
|
+
*/
|
|
64
|
+
const KIT_SESSION_FIELDS = {
|
|
65
|
+
deviceId: {
|
|
66
|
+
type: "string",
|
|
67
|
+
required: false,
|
|
68
|
+
input: false
|
|
69
|
+
},
|
|
70
|
+
familyId: {
|
|
71
|
+
type: "string",
|
|
72
|
+
required: false,
|
|
73
|
+
input: false
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
//#endregion
|
|
77
|
+
export { KIT_SESSION_FIELDS, KIT_USER_FIELDS };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* `pithy_auth_rotated_tokens` — the reuse-detection ledger, a Pithy-specific table with no
|
|
4
|
+
* Better-Auth equivalent.
|
|
5
|
+
*
|
|
6
|
+
* One row per refresh token that has been consumed by a rotation. On `/auth/token/rotate` the
|
|
7
|
+
* presented session token is deleted and recorded here; presenting it again (after it no longer
|
|
8
|
+
* resolves to a live session) is a replayed refresh credential — the canonical compromise signal for
|
|
9
|
+
* rotated refresh tokens (OAuth refresh rotation, RFC 6819 §5.2.2.3). The row carries the `familyId`
|
|
10
|
+
* so the whole token family can be revoked on reuse. Written by Pithy code through our shared Kysely,
|
|
11
|
+
* so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
|
|
12
|
+
*/
|
|
13
|
+
export declare const RotatedToken: z.ZodObject<{
|
|
14
|
+
token: z.ZodString;
|
|
15
|
+
familyId: z.ZodString;
|
|
16
|
+
userId: z.ZodString;
|
|
17
|
+
rotatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
|
|
18
|
+
}, z.core.$strip>;
|
|
19
|
+
export type RotatedToken = z.output<typeof RotatedToken>;
|
|
20
|
+
//# 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,22 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
3
|
+
//#region src/data/rotatedToken.ts
|
|
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
|
+
const RotatedToken = z.object({
|
|
16
|
+
token: z.string().describe("Primary key. The consumed session token, recorded when a rotation revoked it. Presenting it again is reuse."),
|
|
17
|
+
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."),
|
|
18
|
+
userId: z.string().describe("The owning user's id, for attributing the reuse audit event to the compromised account."),
|
|
19
|
+
rotatedAt: SQLiteDate.describe("When the token was consumed by a rotation. Ms-epoch in SQLite; a `Date` in app code. Drives retention pruning.")
|
|
20
|
+
}).describe("A consumed refresh token in `pithy_auth_rotated_tokens` — the ledger that powers refresh-token reuse detection and family revocation.");
|
|
21
|
+
//#endregion
|
|
22
|
+
export { RotatedToken };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
2
|
+
import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
|
|
3
|
+
import type { Kysely } from "kysely";
|
|
4
|
+
/**
|
|
5
|
+
* The auth capability's table map: camelCase keys, so `CamelCasePlugin` emits the snake_case
|
|
6
|
+
* `pithy_auth_*` SQL. One source of truth shared by the capability wiring, the Better-Auth instance
|
|
7
|
+
* (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
|
|
8
|
+
*
|
|
9
|
+
* The first six tables are Better-Auth-managed; `pithyAuthDevices` and `pithyAuthRotatedTokens` are
|
|
10
|
+
* ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
|
|
11
|
+
* own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
|
|
12
|
+
*/
|
|
13
|
+
export declare const authTables: {
|
|
14
|
+
pithyAuthUsers: import("zod").ZodObject<{
|
|
15
|
+
id: import("zod").ZodString;
|
|
16
|
+
name: import("zod").ZodString;
|
|
17
|
+
email: import("zod").ZodString;
|
|
18
|
+
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>;
|
|
19
|
+
image: import("zod").ZodNullable<import("zod").ZodString>;
|
|
20
|
+
locale: import("zod").ZodNullable<import("zod").ZodString>;
|
|
21
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
22
|
+
updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
23
|
+
}, import("zod/v4/core").$strip>;
|
|
24
|
+
pithyAuthSessions: import("zod").ZodObject<{
|
|
25
|
+
id: import("zod").ZodString;
|
|
26
|
+
expiresAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
27
|
+
token: import("zod").ZodString;
|
|
28
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
29
|
+
updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
30
|
+
ipAddress: import("zod").ZodNullable<import("zod").ZodString>;
|
|
31
|
+
userAgent: import("zod").ZodNullable<import("zod").ZodString>;
|
|
32
|
+
userId: import("zod").ZodString;
|
|
33
|
+
deviceId: import("zod").ZodNullable<import("zod").ZodString>;
|
|
34
|
+
familyId: import("zod").ZodNullable<import("zod").ZodString>;
|
|
35
|
+
}, import("zod/v4/core").$strip>;
|
|
36
|
+
pithyAuthAccounts: import("zod").ZodObject<{
|
|
37
|
+
id: import("zod").ZodString;
|
|
38
|
+
issuer: import("zod").ZodString;
|
|
39
|
+
accountId: import("zod").ZodString;
|
|
40
|
+
providerId: import("zod").ZodString;
|
|
41
|
+
userId: import("zod").ZodString;
|
|
42
|
+
accessToken: import("zod").ZodNullable<import("zod").ZodString>;
|
|
43
|
+
refreshToken: import("zod").ZodNullable<import("zod").ZodString>;
|
|
44
|
+
idToken: import("zod").ZodNullable<import("zod").ZodString>;
|
|
45
|
+
accessTokenExpiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
|
|
46
|
+
refreshTokenExpiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
|
|
47
|
+
scope: import("zod").ZodNullable<import("zod").ZodString>;
|
|
48
|
+
password: import("zod").ZodNullable<import("zod").ZodString>;
|
|
49
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
50
|
+
updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
51
|
+
}, import("zod/v4/core").$strip>;
|
|
52
|
+
pithyAuthVerifications: import("zod").ZodObject<{
|
|
53
|
+
id: import("zod").ZodString;
|
|
54
|
+
identifier: import("zod").ZodString;
|
|
55
|
+
value: import("zod").ZodString;
|
|
56
|
+
expiresAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
57
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
58
|
+
updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
59
|
+
}, import("zod/v4/core").$strip>;
|
|
60
|
+
pithyAuthJwks: import("zod").ZodObject<{
|
|
61
|
+
id: import("zod").ZodString;
|
|
62
|
+
publicKey: import("zod").ZodString;
|
|
63
|
+
privateKey: import("zod").ZodString;
|
|
64
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
65
|
+
expiresAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>>;
|
|
66
|
+
alg: import("zod").ZodNullable<import("zod").ZodString>;
|
|
67
|
+
crv: import("zod").ZodNullable<import("zod").ZodString>;
|
|
68
|
+
}, import("zod/v4/core").$strip>;
|
|
69
|
+
pithyAuthRateLimit: import("zod").ZodObject<{
|
|
70
|
+
id: import("zod").ZodString;
|
|
71
|
+
key: import("zod").ZodString;
|
|
72
|
+
count: import("zod").ZodNumber;
|
|
73
|
+
lastRequest: import("zod").ZodNumber;
|
|
74
|
+
}, import("zod/v4/core").$strip>;
|
|
75
|
+
pithyAuthDevices: import("zod").ZodObject<{
|
|
76
|
+
id: import("zod").ZodString;
|
|
77
|
+
userId: import("zod").ZodString;
|
|
78
|
+
platform: import("zod").ZodEnum<{
|
|
79
|
+
android: "android";
|
|
80
|
+
ios: "ios";
|
|
81
|
+
web: "web";
|
|
82
|
+
}>;
|
|
83
|
+
name: import("zod").ZodNullable<import("zod").ZodString>;
|
|
84
|
+
model: import("zod").ZodNullable<import("zod").ZodString>;
|
|
85
|
+
osVersion: import("zod").ZodNullable<import("zod").ZodString>;
|
|
86
|
+
appVersion: import("zod").ZodNullable<import("zod").ZodString>;
|
|
87
|
+
pushToken: import("zod").ZodNullable<import("zod").ZodString>;
|
|
88
|
+
lastIp: import("zod").ZodNullable<import("zod").ZodString>;
|
|
89
|
+
lastSeenAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
90
|
+
createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
91
|
+
}, import("zod/v4/core").$strip>;
|
|
92
|
+
pithyAuthRotatedTokens: import("zod").ZodObject<{
|
|
93
|
+
token: import("zod").ZodString;
|
|
94
|
+
familyId: import("zod").ZodString;
|
|
95
|
+
userId: import("zod").ZodString;
|
|
96
|
+
rotatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>;
|
|
97
|
+
}, import("zod/v4/core").$strip>;
|
|
98
|
+
};
|
|
99
|
+
export type AuthTables = typeof authTables;
|
|
100
|
+
/** The typed Kysely view over the auth tables — shared by the Better-Auth adapter and the device registry. */
|
|
101
|
+
export type AuthDatabase = Kysely<DatabaseSchema<AuthTables>>;
|
|
102
|
+
/** Build the auth Kysely over a D1 binding. Carries `CamelCasePlugin`, so query code stays camelCase. */
|
|
103
|
+
export declare function authDatabase(d1: D1Database): AuthDatabase;
|
|
104
|
+
//# 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,30 @@
|
|
|
1
|
+
import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth.js";
|
|
2
|
+
import { Device } from "./device.js";
|
|
3
|
+
import { RotatedToken } from "./rotatedToken.js";
|
|
4
|
+
import { createDatabase } from "@pithy-sh/core/src/data/db";
|
|
5
|
+
//#region src/data/tables.ts
|
|
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
|
+
const authTables = {
|
|
16
|
+
pithyAuthUsers: User,
|
|
17
|
+
pithyAuthSessions: Session,
|
|
18
|
+
pithyAuthAccounts: Account,
|
|
19
|
+
pithyAuthVerifications: Verification,
|
|
20
|
+
pithyAuthJwks: Jwks,
|
|
21
|
+
pithyAuthRateLimit: RateLimit,
|
|
22
|
+
pithyAuthDevices: Device,
|
|
23
|
+
pithyAuthRotatedTokens: RotatedToken
|
|
24
|
+
};
|
|
25
|
+
/** Build the auth Kysely over a D1 binding. Carries `CamelCasePlugin`, so query code stays camelCase. */
|
|
26
|
+
function authDatabase(d1) {
|
|
27
|
+
return createDatabase(d1, authTables);
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { authDatabase, authTables };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Device, DevicePlatform } from "../data/device";
|
|
2
|
+
import type { AuthDatabase } from "../data/tables";
|
|
3
|
+
/**
|
|
4
|
+
* The device registry: parse optional device metadata off a sign-in request, upsert the
|
|
5
|
+
* `pithy_auth_devices` row, and resolve a device's sessions for revocation. All writes go through our
|
|
6
|
+
* shared Kysely + codecs (ms-epoch dates) — distinct from the Better-Auth-managed tables.
|
|
7
|
+
*/
|
|
8
|
+
/** Request headers a client may send at sign-in to register/identify its device. */
|
|
9
|
+
export declare const DEVICE_HEADERS: {
|
|
10
|
+
readonly id: "x-pithy-device-id";
|
|
11
|
+
readonly platform: "x-pithy-platform";
|
|
12
|
+
readonly name: "x-pithy-device-name";
|
|
13
|
+
readonly model: "x-pithy-device-model";
|
|
14
|
+
readonly osVersion: "x-pithy-os-version";
|
|
15
|
+
readonly appVersion: "x-pithy-app-version";
|
|
16
|
+
readonly pushToken: "x-pithy-push-token";
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Device metadata captured at sign-in. `id` is required; everything else is best-effort. `platform` is
|
|
20
|
+
* `null` when the header was absent — distinct from a supplied value — so a sparse re-login never
|
|
21
|
+
* overwrites a known platform with a default.
|
|
22
|
+
*/
|
|
23
|
+
export interface DeviceMeta {
|
|
24
|
+
id: string;
|
|
25
|
+
platform: DevicePlatform | null;
|
|
26
|
+
name: string | null;
|
|
27
|
+
model: string | null;
|
|
28
|
+
osVersion: string | null;
|
|
29
|
+
appVersion: string | null;
|
|
30
|
+
pushToken: string | null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Parse device metadata from request headers. Returns `undefined` when no `x-pithy-device-id` is
|
|
34
|
+
* present — a device-less login (a plain web session). `platform` is `null` when its header is absent
|
|
35
|
+
* or unrecognized; the default `web` is applied only on first registration, never on a sparse update.
|
|
36
|
+
*/
|
|
37
|
+
export declare function parseDeviceMeta(headers: Headers): DeviceMeta | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Register-or-update a device for a user. Idempotent on the composite `(userId, id)` key: a re-login
|
|
40
|
+
* from the same device refreshes `lastSeenAt`/`lastIp` and any newly-supplied metadata, but never
|
|
41
|
+
* overwrites existing metadata with a sparse login and never resets `createdAt`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function registerDevice(db: AuthDatabase, meta: DeviceMeta, context: {
|
|
44
|
+
userId: string;
|
|
45
|
+
lastIp: string | null;
|
|
46
|
+
now: Date;
|
|
47
|
+
}): Promise<void>;
|
|
48
|
+
/** List a user's registered devices, most-recently-seen first. */
|
|
49
|
+
export declare function listDevices(db: AuthDatabase, userId: string): Promise<Device[]>;
|
|
50
|
+
/** Resolve the session tokens bound to one of a user's devices — the set a device-revoke must sign out. */
|
|
51
|
+
export declare function deviceSessionTokens(db: AuthDatabase, userId: string, deviceId: string): Promise<string[]>;
|
|
52
|
+
/** Delete a user's device row (after its sessions are revoked). Returns true if a row was removed. */
|
|
53
|
+
export declare function deleteDevice(db: AuthDatabase, userId: string, deviceId: string): Promise<boolean>;
|
|
54
|
+
//# 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,85 @@
|
|
|
1
|
+
import { Device, DevicePlatform } from "../data/device.js";
|
|
2
|
+
//#region src/device/registry.ts
|
|
3
|
+
/**
|
|
4
|
+
* The device registry: parse optional device metadata off a sign-in request, upsert the
|
|
5
|
+
* `pithy_auth_devices` row, and resolve a device's sessions for revocation. All writes go through our
|
|
6
|
+
* shared Kysely + codecs (ms-epoch dates) — distinct from the Better-Auth-managed tables.
|
|
7
|
+
*/
|
|
8
|
+
/** Request headers a client may send at sign-in to register/identify its device. */
|
|
9
|
+
const DEVICE_HEADERS = {
|
|
10
|
+
id: "x-pithy-device-id",
|
|
11
|
+
platform: "x-pithy-platform",
|
|
12
|
+
name: "x-pithy-device-name",
|
|
13
|
+
model: "x-pithy-device-model",
|
|
14
|
+
osVersion: "x-pithy-os-version",
|
|
15
|
+
appVersion: "x-pithy-app-version",
|
|
16
|
+
pushToken: "x-pithy-push-token"
|
|
17
|
+
};
|
|
18
|
+
function header(headers, name) {
|
|
19
|
+
const value = headers.get(name)?.trim();
|
|
20
|
+
return value ? value : null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Parse device metadata from request headers. Returns `undefined` when no `x-pithy-device-id` is
|
|
24
|
+
* present — a device-less login (a plain web session). `platform` is `null` when its header is absent
|
|
25
|
+
* or unrecognized; the default `web` is applied only on first registration, never on a sparse update.
|
|
26
|
+
*/
|
|
27
|
+
function parseDeviceMeta(headers) {
|
|
28
|
+
const id = header(headers, DEVICE_HEADERS.id);
|
|
29
|
+
if (!id) return void 0;
|
|
30
|
+
const platform = DevicePlatform.safeParse(header(headers, DEVICE_HEADERS.platform));
|
|
31
|
+
return {
|
|
32
|
+
id,
|
|
33
|
+
platform: platform.success ? platform.data : null,
|
|
34
|
+
name: header(headers, DEVICE_HEADERS.name),
|
|
35
|
+
model: header(headers, DEVICE_HEADERS.model),
|
|
36
|
+
osVersion: header(headers, DEVICE_HEADERS.osVersion),
|
|
37
|
+
appVersion: header(headers, DEVICE_HEADERS.appVersion),
|
|
38
|
+
pushToken: header(headers, DEVICE_HEADERS.pushToken)
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Register-or-update a device for a user. Idempotent on the composite `(userId, id)` key: a re-login
|
|
43
|
+
* from the same device refreshes `lastSeenAt`/`lastIp` and any newly-supplied metadata, but never
|
|
44
|
+
* overwrites existing metadata with a sparse login and never resets `createdAt`.
|
|
45
|
+
*/
|
|
46
|
+
async function registerDevice(db, meta, context) {
|
|
47
|
+
const record = Device.encode({
|
|
48
|
+
id: meta.id,
|
|
49
|
+
userId: context.userId,
|
|
50
|
+
platform: meta.platform ?? "web",
|
|
51
|
+
name: meta.name,
|
|
52
|
+
model: meta.model,
|
|
53
|
+
osVersion: meta.osVersion,
|
|
54
|
+
appVersion: meta.appVersion,
|
|
55
|
+
pushToken: meta.pushToken,
|
|
56
|
+
lastIp: context.lastIp,
|
|
57
|
+
lastSeenAt: context.now,
|
|
58
|
+
createdAt: context.now
|
|
59
|
+
});
|
|
60
|
+
const refreshed = {
|
|
61
|
+
lastSeenAt: record.lastSeenAt,
|
|
62
|
+
lastIp: record.lastIp
|
|
63
|
+
};
|
|
64
|
+
if (meta.platform !== null) refreshed.platform = record.platform;
|
|
65
|
+
if (meta.name !== null) refreshed.name = record.name;
|
|
66
|
+
if (meta.model !== null) refreshed.model = record.model;
|
|
67
|
+
if (meta.osVersion !== null) refreshed.osVersion = record.osVersion;
|
|
68
|
+
if (meta.appVersion !== null) refreshed.appVersion = record.appVersion;
|
|
69
|
+
if (meta.pushToken !== null) refreshed.pushToken = record.pushToken;
|
|
70
|
+
await db.insertInto("pithyAuthDevices").values(record).onConflict((oc) => oc.columns(["userId", "id"]).doUpdateSet(refreshed)).execute();
|
|
71
|
+
}
|
|
72
|
+
/** List a user's registered devices, most-recently-seen first. */
|
|
73
|
+
async function listDevices(db, userId) {
|
|
74
|
+
return (await db.selectFrom("pithyAuthDevices").selectAll().where("userId", "=", userId).orderBy("lastSeenAt", "desc").execute()).map((row) => Device.parse(row));
|
|
75
|
+
}
|
|
76
|
+
/** Resolve the session tokens bound to one of a user's devices — the set a device-revoke must sign out. */
|
|
77
|
+
async function deviceSessionTokens(db, userId, deviceId) {
|
|
78
|
+
return (await db.selectFrom("pithyAuthSessions").select("token").where("userId", "=", userId).where("deviceId", "=", deviceId).execute()).map((row) => row.token);
|
|
79
|
+
}
|
|
80
|
+
/** Delete a user's device row (after its sessions are revoked). Returns true if a row was removed. */
|
|
81
|
+
async function deleteDevice(db, userId, deviceId) {
|
|
82
|
+
return ((await db.deleteFrom("pithyAuthDevices").where("userId", "=", userId).where("id", "=", deviceId).executeTakeFirst()).numDeletedRows ?? 0n) > 0n;
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { DEVICE_HEADERS, deleteDevice, deviceSessionTokens, listDevices, parseDeviceMeta, registerDevice };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { EmailCapability } from "@pithy-sh/email/src/capability";
|
|
2
|
+
import type { SendAuthEmail } from "../instance/auth";
|
|
3
|
+
/**
|
|
4
|
+
* The email-delivery seam. Auth never assembles the email infrastructure — it calls the `enqueue` the
|
|
5
|
+
* email capability exposes (already bound to the request env by the caller), passing only the
|
|
6
|
+
* high-level input. The email capability owns the `DB`/`EMAIL_SENDER` bindings, the from-identity, and
|
|
7
|
+
* the theme. Delivery is the email Workflow's job; auth only enqueues.
|
|
8
|
+
*/
|
|
9
|
+
/** An env-bound enqueue — the email capability's `enqueue`, partially applied with the request env. */
|
|
10
|
+
export type EnqueueEmail = (input: Parameters<EmailCapability["enqueue"]>[1]) => Promise<unknown>;
|
|
11
|
+
/**
|
|
12
|
+
* The language to write to this person in, resolved per message.
|
|
13
|
+
*
|
|
14
|
+
* A thunk over the address rather than a value, because the answer is a database read and most of
|
|
15
|
+
* what it is asked about is a sign-in that may not have an account yet. See {@link makeSendAuthEmail}.
|
|
16
|
+
*/
|
|
17
|
+
export type ResolveRecipientLocale = (email: string) => Promise<string | null>;
|
|
18
|
+
/**
|
|
19
|
+
* Build the `sendEmail` the auth instance calls from its magic-link / OTP hooks.
|
|
20
|
+
*
|
|
21
|
+
* ## The locale
|
|
22
|
+
*
|
|
23
|
+
* A sign-in email is the first thing a project sends and the one it cannot afford to send in a
|
|
24
|
+
* language the reader does not have, because there is no password to fall back to: somebody who cannot
|
|
25
|
+
* find the button in an unfamiliar alphabet cannot get in at all. So `localeFor` is asked per message
|
|
26
|
+
* and the answer rides onto the job, where the send Workflow reads it back hours later.
|
|
27
|
+
*
|
|
28
|
+
* It resolves in two steps and the order matters. **A stored `pithy_auth_users.locale` wins**, because
|
|
29
|
+
* a person who has chosen a language has said something durable about themselves, and the device they
|
|
30
|
+
* happen to be signing in from tonight has not. Where there is no row — a first-time sign-up, which is
|
|
31
|
+
* exactly when a magic link matters most — the resolver falls back to the language this request
|
|
32
|
+
* negotiated, which is the only thing anyone knows about the reader yet. Null means neither answered,
|
|
33
|
+
* and null renders the kit's English rather than asserting English was chosen.
|
|
34
|
+
*
|
|
35
|
+
* Optional so that a composition without it (and every existing test harness) behaves as it did.
|
|
36
|
+
*/
|
|
37
|
+
export declare function makeSendAuthEmail(enqueue: EnqueueEmail, expiresMinutes: number, localeFor?: ResolveRecipientLocale): SendAuthEmail;
|
|
38
|
+
//# 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"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//#region src/email/send.ts
|
|
2
|
+
/**
|
|
3
|
+
* Build the `sendEmail` the auth instance calls from its magic-link / OTP hooks.
|
|
4
|
+
*
|
|
5
|
+
* ## The locale
|
|
6
|
+
*
|
|
7
|
+
* A sign-in email is the first thing a project sends and the one it cannot afford to send in a
|
|
8
|
+
* language the reader does not have, because there is no password to fall back to: somebody who cannot
|
|
9
|
+
* find the button in an unfamiliar alphabet cannot get in at all. So `localeFor` is asked per message
|
|
10
|
+
* and the answer rides onto the job, where the send Workflow reads it back hours later.
|
|
11
|
+
*
|
|
12
|
+
* It resolves in two steps and the order matters. **A stored `pithy_auth_users.locale` wins**, because
|
|
13
|
+
* a person who has chosen a language has said something durable about themselves, and the device they
|
|
14
|
+
* happen to be signing in from tonight has not. Where there is no row — a first-time sign-up, which is
|
|
15
|
+
* exactly when a magic link matters most — the resolver falls back to the language this request
|
|
16
|
+
* negotiated, which is the only thing anyone knows about the reader yet. Null means neither answered,
|
|
17
|
+
* and null renders the kit's English rather than asserting English was chosen.
|
|
18
|
+
*
|
|
19
|
+
* Optional so that a composition without it (and every existing test harness) behaves as it did.
|
|
20
|
+
*/
|
|
21
|
+
function makeSendAuthEmail(enqueue, expiresMinutes, localeFor) {
|
|
22
|
+
return async (message) => {
|
|
23
|
+
const locale = await localeFor?.(message.to) ?? void 0;
|
|
24
|
+
if (message.template === "magicLink") {
|
|
25
|
+
await enqueue({
|
|
26
|
+
to: message.to,
|
|
27
|
+
template: "magicLink",
|
|
28
|
+
payload: {
|
|
29
|
+
url: message.url,
|
|
30
|
+
expiresMinutes
|
|
31
|
+
},
|
|
32
|
+
...locale ? { locale } : {}
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
await enqueue({
|
|
37
|
+
to: message.to,
|
|
38
|
+
template: "otp",
|
|
39
|
+
payload: {
|
|
40
|
+
code: message.code,
|
|
41
|
+
expiresMinutes
|
|
42
|
+
},
|
|
43
|
+
...locale ? { locale } : {}
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { makeSendAuthEmail };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
2
|
+
import type { Hono } from "hono";
|
|
3
|
+
import type { AuthWiring } from "../capability";
|
|
4
|
+
/**
|
|
5
|
+
* Register the control-plane admin routes. Called by `createAuthRoutes` **before** the Better Auth
|
|
6
|
+
* catch-all; see the file header for why that ordering is load-bearing.
|
|
7
|
+
*/
|
|
8
|
+
export declare function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>) => void;
|
|
9
|
+
//# sourceMappingURL=adminRoutes.d.ts.map
|