@pithy-sh/auth 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +8 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/capability.d.ts +26 -1
  7. package/dist/capability.d.ts.map +1 -1
  8. package/dist/capability.js +23 -5
  9. package/dist/client/lifecycle.d.ts +19 -0
  10. package/dist/client/lifecycle.d.ts.map +1 -0
  11. package/dist/client/lifecycle.js +25 -0
  12. package/dist/client/projection.d.ts +4 -0
  13. package/dist/client/projection.d.ts.map +1 -1
  14. package/dist/data/betterAuth.d.ts +4 -0
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +6 -2
  17. package/dist/data/kitFields.d.ts +20 -25
  18. package/dist/data/kitFields.d.ts.map +1 -1
  19. package/dist/data/kitFields.js +28 -32
  20. package/dist/data/tables.d.ts +28 -2
  21. package/dist/data/tables.d.ts.map +1 -1
  22. package/dist/data/tables.js +5 -3
  23. package/dist/data/userLifecycle.d.ts +61 -0
  24. package/dist/data/userLifecycle.d.ts.map +1 -0
  25. package/dist/data/userLifecycle.js +50 -0
  26. package/dist/http/guards.d.ts +23 -1
  27. package/dist/http/guards.d.ts.map +1 -1
  28. package/dist/http/guards.js +28 -3
  29. package/dist/http/lifecycleGate.d.ts +18 -0
  30. package/dist/http/lifecycleGate.d.ts.map +1 -0
  31. package/dist/http/lifecycleGate.js +75 -0
  32. package/dist/http/middleware.d.ts +5 -0
  33. package/dist/http/middleware.d.ts.map +1 -1
  34. package/dist/http/middleware.js +47 -6
  35. package/dist/http/providerRefusal.d.ts.map +1 -1
  36. package/dist/http/providerRefusal.js +8 -0
  37. package/dist/http/resolve.d.ts.map +1 -1
  38. package/dist/http/resolve.js +7 -4
  39. package/dist/http/routes.d.ts.map +1 -1
  40. package/dist/http/routes.js +20 -1
  41. package/dist/instance/auth.d.ts +55 -3
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +53 -2
  44. package/dist/instance/microsoftEmail.d.ts +70 -0
  45. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  46. package/dist/instance/microsoftEmail.js +96 -0
  47. package/dist/instance/providerSignInGate.d.ts +7 -6
  48. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  49. package/dist/instance/providerSignInGate.js +7 -6
  50. package/dist/instance/providers.d.ts +7 -5
  51. package/dist/instance/providers.d.ts.map +1 -1
  52. package/dist/instance/providers.js +5 -3
  53. package/dist/instance/secrets.d.ts +64 -3
  54. package/dist/instance/secrets.d.ts.map +1 -1
  55. package/dist/instance/secrets.js +44 -5
  56. package/dist/lifecycle/enforce.d.ts +40 -0
  57. package/dist/lifecycle/enforce.d.ts.map +1 -0
  58. package/dist/lifecycle/enforce.js +70 -0
  59. package/dist/lifecycle/hooks.d.ts +53 -0
  60. package/dist/lifecycle/hooks.d.ts.map +1 -0
  61. package/dist/lifecycle/hooks.js +2 -0
  62. package/dist/lifecycle/request.d.ts +15 -0
  63. package/dist/lifecycle/request.d.ts.map +1 -0
  64. package/dist/lifecycle/request.js +27 -0
  65. package/dist/lifecycle/state.d.ts +64 -0
  66. package/dist/lifecycle/state.d.ts.map +1 -0
  67. package/dist/lifecycle/state.js +90 -0
  68. package/dist/lifecycle/transitions.d.ts +132 -0
  69. package/dist/lifecycle/transitions.d.ts.map +1 -0
  70. package/dist/lifecycle/transitions.js +349 -0
  71. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  72. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  73. package/dist/migrations/0004_user_lifecycle.js +47 -0
  74. package/dist/migrations/set.d.ts +2 -1
  75. package/dist/migrations/set.d.ts.map +1 -1
  76. package/dist/migrations/set.js +4 -2
  77. package/dist/peer.d.ts +4 -0
  78. package/dist/peer.d.ts.map +1 -1
  79. package/dist/test-utils/liveApp.d.ts +21 -0
  80. package/dist/test-utils/liveApp.d.ts.map +1 -1
  81. package/dist/test-utils/liveApp.js +1 -0
  82. package/dist/test-utils/scopedBackend.d.ts +21 -0
  83. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  84. package/dist/test-utils/scopedBackend.js +7 -1
  85. package/dist/version.generated.d.ts +1 -1
  86. package/dist/version.generated.d.ts.map +1 -1
  87. package/dist/version.generated.js +1 -1
  88. package/docs/account-lifecycle.md +105 -0
  89. package/docs/apple-signin.md +7 -1
  90. package/docs/facebook-oauth.md +7 -1
  91. package/docs/github-oauth.md +7 -1
  92. package/docs/google-oauth.md +7 -1
  93. package/docs/microsoft-oauth.md +177 -0
  94. package/package.json +5 -5
  95. package/pithy.manifest.json +17 -3
  96. package/src/audit/actions.ts +23 -0
  97. package/src/audit/emit.ts +1 -1
  98. package/src/capability.ts +125 -54
  99. package/src/client/lifecycle.ts +27 -0
  100. package/src/client/projection.ts +4 -0
  101. package/src/data/betterAuth.ts +21 -1
  102. package/src/data/kitFields.ts +27 -0
  103. package/src/data/tables.ts +4 -2
  104. package/src/data/userLifecycle.ts +80 -0
  105. package/src/http/guards.ts +29 -1
  106. package/src/http/lifecycleGate.ts +78 -0
  107. package/src/http/middleware.ts +61 -2
  108. package/src/http/providerRefusal.ts +10 -0
  109. package/src/http/resolve.ts +8 -3
  110. package/src/http/routes.ts +38 -1
  111. package/src/instance/auth.ts +69 -2
  112. package/src/instance/microsoftEmail.ts +111 -0
  113. package/src/instance/providerSignInGate.ts +7 -6
  114. package/src/instance/providers.ts +8 -4
  115. package/src/instance/secrets.ts +59 -5
  116. package/src/lifecycle/enforce.ts +89 -0
  117. package/src/lifecycle/hooks.ts +54 -0
  118. package/src/lifecycle/request.ts +31 -0
  119. package/src/lifecycle/state.ts +101 -0
  120. package/src/lifecycle/transitions.ts +483 -0
  121. package/src/migrations/0004_user_lifecycle.ts +68 -0
  122. package/src/migrations/set.ts +3 -1
  123. package/src/test-utils/liveApp.ts +2 -1
  124. package/src/test-utils/scopedBackend.ts +2 -1
  125. package/src/version.generated.ts +1 -1
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * `pithy_auth_user_lifecycle` — every transition an account went through, who made it, and why.
6
+ *
7
+ * **The columns on `pithy_auth_users` answer "what is true now"; this table answers "what happened, and who
8
+ * did it".** The two are written together by `../lifecycle/transitions.ts` and never apart. The columns are
9
+ * what enforcement reads on every request, so they hold only the current state; the reason an operator gave
10
+ * for a suspension, and the history of every reinstatement before it, live here.
11
+ *
12
+ * **No foreign key to the user, deliberately.** A purge erases the user row and every row hanging off it, and
13
+ * this table is the one record that must survive it: the trail that the account existed, was deleted, and
14
+ * was erased, by whom and when. A cascade would take the evidence with the subject. So the row names the user
15
+ * by id and holds nothing else about them — no address, no name — and is the only `pithy_auth_*` row a purge
16
+ * leaves behind.
17
+ *
18
+ * Written by the kit through its own Kysely, so its dates take the house ms-epoch `SQLiteDate`.
19
+ */
20
+ /** What happened to the account. */
21
+ export declare const UserLifecycleAction: z.ZodEnum<{
22
+ deleted: "deleted";
23
+ purge_step: "purge_step";
24
+ purged: "purged";
25
+ reinstated: "reinstated";
26
+ restored: "restored";
27
+ suspended: "suspended";
28
+ }>;
29
+ export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
30
+ /** Who made the transition. */
31
+ export declare const UserLifecycleActorType: z.ZodEnum<{
32
+ "control-plane": "control-plane";
33
+ system: "system";
34
+ user: "user";
35
+ }>;
36
+ export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
37
+ /** One transition, as stored. */
38
+ export declare const UserLifecycleEvent: z.ZodObject<{
39
+ id: z.ZodNumber;
40
+ userId: z.ZodString;
41
+ action: z.ZodEnum<{
42
+ deleted: "deleted";
43
+ purge_step: "purge_step";
44
+ purged: "purged";
45
+ reinstated: "reinstated";
46
+ restored: "restored";
47
+ suspended: "suspended";
48
+ }>;
49
+ actorType: z.ZodEnum<{
50
+ "control-plane": "control-plane";
51
+ system: "system";
52
+ user: "user";
53
+ }>;
54
+ actorId: z.ZodNullable<z.ZodString>;
55
+ reason: z.ZodNullable<z.ZodString>;
56
+ suspendedUntil: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
57
+ step: z.ZodNullable<z.ZodString>;
58
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
59
+ }, z.core.$strip>;
60
+ export type UserLifecycleEvent = z.output<typeof UserLifecycleEvent>;
61
+ //# sourceMappingURL=userLifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userLifecycle.d.ts","sourceRoot":"","sources":["../../src/data/userLifecycle.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;;GAeG;AAEH,oCAAoC;AACpC,eAAO,MAAM,mBAAmB;;;;;;;EAI7B,CAAC;AACJ,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEvE,+BAA+B;AAC/B,eAAO,MAAM,sBAAsB;;;;EAIhC,CAAC;AACJ,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE7E,iCAAiC;AACjC,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;iBAsC5B,CAAC;AACJ,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,kBAAkB,CAAC,CAAC"}
@@ -0,0 +1,50 @@
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/userLifecycle.ts
6
+ /**
7
+ * `pithy_auth_user_lifecycle` — every transition an account went through, who made it, and why.
8
+ *
9
+ * **The columns on `pithy_auth_users` answer "what is true now"; this table answers "what happened, and who
10
+ * did it".** The two are written together by `../lifecycle/transitions.ts` and never apart. The columns are
11
+ * what enforcement reads on every request, so they hold only the current state; the reason an operator gave
12
+ * for a suspension, and the history of every reinstatement before it, live here.
13
+ *
14
+ * **No foreign key to the user, deliberately.** A purge erases the user row and every row hanging off it, and
15
+ * this table is the one record that must survive it: the trail that the account existed, was deleted, and
16
+ * was erased, by whom and when. A cascade would take the evidence with the subject. So the row names the user
17
+ * by id and holds nothing else about them — no address, no name — and is the only `pithy_auth_*` row a purge
18
+ * leaves behind.
19
+ *
20
+ * Written by the kit through its own Kysely, so its dates take the house ms-epoch `SQLiteDate`.
21
+ */
22
+ /** What happened to the account. */
23
+ const UserLifecycleAction = z.enum([
24
+ "suspended",
25
+ "reinstated",
26
+ "deleted",
27
+ "restored",
28
+ "purge_step",
29
+ "purged"
30
+ ]).describe("The transition: `suspended` and `reinstated`; `deleted` (by an operator, or by the account's owner) and `restored` inside the purge window; `purge_step`, one capability's rows erased during a purge, named in `step`; and `purged`, the erasure finished.");
31
+ /** Who made the transition. */
32
+ const UserLifecycleActorType = z.enum([
33
+ "control-plane",
34
+ "user",
35
+ "system"
36
+ ]).describe("Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder, deleting their own account), or `system` (the scheduled purge, with nobody calling).");
37
+ /** One transition, as stored. */
38
+ const UserLifecycleEvent = z.object({
39
+ id: z.number().int().describe("Primary key. Auto-incrementing, so a user's history reads in the order it was written."),
40
+ userId: z.string().describe("The account this happened to. Not a foreign key: the row outlives the user it names, because a purge must leave its own record behind. Indexed."),
41
+ action: UserLifecycleAction.describe("What happened to the account."),
42
+ actorType: UserLifecycleActorType.describe("Who made the transition."),
43
+ actorId: z.string().nullable().describe("The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none."),
44
+ reason: z.string().nullable().describe("Why, in the words of whoever made the transition. For a suspension this is the sentence the locked-out person is shown, so it is written for them. Null for a transition nobody had to justify — a purge, a self-service deletion."),
45
+ suspendedUntil: SQLiteDate.nullable().describe("For a `suspended` row, when that suspension ends by itself; null for one that lasts until a reinstatement, and for every other action. Ms-epoch in SQLite."),
46
+ step: z.string().nullable().describe("For a `purge_step` row, the capability whose rows that step erased — the purge's step name. Null for every other action."),
47
+ createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code.")
48
+ }).describe("One transition in `pithy_auth_user_lifecycle`: an account suspended, reinstated, deleted, restored or purged, with who did it and why.");
49
+ //#endregion
50
+ export { UserLifecycleAction, UserLifecycleActorType, UserLifecycleEvent };
@@ -27,7 +27,7 @@ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/sc
27
27
  * every legitimate management call, permanently, and **no credential could fix it** — there is no user
