@pithy-sh/auth 0.10.0 → 0.11.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 (116) hide show
  1. package/README.md +1 -1
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +19 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +20 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +1 -1
  9. package/dist/capability.d.ts +19 -0
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +20 -3
  12. package/dist/data/tables.d.ts +1 -0
  13. package/dist/data/tables.d.ts.map +1 -1
  14. package/dist/data/userLifecycle.d.ts +1 -0
  15. package/dist/data/userLifecycle.d.ts.map +1 -1
  16. package/dist/data/userLifecycle.js +2 -1
  17. package/dist/http/adminRoutes.d.ts.map +1 -1
  18. package/dist/http/adminRoutes.js +270 -5
  19. package/dist/http/guards.d.ts +8 -7
  20. package/dist/http/guards.d.ts.map +1 -1
  21. package/dist/http/guards.js +38 -7
  22. package/dist/http/middleware.d.ts +25 -1
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +44 -3
  25. package/dist/http/responses.d.ts +180 -0
  26. package/dist/http/responses.d.ts.map +1 -1
  27. package/dist/http/responses.js +142 -1
  28. package/dist/http/routes.d.ts +1 -0
  29. package/dist/http/routes.d.ts.map +1 -1
  30. package/dist/http/routes.js +45 -3
  31. package/dist/http/schemas.d.ts +57 -0
  32. package/dist/http/schemas.d.ts.map +1 -1
  33. package/dist/http/schemas.js +51 -1
  34. package/dist/http/views.d.ts +39 -2
  35. package/dist/http/views.d.ts.map +1 -1
  36. package/dist/http/views.js +105 -1
  37. package/dist/instance/auth.d.ts.map +1 -1
  38. package/dist/instance/auth.js +2 -2
  39. package/dist/lifecycle/audited.d.ts +48 -0
  40. package/dist/lifecycle/audited.d.ts.map +1 -0
  41. package/dist/lifecycle/audited.js +65 -0
  42. package/dist/lifecycle/enforce.d.ts +37 -2
  43. package/dist/lifecycle/enforce.d.ts.map +1 -1
  44. package/dist/lifecycle/enforce.js +46 -5
  45. package/dist/lifecycle/reason.d.ts +11 -0
  46. package/dist/lifecycle/reason.d.ts.map +1 -0
  47. package/dist/lifecycle/reason.js +13 -0
  48. package/dist/lifecycle/request.d.ts +5 -2
  49. package/dist/lifecycle/request.d.ts.map +1 -1
  50. package/dist/lifecycle/request.js +6 -2
  51. package/dist/lifecycle/transitions.d.ts +158 -18
  52. package/dist/lifecycle/transitions.d.ts.map +1 -1
  53. package/dist/lifecycle/transitions.js +344 -70
  54. package/dist/migrations/0005_purge_once.d.ts +22 -0
  55. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  56. package/dist/migrations/0005_purge_once.js +35 -0
  57. package/dist/migrations/pluginTables.d.ts +8 -0
  58. package/dist/migrations/pluginTables.d.ts.map +1 -1
  59. package/dist/migrations/pluginTables.js +8 -1
  60. package/dist/migrations/set.d.ts +2 -1
  61. package/dist/migrations/set.d.ts.map +1 -1
  62. package/dist/migrations/set.js +4 -2
  63. package/dist/purge/contribution.d.ts +47 -0
  64. package/dist/purge/contribution.d.ts.map +1 -0
  65. package/dist/purge/contribution.js +141 -0
  66. package/dist/purge/retryPolicy.d.ts +22 -0
  67. package/dist/purge/retryPolicy.d.ts.map +1 -0
  68. package/dist/purge/retryPolicy.js +26 -0
  69. package/dist/purge/run.d.ts +88 -0
  70. package/dist/purge/run.d.ts.map +1 -0
  71. package/dist/purge/run.js +102 -0
  72. package/dist/purge/specs.d.ts +71 -0
  73. package/dist/purge/specs.d.ts.map +1 -0
  74. package/dist/purge/specs.js +72 -0
  75. package/dist/purge/start.d.ts +42 -0
  76. package/dist/purge/start.d.ts.map +1 -0
  77. package/dist/purge/start.js +37 -0
  78. package/dist/purge/workflow.d.ts +58 -0
  79. package/dist/purge/workflow.d.ts.map +1 -0
  80. package/dist/purge/workflow.js +96 -0
  81. package/dist/test-utils/accountFootprint.d.ts +10 -0
  82. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  83. package/dist/test-utils/accountFootprint.js +44 -0
  84. package/dist/version.generated.d.ts +1 -1
  85. package/dist/version.generated.js +1 -1
  86. package/docs/account-lifecycle.md +123 -11
  87. package/package.json +5 -5
  88. package/pithy.manifest.json +1 -1
  89. package/src/audit/actions.ts +19 -0
  90. package/src/audit/emit.ts +3 -1
  91. package/src/capability.ts +48 -1
  92. package/src/data/userLifecycle.ts +4 -1
  93. package/src/http/adminRoutes.ts +398 -2
  94. package/src/http/guards.ts +39 -7
  95. package/src/http/middleware.ts +45 -2
  96. package/src/http/responses.ts +245 -0
  97. package/src/http/routes.ts +55 -3
  98. package/src/http/schemas.ts +110 -0
  99. package/src/http/views.ts +147 -2
  100. package/src/instance/auth.ts +7 -2
  101. package/src/lifecycle/audited.ts +104 -0
  102. package/src/lifecycle/enforce.ts +55 -5
  103. package/src/lifecycle/reason.ts +11 -0
  104. package/src/lifecycle/request.ts +10 -2
  105. package/src/lifecycle/transitions.ts +482 -93
  106. package/src/migrations/0005_purge_once.ts +42 -0
  107. package/src/migrations/pluginTables.ts +19 -1
  108. package/src/migrations/set.ts +3 -1
  109. package/src/purge/contribution.ts +191 -0
  110. package/src/purge/retryPolicy.ts +26 -0
  111. package/src/purge/run.ts +185 -0
  112. package/src/purge/specs.ts +95 -0
  113. package/src/purge/start.ts +79 -0
  114. package/src/purge/workflow.ts +144 -0
  115. package/src/test-utils/accountFootprint.ts +95 -0
  116. package/src/version.generated.ts +1 -1
