@pithy-sh/auth 0.1.2 → 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.
Files changed (122) hide show
  1. package/dist/admin/users.d.ts +155 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +205 -0
  4. package/dist/audit/actions.d.ts +66 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +66 -0
  7. package/dist/audit/emit.d.ts +101 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +170 -0
  10. package/dist/capability.d.ts +60 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +169 -0
  13. package/dist/client/api.d.ts +299 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +385 -0
  16. package/dist/client/projection.d.ts +51 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +0 -0
  19. package/dist/data/betterAuth.d.ts +75 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +92 -0
  22. package/dist/data/device.d.ts +36 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +33 -0
  25. package/dist/data/kitFields.d.ts +78 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +77 -0
  28. package/dist/data/rotatedToken.d.ts +20 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +22 -0
  31. package/dist/data/tables.d.ts +104 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +30 -0
  34. package/dist/device/registry.d.ts +54 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +85 -0
  37. package/dist/email/send.d.ts +38 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +48 -0
  40. package/dist/http/adminRoutes.d.ts +9 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +274 -0
  43. package/dist/http/baseUrl.d.ts +41 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +96 -0
  46. package/dist/http/csrf.d.ts +18 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +81 -0
  49. package/dist/http/devLoginRoute.d.ts +42 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +112 -0
  52. package/dist/http/errors.d.ts +24 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +67 -0
  55. package/dist/http/guards.d.ts +103 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +148 -0
  58. package/dist/http/middleware.d.ts +17 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +47 -0
  61. package/dist/http/rateLimit.d.ts +17 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +31 -0
  64. package/dist/http/resolve.d.ts +9 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +92 -0
  67. package/dist/http/responses.d.ts +152 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +121 -0
  70. package/dist/http/routes.d.ts +34 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +268 -0
  73. package/dist/http/schemas.d.ts +66 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +59 -0
  76. package/dist/http/views.d.ts +53 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +86 -0
  79. package/dist/i18n/errorCopy.d.ts +24 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +31 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +33 -0
  84. package/dist/i18n/errorCopy.js +91 -0
  85. package/dist/index.d.ts +14 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +8 -0
  88. package/dist/instance/auth.d.ts +1122 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +176 -0
  91. package/dist/instance/plugins.d.ts +87 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +116 -0
  94. package/dist/instance/providers.d.ts +117 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +111 -0
  97. package/dist/instance/secrets.d.ts +163 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +169 -0
  100. package/dist/migrations/0001_init.d.ts +33 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +77 -0
  103. package/dist/migrations/pluginTables.d.ts +126 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +233 -0
  106. package/dist/seeds/devSession.d.ts +124 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +211 -0
  109. package/dist/seeds/example.d.ts +12 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +30 -0
  112. package/dist/test-utils/liveApp.d.ts +227 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +240 -0
  115. package/dist/token/rotation.d.ts +56 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +68 -0
  118. package/dist/version.generated.d.ts +5 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +7 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1,92 @@