28
28
  * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
29
29
  *
30
- * ## Five scopes, because these are five different blast radii
30
+ * ## Eight scopes, because these are eight different blast radii
31
31
  *
32
32
  * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
33
33
  * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
@@ -84,9 +84,31 @@ export declare const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope;
84
84
  * push token go with it.
85
85
  */
86
86
  export declare const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope;
87
+ /**
88
+ * Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
89
+ * operation on one person, and reversible — which is what separates it from deleting them, and why it is
90
+ * granted apart from both reading them and erasing them.
91
+ */
92
+ export declare const AUTH_USERS_SUSPEND_SCOPE: ControlPlaneScope;
93
+ /**
94
+ * Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
95
+ * one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
96
+ * gone from every capability that held them.
97
+ */
98
+ export declare const AUTH_USERS_DELETE_SCOPE: ControlPlaneScope;
99
+ /**
100
+ * Export everything the kit holds about one account — the answer to an access request (#620, the route in
101
+ * #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
102
+ * them, so it is granted on its own and audited as one.
103
+ */
104
+ export declare const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope;
87
105
  /**
88
106
  * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
89
107
  * and the list a manifest or a doc quotes rather than re-typing.
108
+ *
109
+ * **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
110
+ * export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
111
+ * one name each rather than three issues each choosing their own.
90
112
  */