@@ -0,0 +1,104 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { emitControlPlaneAction } from "../audit/emit";
7
+
8
+ /**
9
+ * Every control-plane lifecycle call is audited, including the ones that changed nothing (#621).
10
+ *
11
+ * A transition that moves the account writes its own audit event, beside the history row, in
12
+ * `./transitions.ts`. That leaves two kinds of call with no event, and both matter to somebody reading the
13
+ * trail after an incident: **a refusal** — an unknown account, a deleted one, an end in the past — which says
14
+ * a credential was trying, and **a call that found the account already where it asked to put it**, which
15
+ * says somebody pressed the button. This records both, under the same action as the transition, so one
16
+ * filter finds every attempt: a refusal is `denied` (or `failure` for a fault) with the code, and a no-op is
17
+ * a `success` with `changed: false`. A refusal is still thrown, unchanged.
18
+ *
19
+ * A body the route's validator refuses never reaches the call, so the route records it with
20
+ * {@link recordLifecycleRefusal}, on the same event, before the 400 is thrown.
21
+ */
22
+
23
+ /** Who called, about whom, and why — what every lifecycle audit event carries. */
24
+ export interface LifecycleCall {
25
+ /** The audit action the transition writes when it moves the account. */
26
+ readonly action: string;
27
+ /** The management client's verified `sub`: which person acted. */
28
+ readonly subject: string;
29
+ /** The connection the call came through. */
30
+ readonly connectionId: string;
31
+ /** The account acted on. */
32
+ readonly userId: string;
33
+ /** The reason the caller gave — `null` for a refused body that carried none. */
34
+ readonly reason: string | null;
35
+ /** The request's correlation. */
36
+ readonly ip?: string | undefined;
37
+ readonly userAgent?: string | undefined;
38
+ readonly requestId?: string | undefined;
39
+ }
40
+
41
+ /** The public code of a thrown error, or `core/internal` for anything that is not a `PithyError`. */
42
+ function codeOf(error: unknown): string {
43
+ return error instanceof PithyError ? error.payload.code : "core/internal";
44
+ }
45
+
46
+ /** A refusal this Worker made on purpose is `denied`; a fault, a 5xx or a throw that is not ours, `failure`. */
47
+ function outcomeOf(error: unknown): "denied" | "failure" {
48
+ return error instanceof PithyError && error.payload.status < 500 ? "denied" : "failure";
49
+ }
50
+
51
+ /** The event every lifecycle audit record shares, before its outcome and metadata. */
52
+ function eventOf(call: LifecycleCall) {
53
+ return {
54
+ action: call.action,
55
+ subject: call.subject,
56
+ connectionId: call.connectionId,
57
+ resourceType: "user",
58
+ resourceId: call.userId,
59
+ ip: call.ip,
60
+ userAgent: call.userAgent,
61
+ requestId: call.requestId,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Record one refused lifecycle call — `denied` with its code, or `failure` for a fault. `code` names the
67
+ * refusal when the thrown error carries none of its own, as a body Hono could not parse does not.
68
+ */
69
+ export async function recordLifecycleRefusal(
70
+ emit: AuditEmit,
71
+ call: LifecycleCall,
72
+ error: unknown,
73
+ fallback?: { code: string; outcome: "denied" | "failure" },
74
+ ): Promise<void> {
75
+ const ours = error instanceof PithyError;
76
+ await emitControlPlaneAction(emit, {
77
+ ...eventOf(call),
78
+ outcome: ours || !fallback ? outcomeOf(error) : fallback.outcome,
79
+ metadata: { reason: call.reason, changed: false, code: ours || !fallback ? codeOf(error) : fallback.code },
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Run one lifecycle call and audit whatever the transition did not. `unchanged` says whether a result is a
85
+ * call that changed nothing; the event for a call that did change something is the transition's own.
86
+ */
87
+ export async function auditedLifecycleCall<T>(
88
+ emit: AuditEmit,
89
+ call: LifecycleCall,
90
+ run: () => Promise<T>,
91
+ unchanged: (result: T) => boolean,
92
+ ): Promise<T> {
93
+ let result: T;
94
+ try {
95
+ result = await run();
96
+ } catch (error) {
97
+ await recordLifecycleRefusal(emit, call, error);
98
+ throw error;
99
+ }
100
+ if (unchanged(result)) {
101
+ await emitControlPlaneAction(emit, { ...eventOf(call), metadata: { reason: call.reason, changed: false } });
102
+ }
103
+ return result;
104
+ }
@@ -68,6 +68,14 @@ export async function lifecycleRefusalFor(
68
68
  return lifecycleRefusal(userId, standing, reason);
69
69
  }
70
70
 
71
+ /** The holder of a refused credential: whose session it is. Known because the credential itself is genuine. */
72
+ export interface RefusedHolder {
73
+ /** The account the session belongs to. */
74
+ readonly userId: string;
75
+ /** The session the request presented. */
76
+ readonly sessionId: string;
77
+ }
78
+
71
79
  /**
72
80
  * The refusal the session middleware reached for this request, keyed by the request's context.
73
81
  *
@@ -75,15 +83,57 @@ export async function lifecycleRefusalFor(
75
83
  * capability's own guards read — a refused account already has no `AuthContext`, which is the part every
76
84
  * other capability's guard needs. Keyed by the context the way `../http/resolve.ts` caches the instance, so
77
85
  * it dies with the request.
86
+ *
87
+ * **The holder rides with it (#622).** A suspended account may still delete itself — the app stores require
88
+ * that a person can always leave — and that one route has to know whose account the refused credential
89
+ * opens. Nothing else reads it: the holder is reachable only through `accountHolder`, and only that route uses it.
78
90
  */
79
- const refusals = new WeakMap<object, PithyError>();
91
+ const refusals = new WeakMap<object, { refusal: PithyError; holder: RefusedHolder | undefined }>();
80
92
 
81
- /** Remember that this request's credential belongs to an account that may not act. */
82
- export function noteRefusal(context: object, refusal: PithyError): void {
83
- refusals.set(context, refusal);
93
+ /** Remember that this request's credential belongs to an account that may not act, and whose it is. */
94
+ export function noteRefusal(context: object, refusal: PithyError, holder?: RefusedHolder): void {
95
+ refusals.set(context, { refusal, holder });
84
96
  }
85
97
 
86
98
  /** The refusal the session middleware reached for this request, if it reached one. */
87
99
  export function noticedRefusal(context: object): PithyError | undefined {
88
- return refusals.get(context);
100
+ return refusals.get(context)?.refusal;
101
+ }
102
+
103
+ /**
104
+ * The holder of a **suspended** account's credential on this request, or `undefined` (#622).
105
+ *
106
+ * Only a suspension: a deleted account has nothing left to delete, and a check that could not be made has
107
+ * established nobody. The one reader is the self-service deletion, through `../http/middleware.ts`.
108
+ */
109
+ export function suspendedHolder(context: object): RefusedHolder | undefined {
110
+ const noted = refusals.get(context);
111
+ return noted?.refusal.payload.code === "auth/account_suspended" ? noted.holder : undefined;
112
+ }
113
+
114
+ /**
115
+ * The header a sign-in carries to ask for a session that can do nothing but delete its account, and the one
116
+ * value it takes (#622).
117
+ *
118
+ * A suspension revokes every session the account holds and refuses every new one, so without this a suspended
119
+ * person would hold no credential and could get none — and the one route a suspension leaves open, deleting the
120
+ * account, would be one nobody could reach. With it, the sign-in completes: the person still proves who they are,
121
+ * by the code, the link or the provider, exactly as for any sign-in. **The session that results is still a
122
+ * suspended account's**, so the session middleware refuses it everywhere, Better Auth's own endpoints included,
123
+ * and only `DELETE /auth/account` admits it. Nothing about the header is trusted beyond that: it asks for a
124
+ * session no more capable than none, save for leaving.
125
+ */
126
+ export const ACCOUNT_DELETION_INTENT_HEADER = "x-pithy-intent";
127
+ /** The value of `ACCOUNT_DELETION_INTENT_HEADER` that asks for a deletion-only session. */
128
+ export const ACCOUNT_DELETION_INTENT = "delete-account";
129
+
130
+ /**
131
+ * Whether a sign-in refused with `refusal` may still create its session: only a **suspended** account's, and only
132
+ * when the request asks for nothing but deleting it. A deleted account has nothing left to delete, and a check
133
+ * that could not be made has established nobody, so neither is admitted.
134
+ */
135
+ export function admitsDeletionSignIn(refusal: PithyError, headers: Headers | null | undefined): boolean {
136
+ if (refusal.payload.code !== "auth/account_suspended") return false;
137
+ const asked = headers?.get(ACCOUNT_DELETION_INTENT_HEADER)?.trim().toLowerCase();
138
+ return asked === ACCOUNT_DELETION_INTENT;
89
139
  }
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The longest reason the kit stores. It is shown to the person, so it is a sentence, not a case file.
6
+ *
7
+ * A leaf with no imports, because two programs read it: the transitions, which refuse a longer one, and the
8
+ * request schemas in `../http/schemas.ts`, which a browser program compiles (`tooling/browser-scopes`). Kept
9
+ * in `./transitions.ts`, it pulled the email capability and the Workers types into that program (#621).
10
+ */
11
+ export const MAX_REASON = 500;
@@ -7,7 +7,7 @@ import type { Context } from "hono";
7
7
  import type { AuthWiring } from "../capability";
8
8
  import { authDatabase } from "../data/tables";
9
9
  import { resolveDb } from "../http/resolve";
10
- import type { LifecycleDeps } from "./transitions";
10
+ import type { LifecycleAuditContext, LifecycleDeps } from "./transitions";
11
11
 
12
12
  /**
13
13
  * The transitions' dependencies, resolved from one request — what a lifecycle route hands `./transitions.ts`.
@@ -15,8 +15,15 @@ import type { LifecycleDeps } from "./transitions";
15
15
  * One function so every route resolves them the same way: this request's database, its audit seam and logger,
16
16
  * the composed email capability's enqueue bound to this request's env, and the adopter's hooks as `auth()` was
17
17
  * handed them. A route that assembled its own would be the second place a hook could be forgotten.
18
+ *
19
+ * `context` is what the caller adds to each audit event: the request's correlation, and for a management call
20
+ * the connection it came through. The caller passes it because only the caller knows who it is.
18
21
  */
19
- export function lifecycleDeps(c: Context<PithyHonoEnv>, wiring: AuthWiring): LifecycleDeps {
22
+ export function lifecycleDeps(
23
+ c: Context<PithyHonoEnv>,
24
+ wiring: AuthWiring,
25
+ context?: LifecycleAuditContext,
26
+ ): LifecycleDeps {
20
27
  const d1 = resolveDb(c.env, wiring.config.database);
21
28
  const enqueue = wiring.enqueueEmail;
22
29
  return {
@@ -27,5 +34,6 @@ export function lifecycleDeps(c: Context<PithyHonoEnv>, wiring: AuthWiring): Lif
27
34
  hooks: wiring.lifecycleHooks ?? {},
28
35
  enqueueEmail: enqueue ? (input) => enqueue(c.env as unknown as EmailEnqueueEnv, input) : undefined,
29
36
  log: c.var.log?.child("auth"),
37
+ ...(context ? { context } : {}),
30
38
  };
31
39
  }