1
+ import { authDatabase } from "../data/tables.js";
2
+ import { baseURLResolver } from "./baseUrl.js";
3
+ import { resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecret } from "../instance/secrets.js";
4
+ import { makeSendAuthEmail } from "../email/send.js";
5
+ import { resolveProvider } from "../instance/providers.js";
6
+ import { makeAuth } from "../instance/auth.js";
7
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
8
+ //#region src/http/resolve.ts
9
+ /**
10
+ * Build the Better-Auth instance for one request, memoized on the request context so the
11
+ * session-resolving middleware and the route handler share a single instance (one secret resolution,
12
+ * one construction). The instance closes over request-scoped state: the audit `emit` seam and the D1
13
+ * binding from `c.env`.
14
+ */
15
+ const cache = /* @__PURE__ */ new WeakMap();
16
+ /** Read the configured D1 binding by name from the worker env, or fail loudly (not a silent undefined). */
17
+ function resolveDb(env, bindingName) {
18
+ const binding = env[bindingName];
19
+ if (!binding) throw new InternalError({
20
+ message: "The auth database binding is missing.",
21
+ detail: `D1 binding "${bindingName}" is not present on the worker env`
22
+ });
23
+ return binding;
24
+ }
25
+ /**
26
+ * The language to write a sign-in email in, for one address.
27
+ *
28
+ * **The stored preference first, the request's negotiation second** (pithy-sh/pithy#441). Somebody who
29
+ * picked a language in a settings pane has said something durable about themselves; the device they are
30
+ * signing in from tonight has only sent an `Accept-Language`. But most of what this is asked about is a
31
+ * *first* sign-in, where no row exists yet — and that is precisely the message a project cannot afford
32
+ * to send in the wrong language, because passwordless has no password to fall back to. So the header's
33
+ * answer, which `@pithy-sh/i18n` has already matched against this project's supported set and put on
34
+ * `c.var.locale`, is what covers that case.
35
+ *
36
+ * One indexed lookup on a unique column, per sign-in email, and only for the two templates that send
37
+ * one. `null` when neither answers, which renders the kit's English — not the same statement as `en`.
38
+ *
39
+ * `c.var.locale` is null unless the i18n capability is composed, so a project that never opted in gets
40
+ * a resolver that reads a column nobody fills and returns null: the behavior it had before any of this.
41
+ */
42
+ function recipientLocale(c, db) {
43
+ return async (email) => {
44
+ return (await db.selectFrom("pithyAuthUsers").select("locale").where("email", "=", email).executeTakeFirst())?.locale ?? c.var.locale?.catalogLocale ?? null;
45
+ };
46
+ }
47
+ function getAuthInstance(c, wiring) {
48
+ const existing = cache.get(c);
49
+ if (existing) return existing;
50
+ const built = buildAuthInstance(c, wiring);
51
+ cache.set(c, built);
52
+ return built;
53
+ }
54
+ async function buildAuthInstance(c, wiring) {
55
+ const cfg = wiring.config;
56
+ const enqueueEmail = wiring.enqueueEmail;
57
+ if (!enqueueEmail) throw new InternalError({
58
+ message: "Authentication is misconfigured.",
59
+ detail: "auth.compose did not resolve the email enqueue seam; ensure email() is composed."
60
+ });
61
+ const env = c.env;
62
+ const [secret, google, apple, facebook, github] = await Promise.all([
63
+ resolveSessionSecret(env),
64
+ resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
65
+ resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
66
+ resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
67
+ resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env))
68
+ ]);
69
+ const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
70
+ return makeAuth({
71
+ db: authDatabase(resolveDb(c.env, cfg.database)),
72
+ secret,
73
+ baseURL: baseURLResolver(cfg.baseURL)(c.req.raw),
74
+ locale: c.var.locale?.catalogLocale ?? null,
75
+ basePath: cfg.basePath,
76
+ trustedOrigins: cfg.trustedOrigins,
77
+ google,
78
+ apple,
79
+ facebook,
80
+ github,
81
+ sendEmail: makeSendAuthEmail((input) => enqueueEmail(env, input), expiresMinutes, recipientLocale(c, authDatabase(resolveDb(c.env, cfg.database)))),
82
+ sessionExpiresIn: cfg.sessionExpiresIn,
83
+ sessionUpdateAge: cfg.sessionUpdateAge,
84
+ verificationExpiresIn: cfg.verificationExpiresIn,
85
+ otpLength: cfg.otpLength,
86
+ disableSignUp: cfg.disableSignUp,
87
+ emit: (event) => c.var.emit(event),
88
+ plugins: cfg.plugins
89
+ });
90
+ }
91
+ //#endregion
92
+ export { getAuthInstance, resolveDb };
@@ -0,0 +1,152 @@
1
+ import { z } from "zod";
2
+ /** A user as a management client may see them. */
3
+ export declare const AdminUserView: z.ZodObject<{
4
+ id: z.ZodString;
5
+ email: z.ZodString;
6
+ name: z.ZodString;
7
+ emailVerified: z.ZodBoolean;
8
+ image: z.ZodNullable<z.ZodString>;
9
+ locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ createdAt: z.ZodISODateTime;
11
+ updatedAt: z.ZodISODateTime;
12
+ }, z.core.$strip>;
13
+ export type AdminUserView = z.output<typeof AdminUserView>;
14
+ /** A session as a management client may see it — the token is not part of the contract. */
15
+ export declare const AdminSessionView: z.ZodObject<{
16
+ id: z.ZodString;
17
+ deviceId: z.ZodNullable<z.ZodString>;
18
+ ipAddress: z.ZodNullable<z.ZodString>;
19
+ userAgent: z.ZodNullable<z.ZodString>;
20
+ createdAt: z.ZodISODateTime;
21
+ updatedAt: z.ZodISODateTime;
22
+ expiresAt: z.ZodISODateTime;
23
+ }, z.core.$strip>;
24
+ export type AdminSessionView = z.output<typeof AdminSessionView>;
25
+ /** A registered device as a management client may see it — the push token is not part of the contract. */
26
+ export declare const AdminDeviceView: z.ZodObject<{
27
+ id: z.ZodString;
28
+ userId: z.ZodString;
29
+ platform: z.ZodEnum<{
30
+ android: "android";
31
+ ios: "ios";
32
+ web: "web";
33
+ }>;
34
+ name: z.ZodNullable<z.ZodString>;
35
+ model: z.ZodNullable<z.ZodString>;
36
+ osVersion: z.ZodNullable<z.ZodString>;
37
+ appVersion: z.ZodNullable<z.ZodString>;
38
+ lastIp: z.ZodNullable<z.ZodString>;
39
+ lastSeenAt: z.ZodISODateTime;
40
+ createdAt: z.ZodISODateTime;
41
+ }, z.core.$strip>;
42
+ export type AdminDeviceView = z.output<typeof AdminDeviceView>;
43
+ /** `GET {base}/admin/users`. */
44
+ export declare const AdminUsersResponse: z.ZodObject<{
45
+ users: z.ZodArray<z.ZodObject<{
46
+ id: z.ZodString;
47
+ email: z.ZodString;
48
+ name: z.ZodString;
49
+ emailVerified: z.ZodBoolean;
50
+ image: z.ZodNullable<z.ZodString>;
51
+ locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
52
+ createdAt: z.ZodISODateTime;
53
+ updatedAt: z.ZodISODateTime;
54
+ }, z.core.$strip>>;
55
+ nextCursor: z.ZodNullable<z.ZodString>;
56
+ }, z.core.$strip>;
57
+ export type AdminUsersResponse = z.output<typeof AdminUsersResponse>;
58
+ export declare const AdminUserResponse: z.ZodObject<{
59
+ user: z.ZodObject<{
60
+ id: z.ZodString;
61
+ email: z.ZodString;
62
+ name: z.ZodString;
63
+ emailVerified: z.ZodBoolean;
64
+ image: z.ZodNullable<z.ZodString>;
65
+ locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
66
+ createdAt: z.ZodISODateTime;
67
+ updatedAt: z.ZodISODateTime;
68
+ }, z.core.$strip>;
69
+ providers: z.ZodDiscriminatedUnion<[z.ZodObject<{
70
+ state: z.ZodLiteral<"read">;
71
+ items: z.ZodArray<z.ZodString>;
72
+ }, z.core.$strip>, z.ZodObject<{
73
+ state: z.ZodLiteral<"unavailable">;
74
+ }, z.core.$strip>], "state">;
75
+ sessions: z.ZodDiscriminatedUnion<[z.ZodObject<{
76
+ state: z.ZodLiteral<"read">;
77
+ items: z.ZodArray<z.ZodObject<{
78
+ id: z.ZodString;
79
+ deviceId: z.ZodNullable<z.ZodString>;
80
+ ipAddress: z.ZodNullable<z.ZodString>;
81
+ userAgent: z.ZodNullable<z.ZodString>;
82
+ createdAt: z.ZodISODateTime;
83
+ updatedAt: z.ZodISODateTime;
84
+ expiresAt: z.ZodISODateTime;
85
+ }, z.core.$strip>>;
86
+ truncated: z.ZodBoolean;
87
+ }, z.core.$strip>, z.ZodObject<{
88
+ state: z.ZodLiteral<"unavailable">;
89
+ }, z.core.$strip>], "state">;
90
+ devices: z.ZodDiscriminatedUnion<[z.ZodObject<{
91
+ state: z.ZodLiteral<"read">;
92
+ items: z.ZodArray<z.ZodObject<{
93
+ id: z.ZodString;
94
+ userId: z.ZodString;
95
+ platform: z.ZodEnum<{
96
+ android: "android";
97
+ ios: "ios";
98
+ web: "web";
99
+ }>;
100
+ name: z.ZodNullable<z.ZodString>;
101
+ model: z.ZodNullable<z.ZodString>;
102
+ osVersion: z.ZodNullable<z.ZodString>;
103
+ appVersion: z.ZodNullable<z.ZodString>;
104
+ lastIp: z.ZodNullable<z.ZodString>;
105
+ lastSeenAt: z.ZodISODateTime;
106
+ createdAt: z.ZodISODateTime;
107
+ }, z.core.$strip>>;
108
+ truncated: z.ZodBoolean;
109
+ }, z.core.$strip>, z.ZodObject<{
110
+ state: z.ZodLiteral<"unavailable">;
111
+ }, z.core.$strip>], "state">;
112
+ }, z.core.$strip>;
113
+ export type AdminUserResponse = z.output<typeof AdminUserResponse>;
114
+ /** `GET {base}/admin/devices`. */
115
+ export declare const AdminDevicesResponse: z.ZodObject<{
116
+ devices: z.ZodArray<z.ZodObject<{
117
+ id: z.ZodString;
118
+ userId: z.ZodString;
119
+ platform: z.ZodEnum<{
120
+ android: "android";
121
+ ios: "ios";
122
+ web: "web";
123
+ }>;
124
+ name: z.ZodNullable<z.ZodString>;
125
+ model: z.ZodNullable<z.ZodString>;
126
+ osVersion: z.ZodNullable<z.ZodString>;
127
+ appVersion: z.ZodNullable<z.ZodString>;
128
+ lastIp: z.ZodNullable<z.ZodString>;
129
+ lastSeenAt: z.ZodISODateTime;
130
+ createdAt: z.ZodISODateTime;
131
+ }, z.core.$strip>>;
132
+ nextCursor: z.ZodNullable<z.ZodString>;
133
+ }, z.core.$strip>;
134
+ export type AdminDevicesResponse = z.output<typeof AdminDevicesResponse>;
135
+ /**
136
+ * `POST {base}/admin/sessions/revoke` and `POST {base}/admin/users/:userId/sessions/revoke`.
137
+ *
138
+ * A count and nothing else, deliberately. Both routes are idempotent — revoking a session that has
139
+ * already gone is a success — and neither caller holds a read scope, so the response must not say
140
+ * whose session it was. The owning user reaches the audit trail instead.
141
+ */
142
+ export declare const AdminRevokeResponse: z.ZodObject<{
143
+ revoked: z.ZodNumber;
144
+ }, z.core.$strip>;
145
+ export type AdminRevokeResponse = z.output<typeof AdminRevokeResponse>;
146
+ /** `POST {base}/admin/users/:userId/devices/revoke`. */
147
+ export declare const AdminDeviceRevokeResponse: z.ZodObject<{
148
+ revoked: z.ZodNumber;
149
+ removed: z.ZodBoolean;
150
+ }, z.core.$strip>;
151
+ export type AdminDeviceRevokeResponse = z.output<typeof AdminDeviceRevokeResponse>;
152
+ //# sourceMappingURL=responses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses.d.ts","sourceRoot":"","sources":["../../src/http/responses.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAwCxB,kDAAkD;AAClD,eAAO,MAAM,aAAa;;;;;;;;;iBAiBsF,CAAC;AACjH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAE3D,2FAA2F;AAC3F,eAAO,MAAM,gBAAgB;;;;;;;;iBAUiF,CAAC;AAC/G,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE,0GAA0G;AAC1G,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;iBAawF,CAAC;AACrH,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D,gCAAgC;AAChC,eAAO,MAAM,kBAAkB;;;;;;;;;;;;iBAKQ,CAAC;AACxC,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAoDrE,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAY3B,CAAC;AACJ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE,kCAAkC;AAClC,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;iBAKY,CAAC;AAC9C,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAEzE;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB;;iBAEsB,CAAC;AACvD,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEvE,wDAAwD;AACxD,eAAO,MAAM,yBAAyB;;;iBAKoE,CAAC;AAC3G,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,yBAAyB,CAAC,CAAC"}
@@ -0,0 +1,121 @@
1
+ import { DevicePlatform } from "../data/device.js";
2
+ import { z } from "zod";
3
+ import { Locale } from "@pithy-sh/core/src/i18n/locale";
4
+ //#region src/http/responses.ts
5
+ /**
6
+ * What the auth admin routes return, as Zod objects a management client can validate against.
7
+ *
8
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. Both halves are
9
+ * runtime values for the same reason: a management client reading a customer's Worker is crossing a
10
+ * trust boundary, its own rules require it to validate that response before rendering it, and a
11
+ * TypeScript interface is erased before it can help. Every client that had only an interface
12
+ * hand-wrote a mirror of these, and the mirror drifted the first time a field landed here.
13
+ *
14
+ * **No codecs, and no transform anywhere in this file.** These describe JSON on the wire, so parsing
15
+ * one hands back exactly what went in — which is what lets `responses.test.ts` compare a parsed value
16
+ * with the projection's output and fail on a field either side forgot. A `SQLiteDate` here would
17
+ * decode an ISO string into a `Date` and make that comparison meaningless.
18
+ *
19
+ * The projections that fill these live in `views.ts`, which documents *why* a credential is absent
20
+ * from each. This file is the shape; that file is the argument.
21
+ *
22
+ * **A field added here later is `.optional()`, not merely `.nullable()`.** This module is read across a
23
+ * version boundary — a management client validates a response with this schema against a customer's
24
+ * Worker at whatever kit version it is on — so an additive required key fails `safeParse` for everyone
25
+ * below that release and takes the whole pane with it (#450). Absent then means *this Worker cannot
26
+ * say*, which is a different fact from `null`.
27
+ */
28
+ /** Where a page resumes, or the end of the list. */
29
+ const NextCursor = z.string().nullable().describe("Where the next page resumes. Null at the end of the list. Opaque — pass it back verbatim.");
30
+ /** How many sessions a revocation actually ended. */
31
+ const RevokedCount = z.number().int().min(0).describe("How many sessions were revoked. Zero is a success: revoking nothing is the idempotent case.");
32
+ /** A user as a management client may see them. */
33
+ const AdminUserView = z.object({
34
+ id: z.string().describe("The user's id, as `pithy_auth_users.id` stores it."),
35
+ email: z.string().describe("The user's email address. Personal data, and the point of a support pane."),
36
+ name: z.string().describe("The display name from the provider profile or sign-up."),
37
+ emailVerified: z.boolean().describe("Whether the address has been verified."),
38
+ image: z.string().nullable().describe("The avatar URL from a social profile, or null."),
39
+ locale: Locale.nullable().optional().describe("The reader's chosen language as a BCP-47 tag; null when they have never chosen one, and absent when the Worker that answered predates the field (#450)."),
40
+ createdAt: z.iso.datetime().describe("When the user was created, ISO-8601."),
41
+ updatedAt: z.iso.datetime().describe("When the row was last written, ISO-8601.")
42
+ }).describe("One user as a management client sees them. The table holds no credential, so nothing is withheld.");
43
+ /** A session as a management client may see it — the token is not part of the contract. */
44
+ const AdminSessionView = z.object({
45
+ id: z.string().describe("The session's id — the handle `POST /admin/sessions/revoke` accepts. Not the token."),
46
+ deviceId: z.string().nullable().describe("The device this session was created on, or null."),
47
+ ipAddress: z.string().nullable().describe("Where the sign-in came from, or null. The field that catches a theft."),
48
+ userAgent: z.string().nullable().describe("The client user-agent at sign-in, or null."),
49
+ createdAt: z.iso.datetime().describe("When the session began, ISO-8601."),
50
+ updatedAt: z.iso.datetime().describe("When it was last refreshed, ISO-8601."),
51
+ expiresAt: z.iso.datetime().describe("When it lapses, ISO-8601.")
52
+ }).describe("One session as a management client sees it — without the token, which is the credential itself.");
53
+ /** A registered device as a management client may see it — the push token is not part of the contract. */
54
+ const AdminDeviceView = z.object({
55
+ id: z.string().describe("The client-generated device id it registered at sign-in."),
56
+ userId: z.string().describe("The owning user's id."),
57
+ platform: DevicePlatform.describe("The platform the device registered as."),
58
+ name: z.string().nullable().describe("The device's human label, or null."),
59
+ model: z.string().nullable().describe("The hardware model, or null."),
60
+ osVersion: z.string().nullable().describe("The device OS version at last sign-in, or null."),
61
+ appVersion: z.string().nullable().describe("The client app version at last sign-in, or null."),
62
+ lastIp: z.string().nullable().describe("Where the device was last seen, or null."),
63
+ lastSeenAt: z.iso.datetime().describe("When it was last seen, ISO-8601."),
64
+ createdAt: z.iso.datetime().describe("When it first registered, ISO-8601.")
65
+ }).describe("One registered device as a management client sees it — without the push token, which is a credential.");
66
+ /** `GET {base}/admin/users`. */
67
+ const AdminUsersResponse = z.object({
68
+ users: z.array(AdminUserView).describe("The page, newest first."),
69
+ nextCursor: NextCursor
70
+ }).describe("A page of the user list.");
71
+ /** `GET {base}/admin/users/:userId`. */
72
+ /**
73
+ * A sub-read of the user pane that could not be made (#380).
74
+ *
75
+ * The pane fans out over three independent tables and this route used to `Promise.all` them: one D1 read
76
+ * failing took the whole page down, so a support agent looking at a locked-out account saw a 500 instead
77
+ * of the user and whichever lists did read.
78
+ *
79
+ * It carries **no rows and no reason**. No rows, because an empty array means *this user has none* and a
80
+ * pane rendering "no active sessions" over a list nobody read is telling a support agent something that
81
+ * was never established. No reason, because what a D1 read throws names a query and a table, and this
82
+ * response crosses a trust boundary to a management client.
83
+ */
84
+ const ListUnavailable = z.object({ state: z.literal("unavailable").describe("The list could not be read on this request.") }).describe("Nothing was established about this list. Deliberately empty — there is nothing here to render as 'none'.");
85
+ /** A bounded sub-list, behind its state: the rows and the truncation flag are unreachable without narrowing. */
86
+ const boundedList = (items, what) => z.discriminatedUnion("state", [z.object({
87
+ state: z.literal("read").describe("The list was read."),
88
+ items: z.array(items).describe(`${what} Empty means this user has none.`),
89
+ truncated: z.boolean().describe("True when more rows exist than the bound allowed. A pane must say so rather than imply a total.")
90
+ }).describe("The rows, and whether the bound cut them short."), ListUnavailable]).describe(`${what} Behind a state, so an unread list cannot be rendered as an empty one.`);
91
+ /** An unbounded sub-list, behind the same state. No truncation flag: this read has no bound to exceed. */
92
+ const wholeList = (items, what) => z.discriminatedUnion("state", [z.object({
93
+ state: z.literal("read").describe("The list was read."),
94
+ items: z.array(items).describe(`${what} Empty means this user has none.`)
95
+ }).describe("The rows, in full."), ListUnavailable]).describe(`${what} Behind a state, so an unread list cannot be rendered as an empty one.`);
96
+ const AdminUserResponse = z.object({
97
+ user: AdminUserView.describe("The user."),
98
+ providers: wholeList(z.string(), "The OAuth providers linked to this account, as slugs. Read by a query that selects only `providerId`, so no provider token is ever loaded."),
99
+ sessions: boundedList(AdminSessionView, "Their live sessions, newest first, bounded."),
100
+ devices: boundedList(AdminDeviceView, "Their registered devices, most recently seen first, bounded.")
101
+ }).describe("One user with their live sessions, registered devices, and linked providers. The user is the subject and its absence is a 404; the three lists are contributors, and one that will not read costs its own list and not the page (#380).");
102
+ /** `GET {base}/admin/devices`. */
103
+ const AdminDevicesResponse = z.object({
104
+ devices: z.array(AdminDeviceView).describe("The page, most recently seen first."),
105
+ nextCursor: NextCursor
106
+ }).describe("A page of the device registry.");
107
+ /**
108
+ * `POST {base}/admin/sessions/revoke` and `POST {base}/admin/users/:userId/sessions/revoke`.
109
+ *
110
+ * A count and nothing else, deliberately. Both routes are idempotent — revoking a session that has
111
+ * already gone is a success — and neither caller holds a read scope, so the response must not say
112
+ * whose session it was. The owning user reaches the audit trail instead.
113
+ */
114
+ const AdminRevokeResponse = z.object({ revoked: RevokedCount }).describe("How many sessions the revocation ended.");
115
+ /** `POST {base}/admin/users/:userId/devices/revoke`. */
116
+ const AdminDeviceRevokeResponse = z.object({
117
+ revoked: RevokedCount,
118
+ removed: z.boolean().describe("Whether a device row was deleted. False when the user had no such device.")
119
+ }).describe("How many sessions the device revocation ended, and whether the registry row went with them.");
120
+ //#endregion
121
+ export { AdminDeviceRevokeResponse, AdminDeviceView, AdminDevicesResponse, AdminRevokeResponse, AdminSessionView, AdminUserResponse, AdminUserView, AdminUsersResponse };
@@ -0,0 +1,34 @@
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 auth routes onto the backend's Hono app.
6
+ *
7
+ * Order matters: turnstile gates the human-initiated send routes (only when composed), Pithy's own
8
+ * routes are registered before the catch-all so they win, and Better Auth owns everything else under
9
+ * `basePath`. A handler that returns a Response ends the chain, so the specific routes never fall
10
+ * through to the catch-all. (The tier-1 edge rate limiter is contributed as capability *middleware*, so
11
+ * it runs before session resolution — see `capability.ts`.)
12
+ *
13
+ * What each Pithy-owned route accepts, declared on its route line (schemas in `./schemas`):
14
+ *
15
+ * | Route | Verification | Input |
16
+ * | -------------------------- | --------------- | --------------------------- |
17
+ * | `POST /token/rotate` | bearer/session | none — the credential only |
18
+ * | `GET /devices` | bearer/session | none |
19
+ * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
20
+ * | `* /admin/*` | control-plane | see `./adminRoutes` |
21
+ *
22
+ * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
23
+ * and reading the body first would consume the stream. Better Auth validates its own endpoints and
24
+ * answers its own refusals; what it rejects reaches a caller in its shape, not ours.
25
+ *
26
+ * **The admin routes must be registered before the catch-all, and it is not a style preference.**
27
+ * `handleBetterAuth` returns a Response, which ends the chain — so a route registered after
28
+ * `app.all(`${base}/*`)` is mounted, is visible in `app.routes`, and never runs. A management call to
29
+ * `/auth/admin/users` would instead reach Better Auth, which knows no such endpoint, and the failure
30
+ * would look like a 404 from the wrong layer. `routeContract.test.ts` proves the ordering with a real
31
+ * request rather than by inspecting the route table, because the route table cannot see this.
32
+ */
33
+ export declare function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>) => void;
34
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAsBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAgCtF"}