91
113
  export declare const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[];
92
114
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAA0C,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,EAAE,iBAAyC,CAAC;AAElF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,EAAE,SAAS,iBAAiB,EAMjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAuC9D"}
1
+ {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAA0C,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,EAAE,iBAAyC,CAAC;AAElF;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,EAAE,iBAAwC,CAAC;AAEhF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,EAAE,SAAS,iBAAiB,EASjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAuC9D"}
@@ -26,7 +26,7 @@
26
26
  * every legitimate management call, permanently, and **no credential could fix it** — there is no user
27
27
  * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
28
28
  *
29
- * ## Five scopes, because these are five different blast radii
29
+ * ## Eight scopes, because these are eight different blast radii
30
30
  *
31
31
  * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
32
32
  * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
@@ -84,15 +84,40 @@ const AUTH_USERS_LOGOUT_SCOPE = "auth:users:logout";
84
84
  */
85
85
  const AUTH_DEVICES_REVOKE_SCOPE = "auth:devices:revoke";
86
86
  /**
87
+ * Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
88
+ * operation on one person, and reversible — which is what separates it from deleting them, and why it is
89
+ * granted apart from both reading them and erasing them.
90
+ */
91
+ const AUTH_USERS_SUSPEND_SCOPE = "auth:users:suspend";
92
+ /**
93
+ * Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
94
+ * one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
95
+ * gone from every capability that held them.
96
+ */
97
+ const AUTH_USERS_DELETE_SCOPE = "auth:users:delete";
98
+ /**
99
+ * Export everything the kit holds about one account — the answer to an access request (#620, the route in
100
+ * #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
101
+ * them, so it is granted on its own and audited as one.
102
+ */
103
+ const AUTH_USERS_EXPORT_SCOPE = "auth:users:export";
104
+ /**
87
105
  * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
88
106
  * and the list a manifest or a doc quotes rather than re-typing.
107
+ *
108
+ * **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
109
+ * export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
110
+ * one name each rather than three issues each choosing their own.
89
111
  */
90
112
  const AUTH_CONTROL_PLANE_SCOPES = [
91
113
  AUTH_USERS_READ_SCOPE,
92
114
  AUTH_DEVICES_READ_SCOPE,
93
115
  AUTH_SESSIONS_REVOKE_SCOPE,
94
116
  AUTH_USERS_LOGOUT_SCOPE,
95
- AUTH_DEVICES_REVOKE_SCOPE
117
+ AUTH_DEVICES_REVOKE_SCOPE,
118
+ AUTH_USERS_SUSPEND_SCOPE,
119
+ AUTH_USERS_DELETE_SCOPE,
120
+ AUTH_USERS_EXPORT_SCOPE
96
121
  ];
97
122
  /**
98
123
  * Auth's management surface, as `GET /control-plane/manifest` reports it.
@@ -147,4 +172,4 @@ function authAdminRoutes(basePath) {
147
172
  ];
148
173
  }
149
174
  //#endregion
150
- export { AUTH_CONTROL_PLANE_SCOPES, AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE, authAdminRoutes };
175
+ export { AUTH_CONTROL_PLANE_SCOPES, AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_DELETE_SCOPE, AUTH_USERS_EXPORT_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE, AUTH_USERS_SUSPEND_SCOPE, authAdminRoutes };
@@ -0,0 +1,18 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ /** Whether a refused account's credential may still reach this Better Auth endpoint (path relative to `basePath`). */
5
+ export declare function admitsRefusedAccount(path: string): boolean;
6
+ /**
7
+ * The redirect a refused magic link answers with: back to the screen the link named, carrying the code as
8
+ * `?error=`, exactly as Better Auth's own `redirectWithError` does for the refusals it raises itself
9
+ * (`plugins/magic-link/index.mjs`). `null` when the target is not one this Worker trusts, and the caller
10
+ * answers the refusal as JSON instead.
11
+ *
12
+ * A browser following a magic link is mid-navigation, so a 403 body would strand it on the API's origin
13
+ * with nothing to read; the adopter's screen is where the copy for this state lives. Better Auth has already
14
+ * checked the URLs by the time a session is refused, so the trust check is defense in depth — a refusal must
15
+ * not become an open redirect.
16
+ */
17
+ export declare function lifecycleRedirect(requestUrl: URL, baseURL: string, trustedOrigins: readonly string[], refusal: PithyError): Response | null;
18
+ //# sourceMappingURL=lifecycleGate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycleGate.d.ts","sourceRoot":"","sources":["../../src/http/lifecycleGate.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AA8BtE,sHAAsH;AACtH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAG1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,GAAG,EACf,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,OAAO,EAAE,UAAU,GAClB,QAAQ,GAAG,IAAI,CAYjB"}
@@ -0,0 +1,75 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/http/lifecycleGate.ts
4
+ /**
5
+ * Where a suspended or deleted account meets Better Auth's own endpoints (#620).
6
+ *
7
+ * The session middleware refuses such an account an `AuthContext`, which closes every kit route. Better Auth's
8
+ * catch-all is the one place that does not ask: it resolves the session itself, so `/token` would mint a fresh
9
+ * access token for an account the rest of the Worker refuses. `handleBetterAuth` therefore refuses the
10
+ * middleware's verdict here too — everywhere except the endpoints below.
11
+ */
12
+ /**
13
+ * The endpoints that never act as the account the presented credential names, relative to `basePath`.
14
+ *
15
+ * Signing out must always work. And each of the rest *starts* a session rather than using one, so a stale
16
+ * cookie a suspended person left on a shared machine must not stop somebody else signing in — the session
17
+ * that results is checked where it is created, in `session.create.before`. Everything else is refused by
18
+ * default: an endpoint nobody listed may be one a plugin added, and an account that may not act may not act
19
+ * there either.
20
+ */
21
+ const ADMITTED_PREFIXES = [
22
+ "/sign-out",
23
+ "/sign-in/",
24
+ "/magic-link/verify",
25
+ "/email-otp/",
26
+ "/callback/",
27
+ "/oauth2/callback/"
28
+ ];
29
+ const ADMITTED_EXACT = /* @__PURE__ */ new Set([
30
+ "/jwks",
31
+ "/ok",
32
+ "/error"
33
+ ]);
34
+ /** Whether a refused account's credential may still reach this Better Auth endpoint (path relative to `basePath`). */
35
+ function admitsRefusedAccount(path) {
36
+ if (ADMITTED_EXACT.has(path)) return true;
37
+ return ADMITTED_PREFIXES.some((prefix) => path === prefix || path.startsWith(prefix));
38
+ }
39
+ /**
40
+ * The redirect a refused magic link answers with: back to the screen the link named, carrying the code as
41
+ * `?error=`, exactly as Better Auth's own `redirectWithError` does for the refusals it raises itself
42
+ * (`plugins/magic-link/index.mjs`). `null` when the target is not one this Worker trusts, and the caller
43
+ * answers the refusal as JSON instead.
44
+ *
45
+ * A browser following a magic link is mid-navigation, so a 403 body would strand it on the API's origin
46
+ * with nothing to read; the adopter's screen is where the copy for this state lives. Better Auth has already
47
+ * checked the URLs by the time a session is refused, so the trust check is defense in depth — a refusal must
48
+ * not become an open redirect.
49
+ */
50
+ function lifecycleRedirect(requestUrl, baseURL, trustedOrigins, refusal) {
51
+ const named = requestUrl.searchParams.get("errorCallbackURL") || requestUrl.searchParams.get("callbackURL") || "/";
52
+ let target;
53
+ try {
54
+ target = new URL(named, baseURL);
55
+ } catch {
56
+ return null;
57
+ }
58
+ if (!(/* @__PURE__ */ new Set([new URL(baseURL).origin, ...trustedOrigins.flatMap((origin) => originOf(origin))])).has(target.origin)) return null;
59
+ target.searchParams.set("error", refusal.payload.code);
60
+ return new Response(null, {
61
+ status: 302,
62
+ headers: { location: target.toString() }
63
+ });
64
+ }
65
+ /** An origin's canonical form, or nothing for an entry that is not a URL (a bare deep-link scheme). */
66
+ function originOf(value) {
67
+ try {
68
+ const origin = new URL(value).origin;
69
+ return origin === "null" ? [] : [origin];
70
+ } catch {
71
+ return [];
72
+ }
73
+ }
74
+ //#endregion
75
+ export { admitsRefusedAccount, lifecycleRedirect };
@@ -7,6 +7,11 @@ export declare function createSessionMiddleware(wiring: AuthWiring): PithyMiddle
7
7
  /**
8
8
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
9
9
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
10
+ *
11
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
12
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
13
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
14
+ * middleware's, remembered for this request; this guard only raises it.
10
15
  */
11
16
  export declare function requireAuth(): MiddlewareHandler<PithyHonoEnv>;
12
17
  //# sourceMappingURL=middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA0DrF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAqB3E;AA2CD;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA6DrF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAqB3E;AA4FD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAY7D"}
@@ -1,8 +1,11 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { getAuthInstance } from "./resolve.js";
3
+ import { authDatabase } from "../data/tables.js";
4
+ import { LifecycleColumns } from "../lifecycle/state.js";
5
+ import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce.js";
6
+ import { getAuthInstance, resolveDb } from "./resolve.js";
4
7
  import { withResignedCredentials } from "./credentialResign.js";
5
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
8
+ import { InternalError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
9
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
7
10
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
8
11
  //#region src/http/middleware.ts
@@ -74,6 +77,11 @@ async function resolveSession(c, wiring, instance) {
74
77
  try {
75
78
  const session = await instance.api.getSession({ headers });
76
79
  if (session) {
80
+ const refusal = await standingRefusal(c, wiring, session.user);
81
+ if (refusal) {
82
+ noteRefusal(c, refusal);
83
+ return;
84
+ }
77
85
  const scopes = await resolvedScopes(c, wiring.resolveScopes, {
78
86
  userId: session.user.id,
79
87
  sessionId: session.session.id
@@ -90,15 +98,48 @@ async function resolveSession(c, wiring, instance) {
90
98
  } catch {}
91
99
  }
92
100
  /**
101
+ * The refusal for the session's account, or `null` when it may act.
102
+ *
103
+ * **A check that cannot be made refuses**, rather than throwing into `resolveSession`'s catch. That catch
104
+ * leaves `auth` null and notes nothing, and `handleBetterAuth` only refuses on a noted verdict — so a failed
105
+ * read of a suspension's reason, or a column that will not decode, would let Better Auth's own `/token` mint a
106
+ * JWT for the suspended account it resolved on its own. So the failure is logged and becomes the verdict: a
107
+ * 500, since the fault is this Worker's, and every door that honors a lifecycle refusal honors this one.
108
+ */
109
+ async function standingRefusal(c, wiring, user) {
110
+ try {
111
+ return await lifecycleRefusalFor(authDatabase(resolveDb(c.env, wiring.config.database)), user.id, LifecycleColumns.parse(user), /* @__PURE__ */ new Date());
112
+ } catch (cause) {
113
+ c.var.log?.child("auth").warn("the account's standing could not be checked; the request is refused", {
114
+ userId: user.id,
115
+ reason: cause instanceof Error ? cause.message : String(cause)
116
+ });
117
+ return new InternalError({
118
+ message: "This account could not be checked. Try again shortly.",
119
+ action: "Check the auth database binding and that the auth migrations have run.",
120
+ detail: `lifecycle check for user ${user.id} failed`
121
+ }, { cause });
122
+ }
123
+ }
124
+ /**
93
125
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
94
126
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
127
+ *
128
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
129
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
130
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
131
+ * middleware's, remembered for this request; this guard only raises it.
95
132
  */
96
133
  function requireAuth() {
97
134
  return async (c, next) => {
98
- if (!c.var.auth) throw new UnauthorizedError({
99
- message: "Authentication required.",
100
- action: "Sign in and retry with a valid session or bearer token."
101
- });
135
+ if (!c.var.auth) {
136
+ const refusal = noticedRefusal(c);
137
+ if (refusal) throw refusal;
138
+ throw new UnauthorizedError({
139
+ message: "Authentication required.",
140
+ action: "Sign in and retry with a valid session or bearer token."
141
+ });
142
+ }
102
143
  await next();
103
144
  };
104
145
  }
@@ -1 +1 @@
1
- {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAiLD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
1
+ {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AA2LD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
@@ -153,6 +153,14 @@ const PROVIDER_REFUSAL_VERDICTS = {
153
153
  collapse: true,
154
154
  why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow."
155
155
  },
156
+ "auth/account_suspended": {
157
+ collapse: false,
158
+ why: "The kit's own `session.create.before` hook (instance/auth.ts, #620). A session is only ever created for a user the callback has already resolved and linked — the caller has just proved control of a provider identity bound to this account — so the code is told to its holder, never to somebody probing an address. Collapsing it would leave a suspended person with a screen that says nothing happened."
159
+ },
160
+ "auth/account_deleted": {
161
+ collapse: false,
162
+ why: "The same hook, for an account inside its purge window, and the same reasoning: it is reached only after the caller authenticated as the account, so it names the state of their own account to them."
163
+ },
156
164
  no_code: {
157
165
  collapse: false,
158
166
  why: "The provider came back without a code. The shape of the request itself, settled before any lookup."
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAsB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAuB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { authDatabase } from "../data/tables.js";
4
4
  import { baseURLResolver } from "./baseUrl.js";
5
- import { resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecrets } from "../instance/secrets.js";
5
+ import { resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveMicrosoftCredentials, resolveSessionSecrets } from "../instance/secrets.js";
6
6
  import { makeSendAuthEmail } from "../email/send.js";
7
7
  import { resolveProvider } from "../instance/providers.js";
8
8
  import { makeAuth } from "../instance/auth.js";
@@ -63,12 +63,13 @@ async function buildAuthInstance(c, wiring) {
63
63
  detail: "auth.compose did not resolve the email enqueue seam; ensure email() is composed."
64
64
  });
65
65
  const env = c.env;
66
- const [sessionSecrets, google, apple, facebook, github] = await Promise.all([
66
+ const [sessionSecrets, google, apple, facebook, github, microsoft] = await Promise.all([
67
67
  resolveSessionSecrets(env),
68
68
  resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
69
69
  resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
70
70
  resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
71
- resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env))
71
+ resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
72
+ resolveProvider(cfg.microsoft.enabled, () => resolveMicrosoftCredentials(env))
72
73
  ]);
73
74
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
74
75
  const d1 = resolveDb(c.env, cfg.database);
@@ -98,6 +99,7 @@ async function buildAuthInstance(c, wiring) {
98
99
  apple,
99
100
  facebook,
100
101
  github,
102
+ microsoft,
101
103
  sendEmail: makeSendAuthEmail((input) => enqueueEmail(env, input), expiresMinutes, recipientLocale(c, authDatabase(resolveDb(c.env, cfg.database)))),
102
104
  sessionExpiresIn: cfg.sessionExpiresIn,
103
105
  sessionUpdateAge: cfg.sessionUpdateAge,
@@ -108,7 +110,8 @@ async function buildAuthInstance(c, wiring) {
108
110
  google: cfg.google.allowSignUp,
109
111
  apple: cfg.apple.allowSignUp,
110
112
  facebook: cfg.facebook.allowSignUp,
111
- github: cfg.github.allowSignUp
113
+ github: cfg.github.allowSignUp,
114
+ microsoft: cfg.microsoft.allowSignUp
112
115
  },
113
116
  ...wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {},
114
117
  emit: (event) => c.var.emit(event),
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAQ7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuHtF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAQ7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAwChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuHtF"}
@@ -4,6 +4,8 @@ import { authDatabase } from "../data/tables.js";
4
4
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit.js";
5
5
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry.js";
6
6
  import { requireFreshAuthentication } from "./providerFreshness.js";
7
+ import { isLifecycleRefusal } from "../lifecycle/state.js";
8
+ import { noticedRefusal } from "../lifecycle/enforce.js";
7
9
  import { PROFILE_IMAGE_PATH } from "../profile/profile.js";
8
10
  import { collapseProviderRefusal } from "./providerRefusal.js";
9
11
  import { getAuthInstance, resolveDb } from "./resolve.js";
@@ -14,6 +16,7 @@ import { RevokeDeviceBody } from "./schemas.js";
14
16
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
15
17
  import { guardErrorCallbackURL } from "./errorCallbackUrl.js";
16
18
  import { apiErrorToPithy } from "./errors.js";
19
+ import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate.js";
17
20
  import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
18
21
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
19
22
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
@@ -197,12 +200,26 @@ async function auditRefusal(c, response) {
197
200
  */
198
201
  async function handleBetterAuth(c, wiring) {
199
202
  const instance = await getAuthInstance(c, wiring);
203
+ const pathname = new URL(c.req.raw.url).pathname;
204
+ const refusal = noticedRefusal(c);
205
+ if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
200
206
  const request = await guardErrorCallbackURL(c.req.raw, c.req.raw.url);
201
207
  let response;
202
208
  try {
203
209
  response = await instance.handler(request);
204
210
  } catch (error) {
205
- throw apiErrorToPithy(error);
211
+ const pithy = apiErrorToPithy(error);
212
+ if (isLifecycleRefusal(pithy)) {
213
+ if (isSignInAttempt(pathname)) await emitDenied(c.var.emit, {
214
+ ...correlation(c.req.raw.headers),
215
+ detail: pithy.payload.code
216
+ });
217
+ if (c.req.method === "GET" && pathname === `${wiring.config.basePath}/magic-link/verify`) {
218
+ const redirect = lifecycleRedirect(new URL(request.url), wiring.config.baseURL, wiring.config.trustedOrigins, pithy);
219
+ if (redirect) return redirect;
220
+ }
221
+ }
222
+ throw pithy;
206
223
  }
207
224
  const collapsed = collapseProviderRefusal(c.req.raw.url, response);
208
225
  if (collapsed) {
@@ -272,6 +289,8 @@ async function rotateToken(c, wiring) {
272
289
  action: "Present a valid session or bearer token to rotate."
273
290
  });
274
291
  }
292
+ const refusal = noticedRefusal(c);
293
+ if (refusal) throw refusal;
275
294
  const ip = headers.get("cf-connecting-ip") ?? void 0;
276
295
  const userAgent = headers.get("user-agent") ?? void 0;
277
296
  const session = current.session;