@0x0501/mystack 0.0.0-stage → 0.1.0-bootstrap.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 (211) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/assets/auth.sqlite.schema.ts +479 -0
  4. package/assets/bun-sqlite.test.ts +46 -0
  5. package/assets/d1.test.ts +41 -0
  6. package/assets/drizzle.config.ts +2 -0
  7. package/assets/generate-auth-schema.mjs +25 -0
  8. package/assets/platform.sqlite.schema.ts +46 -0
  9. package/assets/polar-checkout.ts +10 -0
  10. package/assets/polar-route.ts +19 -0
  11. package/assets/polar.test.ts +30 -0
  12. package/assets/polar.ts +12 -0
  13. package/assets/purchase.bun-sqlite.ts +38 -0
  14. package/assets/purchase.sqlite.ts +39 -0
  15. package/assets/sqlite-migrations/0000_thin_phalanx.sql +295 -0
  16. package/assets/sqlite-migrations/meta/0000_snapshot.json +2058 -0
  17. package/assets/sqlite-migrations/meta/_journal.json +13 -0
  18. package/assets/turso.test.ts +40 -0
  19. package/package.json +44 -5
  20. package/src/adapters/database.mjs +448 -0
  21. package/src/adapters/deployment.mjs +101 -0
  22. package/src/adapters/email.mjs +75 -0
  23. package/src/adapters/payments.mjs +270 -0
  24. package/src/catalog.mjs +128 -0
  25. package/src/cli.mjs +294 -0
  26. package/src/generate.mjs +183 -0
  27. package/src/template.mjs +93 -0
  28. package/template/.env.docker +16 -0
  29. package/template/.env.example +67 -0
  30. package/template/DESIGN.md +58 -0
  31. package/template/LICENSE +21 -0
  32. package/template/biome.json +46 -0
  33. package/template/docker-compose.yml +47 -0
  34. package/template/docs/project-guide.md +61 -0
  35. package/template/drizzle/0000_create-app-role.sql +54 -0
  36. package/template/drizzle/0001_add-rls-context.sql +21 -0
  37. package/template/drizzle/0002_platform_tables.sql +320 -0
  38. package/template/drizzle/meta/0002_snapshot.json +2125 -0
  39. package/template/drizzle/meta/_journal.json +27 -0
  40. package/template/drizzle.config.ts +25 -0
  41. package/template/e2e/authenticated-ui.spec.ts +40 -0
  42. package/template/e2e/headless-design.spec.ts +66 -0
  43. package/template/e2e/navigation-loading.spec.ts +70 -0
  44. package/template/e2e/theme-responsive.spec.ts +260 -0
  45. package/template/gitignore +24 -0
  46. package/template/messages/de.json +212 -0
  47. package/template/messages/en.json +212 -0
  48. package/template/package.json +101 -0
  49. package/template/paraglide.config.ts +49 -0
  50. package/template/playwright.config.ts +58 -0
  51. package/template/project.inlang/settings.json +12 -0
  52. package/template/public/drizzle.svg +1 -0
  53. package/template/public/favicon.ico +0 -0
  54. package/template/public/logo192.png +0 -0
  55. package/template/public/logo512.png +0 -0
  56. package/template/public/manifest.json +25 -0
  57. package/template/public/robots.txt +3 -0
  58. package/template/scripts/check-client-bundle.ts +150 -0
  59. package/template/scripts/check-server-fns.ts +290 -0
  60. package/template/scripts/check-sql-raw.ts +50 -0
  61. package/template/scripts/compile-paraglide.ts +12 -0
  62. package/template/scripts/postgres/README.md +76 -0
  63. package/template/scripts/postgres/create-app-role.sh +60 -0
  64. package/template/scripts/seed-local.ts +331 -0
  65. package/template/scripts/validate-prod-env.ts +53 -0
  66. package/template/src/__tests__/README.md +9 -0
  67. package/template/src/__tests__/account-security.test.ts +664 -0
  68. package/template/src/__tests__/admin-http-surface.test.ts +311 -0
  69. package/template/src/__tests__/admin-peer-protection.test.ts +178 -0
  70. package/template/src/__tests__/auth-harness.ts +104 -0
  71. package/template/src/__tests__/auth-rate-limit.test.ts +43 -0
  72. package/template/src/__tests__/auth-redirect.test.ts +120 -0
  73. package/template/src/__tests__/body-limit.test.ts +47 -0
  74. package/template/src/__tests__/creem.test.ts +62 -0
  75. package/template/src/__tests__/demo-checkout.test.ts +141 -0
  76. package/template/src/__tests__/email-locale.test.ts +110 -0
  77. package/template/src/__tests__/global-setup.ts +80 -0
  78. package/template/src/__tests__/input-rules.test.ts +0 -0
  79. package/template/src/__tests__/message-parity.test.ts +38 -0
  80. package/template/src/__tests__/navigation-loading.test.tsx +252 -0
  81. package/template/src/__tests__/nowpayments.test.ts +106 -0
  82. package/template/src/__tests__/paraglide-url-contract.test.ts +87 -0
  83. package/template/src/__tests__/purchase-fulfillment.test.ts +204 -0
  84. package/template/src/__tests__/query-unauthorized-redirect.test.ts +95 -0
  85. package/template/src/__tests__/rls-policy.test.ts +120 -0
  86. package/template/src/__tests__/same-page-locale-href.test.ts +47 -0
  87. package/template/src/__tests__/search-params-oauth.test.ts +57 -0
  88. package/template/src/__tests__/security-headers.test.ts +12 -0
  89. package/template/src/__tests__/server-fn-error-contract.test.ts +173 -0
  90. package/template/src/__tests__/stripe.test.ts +84 -0
  91. package/template/src/__tests__/test-db.ts +32 -0
  92. package/template/src/__tests__/test-rls-db.ts +23 -0
  93. package/template/src/__tests__/user-update-guard.test.ts +109 -0
  94. package/template/src/components/LocaleSwitcher.tsx +79 -0
  95. package/template/src/components/ThemeToggle.tsx +47 -0
  96. package/template/src/components/auth/social.tsx +90 -0
  97. package/template/src/components/auth/turnstile.tsx +67 -0
  98. package/template/src/components/root/navigation-progress.tsx +32 -0
  99. package/template/src/components/root/not-found.tsx +20 -0
  100. package/template/src/components/root/pending.tsx +9 -0
  101. package/template/src/components/root/root-document.tsx +37 -0
  102. package/template/src/components/root/root-error.tsx +34 -0
  103. package/template/src/components/shells.tsx +201 -0
  104. package/template/src/components/ui/styles.ts +9 -0
  105. package/template/src/db/auth.schema.ts +455 -0
  106. package/template/src/db/helper.ts +38 -0
  107. package/template/src/db/index.ts +15 -0
  108. package/template/src/db/platform.schema.ts +122 -0
  109. package/template/src/db/schema.ts +2 -0
  110. package/template/src/env.ts +65 -0
  111. package/template/src/hooks/use-theme.ts +32 -0
  112. package/template/src/integrations/better-auth/header-user.tsx +36 -0
  113. package/template/src/integrations/better-auth/session-query.ts +11 -0
  114. package/template/src/integrations/react-email/PasswordOtpEmail.tsx +62 -0
  115. package/template/src/integrations/react-email/ResetPasswordEmail.tsx +64 -0
  116. package/template/src/integrations/react-email/VerifyEmail.tsx +72 -0
  117. package/template/src/integrations/react-email/theme.ts +75 -0
  118. package/template/src/integrations/tanstack-query/devtools.tsx +6 -0
  119. package/template/src/integrations/tanstack-query/root-provider.tsx +60 -0
  120. package/template/src/lib/auth-client.ts +27 -0
  121. package/template/src/lib/auth-paths.ts +94 -0
  122. package/template/src/lib/auth-plugins/existing-email-signup.ts +86 -0
  123. package/template/src/lib/auth-plugins/field-rules.ts +84 -0
  124. package/template/src/lib/auth-plugins/social-two-factor.ts +194 -0
  125. package/template/src/lib/auth-timing.ts +9 -0
  126. package/template/src/lib/auth.ts +279 -0
  127. package/template/src/lib/captcha.ts +11 -0
  128. package/template/src/lib/email.tsx +162 -0
  129. package/template/src/lib/github.ts +18 -0
  130. package/template/src/lib/locale-cookie.ts +12 -0
  131. package/template/src/lib/localized-pages.ts +25 -0
  132. package/template/src/lib/oauth-metadata.ts +19 -0
  133. package/template/src/lib/permissions.ts +29 -0
  134. package/template/src/lib/security-headers.ts +20 -0
  135. package/template/src/lib/site.ts +59 -0
  136. package/template/src/lib/theme.ts +42 -0
  137. package/template/src/lib/user-update-guard.ts +35 -0
  138. package/template/src/middlewares/admin.ts +46 -0
  139. package/template/src/middlewares/auth-rate-limit.ts +37 -0
  140. package/template/src/middlewares/better-auth.ts +15 -0
  141. package/template/src/middlewares/body-limit.ts +62 -0
  142. package/template/src/middlewares/database.ts +13 -0
  143. package/template/src/middlewares/protected.ts +45 -0
  144. package/template/src/routeTree.gen.ts +536 -0
  145. package/template/src/router.tsx +53 -0
  146. package/template/src/routes/[.]well-known/oauth-authorization-server/api/auth.ts +18 -0
  147. package/template/src/routes/[.]well-known/oauth-protected-resource/index.ts +32 -0
  148. package/template/src/routes/__root.tsx +175 -0
  149. package/template/src/routes/admin/audit.tsx +74 -0
  150. package/template/src/routes/admin/index.tsx +7 -0
  151. package/template/src/routes/admin/oauth-apps.tsx +164 -0
  152. package/template/src/routes/admin/route.tsx +27 -0
  153. package/template/src/routes/admin/users.tsx +215 -0
  154. package/template/src/routes/api/auth/$.ts +14 -0
  155. package/template/src/routes/api/auth/[.]well-known/openid-configuration.ts +15 -0
  156. package/template/src/routes/api/webhooks/creem.ts +69 -0
  157. package/template/src/routes/api/webhooks/nowpayments.ts +62 -0
  158. package/template/src/routes/api/webhooks/stripe.ts +74 -0
  159. package/template/src/routes/dashboard/account.tsx +430 -0
  160. package/template/src/routes/dashboard/index.tsx +128 -0
  161. package/template/src/routes/dashboard/route.tsx +17 -0
  162. package/template/src/routes/forgot-password.tsx +65 -0
  163. package/template/src/routes/index.tsx +85 -0
  164. package/template/src/routes/oauth/consent.tsx +77 -0
  165. package/template/src/routes/reset-password.tsx +78 -0
  166. package/template/src/routes/sign-in.tsx +174 -0
  167. package/template/src/routes/sign-up.tsx +135 -0
  168. package/template/src/routes/two-factor.tsx +74 -0
  169. package/template/src/server/README.md +3 -0
  170. package/template/src/server/account-security.ts +163 -0
  171. package/template/src/server/admin-audit.ts +37 -0
  172. package/template/src/server/admin-users.ts +112 -0
  173. package/template/src/server/auth.ts +44 -0
  174. package/template/src/server/demo-checkout.ts +67 -0
  175. package/template/src/server/oauth-clients.ts +83 -0
  176. package/template/src/server/payment-toggles.ts +39 -0
  177. package/template/src/server.ts +20 -0
  178. package/template/src/services/README.md +3 -0
  179. package/template/src/services/account-security.ts +893 -0
  180. package/template/src/services/admin-security.ts +164 -0
  181. package/template/src/services/admin-users.ts +181 -0
  182. package/template/src/services/auth-rate-limit.ts +32 -0
  183. package/template/src/services/creem.ts +83 -0
  184. package/template/src/services/demo-checkout.ts +100 -0
  185. package/template/src/services/nowpayments.ts +154 -0
  186. package/template/src/services/oauth-client.ts +85 -0
  187. package/template/src/services/oauth-clients.ts +15 -0
  188. package/template/src/services/payment-providers.ts +157 -0
  189. package/template/src/services/payment-toggles.ts +48 -0
  190. package/template/src/services/purchase.ts +233 -0
  191. package/template/src/services/stripe.ts +106 -0
  192. package/template/src/start.ts +35 -0
  193. package/template/src/styles/layout.css +93 -0
  194. package/template/src/styles/theme.css +84 -0
  195. package/template/src/styles/ui.css +233 -0
  196. package/template/src/styles.css +90 -0
  197. package/template/src/utils/api-error.ts +129 -0
  198. package/template/src/utils/auth-errors.ts +157 -0
  199. package/template/src/utils/auth-redirect.ts +61 -0
  200. package/template/src/utils/body-limit.ts +84 -0
  201. package/template/src/utils/cn.ts +6 -0
  202. package/template/src/utils/input-rules.ts +172 -0
  203. package/template/src/utils/locale-paths.ts +18 -0
  204. package/template/src/utils/same-page-locale-href.ts +20 -0
  205. package/template/src/utils/search-params.ts +71 -0
  206. package/template/tsconfig.json +30 -0
  207. package/template/tsr.config.json +6 -0
  208. package/template/vite.config.ts +24 -0
  209. package/template/vitest.config.ts +26 -0
  210. package/template/worker-configuration.d.ts +14660 -0
  211. package/template/wrangler.jsonc +39 -0
@@ -0,0 +1,201 @@
1
+ import { Link } from "@tanstack/react-router";
2
+ import type { ComponentProps, ReactNode } from "react";
3
+ import { LocaleSwitcher } from "@/components/LocaleSwitcher";
4
+ import { ThemeToggle } from "@/components/ThemeToggle";
5
+ import * as m from "@/paraglide/messages";
6
+ import { cn } from "@/utils/cn";
7
+ import { cardClass, labelClass, mutedTextClass } from "./ui/styles";
8
+
9
+ export {
10
+ buttonClass,
11
+ buttonPrimaryClass,
12
+ buttonSecondaryClass,
13
+ cardClass,
14
+ inputClass,
15
+ labelClass,
16
+ linkClass,
17
+ mutedTextClass,
18
+ } from "./ui/styles";
19
+
20
+ type ShellProps = ComponentProps<"div"> & { title: string };
21
+
22
+ /** Auth flow layout; presentation is replaceable through CSS and className. */
23
+ export function AuthShell({
24
+ title,
25
+ children,
26
+ className,
27
+ ...props
28
+ }: ShellProps) {
29
+ return (
30
+ <div {...props} className={cn("page page--narrow auth-shell", className)}>
31
+ <div className="auth-shell__header">
32
+ <Link to="/" className={cn(mutedTextClass, "hover:text-foreground")}>
33
+ ← {m.nav_home()}
34
+ </Link>
35
+ <div className="flex items-center gap-2">
36
+ <LocaleSwitcher variant="bare" />
37
+ <ThemeToggle />
38
+ </div>
39
+ </div>
40
+ <h1 className="shell-title auth-shell__title">{title}</h1>
41
+ <div
42
+ className={cn(cardClass, "auth-shell__content")}
43
+ data-testid="auth-card"
44
+ >
45
+ {children}
46
+ </div>
47
+ </div>
48
+ );
49
+ }
50
+
51
+ /** Signed-in member layout. */
52
+ export function DashboardShell({
53
+ title,
54
+ children,
55
+ className,
56
+ ...props
57
+ }: ShellProps) {
58
+ return (
59
+ <div
60
+ {...props}
61
+ className={cn("page app-shell", className)}
62
+ data-testid="dashboard-shell"
63
+ >
64
+ <header className="app-shell__header">
65
+ <div>
66
+ <p className="text-xs text-muted-foreground">{m.dashboard_title()}</p>
67
+ <h1 className="shell-title">{title}</h1>
68
+ </div>
69
+ <div className="flex flex-wrap items-center gap-3">
70
+ <nav
71
+ className="flex flex-wrap gap-3 text-sm"
72
+ aria-label={m.dashboard_title()}
73
+ >
74
+ <ShellNavLink to="/dashboard">{m.nav_overview()}</ShellNavLink>
75
+ <ShellNavLink to="/dashboard/account">
76
+ {m.nav_account()}
77
+ </ShellNavLink>
78
+ <ShellNavLink to="/" muted>
79
+ {m.nav_home()}
80
+ </ShellNavLink>
81
+ </nav>
82
+ <LocaleSwitcher />
83
+ <ThemeToggle />
84
+ </div>
85
+ </header>
86
+ {children}
87
+ </div>
88
+ );
89
+ }
90
+
91
+ /** Administrator layout. */
92
+ export function AdminShell({
93
+ title,
94
+ children,
95
+ className,
96
+ ...props
97
+ }: ShellProps) {
98
+ return (
99
+ <div
100
+ {...props}
101
+ className={cn("page page--wide app-shell", className)}
102
+ data-testid="admin-shell"
103
+ >
104
+ <header className="app-shell__header">
105
+ <div>
106
+ <p className="text-xs text-muted-foreground">{m.admin_title()}</p>
107
+ <h1 className="shell-title">{title}</h1>
108
+ </div>
109
+ <div className="flex flex-wrap items-center gap-3">
110
+ <nav
111
+ className="flex flex-wrap gap-3 text-sm"
112
+ aria-label={m.admin_title()}
113
+ >
114
+ <ShellNavLink to="/admin/users">{m.nav_users()}</ShellNavLink>
115
+ <ShellNavLink to="/admin/audit">{m.nav_audit()}</ShellNavLink>
116
+ <ShellNavLink to="/admin/oauth-apps">
117
+ {m.nav_oauth_apps()}
118
+ </ShellNavLink>
119
+ <ShellNavLink to="/dashboard" muted>
120
+ {m.nav_dashboard()}
121
+ </ShellNavLink>
122
+ </nav>
123
+ <LocaleSwitcher />
124
+ <ThemeToggle />
125
+ </div>
126
+ </header>
127
+ {children}
128
+ </div>
129
+ );
130
+ }
131
+
132
+ function ShellNavLink({
133
+ to,
134
+ children,
135
+ muted = false,
136
+ }: {
137
+ to:
138
+ | "/"
139
+ | "/dashboard"
140
+ | "/dashboard/account"
141
+ | "/admin/users"
142
+ | "/admin/audit"
143
+ | "/admin/oauth-apps";
144
+ children: ReactNode;
145
+ muted?: boolean;
146
+ }) {
147
+ return (
148
+ <Link
149
+ to={to}
150
+ activeOptions={{ exact: true }}
151
+ activeProps={{ "aria-current": "page" }}
152
+ className={cn(
153
+ "shell-nav-link",
154
+ muted ? "text-muted-foreground" : "text-foreground",
155
+ )}
156
+ >
157
+ {children}
158
+ </Link>
159
+ );
160
+ }
161
+
162
+ export function Field({
163
+ label,
164
+ children,
165
+ hint,
166
+ }: {
167
+ label: string;
168
+ children: ReactNode;
169
+ hint?: string;
170
+ }) {
171
+ return (
172
+ // biome-ignore lint/a11y/noLabelWithoutControl: control is provided via children
173
+ <label className="mb-4 block">
174
+ <span className={labelClass}>{label}</span>
175
+ {children}
176
+ {hint ? (
177
+ <span className={cn(mutedTextClass, "mt-1 block text-xs")}>{hint}</span>
178
+ ) : null}
179
+ </label>
180
+ );
181
+ }
182
+
183
+ export function PageAlert({
184
+ children,
185
+ tone = "error",
186
+ }: {
187
+ children: ReactNode;
188
+ tone?: "error" | "success" | "info";
189
+ }) {
190
+ const toneClass =
191
+ tone === "success"
192
+ ? "text-success"
193
+ : tone === "info"
194
+ ? "text-muted-foreground"
195
+ : "text-destructive";
196
+ return (
197
+ <p className={cn("mb-3 text-sm", toneClass)} role="alert">
198
+ {children}
199
+ </p>
200
+ );
201
+ }
@@ -0,0 +1,9 @@
1
+ /** Opt-in presentation hooks. Definitions live in styles/ui.css. */
2
+ export const buttonPrimaryClass = "ui-button ui-button--primary";
3
+ export const buttonSecondaryClass = "ui-button ui-button--secondary";
4
+ export const cardClass = "ui-card";
5
+ export const labelClass = "ui-label";
6
+ export const mutedTextClass = "ui-muted";
7
+ export const linkClass = "ui-link";
8
+ export const buttonClass = `${buttonPrimaryClass} w-full`;
9
+ export const inputClass = "ui-input";
@@ -0,0 +1,455 @@
1
+ import { relations } from "drizzle-orm";
2
+ import {
3
+ boolean,
4
+ index,
5
+ integer,
6
+ jsonb,
7
+ pgTable,
8
+ text,
9
+ timestamp,
10
+ uniqueIndex,
11
+ } from "drizzle-orm/pg-core";
12
+
13
+ export const user = pgTable("user", {
14
+ id: text("id").primaryKey(),
15
+ name: text("name").notNull(),
16
+ email: text("email").notNull().unique(),
17
+ emailVerified: boolean("email_verified").default(false).notNull(),
18
+ image: text("image"),
19
+ createdAt: timestamp("created_at").defaultNow().notNull(),
20
+ updatedAt: timestamp("updated_at")
21
+ .defaultNow()
22
+ .$onUpdate(() => /* @__PURE__ */ new Date())
23
+ .notNull(),
24
+ role: text("role"),
25
+ banned: boolean("banned").default(false),
26
+ banReason: text("ban_reason"),
27
+ banExpires: timestamp("ban_expires"),
28
+ twoFactorEnabled: boolean("two_factor_enabled").default(false),
29
+ tokensRevokedAt: timestamp("tokens_revoked_at"),
30
+ locale: text("locale"),
31
+ });
32
+
33
+ export const session = pgTable(
34
+ "session",
35
+ {
36
+ id: text("id").primaryKey(),
37
+ expiresAt: timestamp("expires_at").notNull(),
38
+ token: text("token").notNull().unique(),
39
+ createdAt: timestamp("created_at").defaultNow().notNull(),
40
+ updatedAt: timestamp("updated_at")
41
+ .$onUpdate(() => /* @__PURE__ */ new Date())
42
+ .notNull(),
43
+ ipAddress: text("ip_address"),
44
+ userAgent: text("user_agent"),
45
+ userId: text("user_id")
46
+ .notNull()
47
+ .references(() => user.id, { onDelete: "cascade" }),
48
+ impersonatedBy: text("impersonated_by"),
49
+ },
50
+ (table) => [index("session_userId_idx").on(table.userId)],
51
+ );
52
+
53
+ export const account = pgTable(
54
+ "account",
55
+ {
56
+ id: text("id").primaryKey(),
57
+ accountId: text("account_id").notNull(),
58
+ providerId: text("provider_id").notNull(),
59
+ userId: text("user_id")
60
+ .notNull()
61
+ .references(() => user.id, { onDelete: "cascade" }),
62
+ accessToken: text("access_token"),
63
+ refreshToken: text("refresh_token"),
64
+ idToken: text("id_token"),
65
+ accessTokenExpiresAt: timestamp("access_token_expires_at"),
66
+ refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
67
+ scope: text("scope"),
68
+ password: text("password"),
69
+ createdAt: timestamp("created_at").defaultNow().notNull(),
70
+ updatedAt: timestamp("updated_at")
71
+ .$onUpdate(() => /* @__PURE__ */ new Date())
72
+ .notNull(),
73
+ },
74
+ (table) => [index("account_userId_idx").on(table.userId)],
75
+ );
76
+
77
+ export const verification = pgTable(
78
+ "verification",
79
+ {
80
+ id: text("id").primaryKey(),
81
+ identifier: text("identifier").notNull(),
82
+ value: text("value").notNull(),
83
+ expiresAt: timestamp("expires_at").notNull(),
84
+ createdAt: timestamp("created_at").defaultNow().notNull(),
85
+ updatedAt: timestamp("updated_at")
86
+ .defaultNow()
87
+ .$onUpdate(() => /* @__PURE__ */ new Date())
88
+ .notNull(),
89
+ },
90
+ (table) => [index("verification_identifier_idx").on(table.identifier)],
91
+ );
92
+
93
+ export const jwks = pgTable("jwks", {
94
+ id: text("id").primaryKey(),
95
+ publicKey: text("public_key").notNull(),
96
+ privateKey: text("private_key").notNull(),
97
+ createdAt: timestamp("created_at").notNull(),
98
+ expiresAt: timestamp("expires_at"),
99
+ alg: text("alg"),
100
+ crv: text("crv"),
101
+ });
102
+
103
+ export const oauthClient = pgTable(
104
+ "oauth_client",
105
+ {
106
+ id: text("id").primaryKey(),
107
+ clientId: text("client_id").notNull().unique(),
108
+ clientSecret: text("client_secret"),
109
+ clientDiscoveryId: text("client_discovery_id"),
110
+ disabled: boolean("disabled").default(false),
111
+ skipConsent: boolean("skip_consent"),
112
+ enableEndSession: boolean("enable_end_session"),
113
+ subjectType: text("subject_type"),
114
+ scopes: text("scopes").array(),
115
+ clientCredentialsScopes: text("client_credentials_scopes")
116
+ .array()
117
+ .default([]),
118
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
119
+ createdAt: timestamp("created_at"),
120
+ updatedAt: timestamp("updated_at"),
121
+ name: text("name"),
122
+ uri: text("uri"),
123
+ icon: text("icon"),
124
+ contacts: text("contacts").array(),
125
+ tos: text("tos"),
126
+ policy: text("policy"),
127
+ softwareId: text("software_id"),
128
+ softwareVersion: text("software_version"),
129
+ softwareStatement: text("software_statement"),
130
+ redirectUris: text("redirect_uris").array().notNull(),
131
+ postLogoutRedirectUris: text("post_logout_redirect_uris").array(),
132
+ backchannelLogoutUri: text("backchannel_logout_uri"),
133
+ backchannelLogoutSessionRequired: boolean(
134
+ "backchannel_logout_session_required",
135
+ ),
136
+ tokenEndpointAuthMethod: text("token_endpoint_auth_method"),
137
+ applicationType: text("application_type"),
138
+ jwks: text("jwks"),
139
+ jwksUri: text("jwks_uri"),
140
+ grantTypes: text("grant_types").array(),
141
+ responseTypes: text("response_types").array(),
142
+ requirePKCE: boolean("require_pkce"),
143
+ dpopBoundAccessTokens: boolean("dpop_bound_access_tokens").default(false),
144
+ referenceId: text("reference_id"),
145
+ metadata: jsonb("metadata"),
146
+ },
147
+ (table) => [index("oauthClient_userId_idx").on(table.userId)],
148
+ );
149
+
150
+ export const oauthResource = pgTable("oauth_resource", {
151
+ id: text("id").primaryKey(),
152
+ identifier: text("identifier").notNull().unique(),
153
+ name: text("name").notNull(),
154
+ accessTokenTtl: integer("access_token_ttl"),
155
+ refreshTokenTtl: integer("refresh_token_ttl"),
156
+ signingAlgorithm: text("signing_algorithm"),
157
+ signingKeyId: text("signing_key_id"),
158
+ allowedScopes: text("allowed_scopes").array(),
159
+ customClaims: jsonb("custom_claims"),
160
+ dpopBoundAccessTokensRequired: boolean(
161
+ "dpop_bound_access_tokens_required",
162
+ ).default(false),
163
+ disabled: boolean("disabled").default(false),
164
+ createdAt: timestamp("created_at"),
165
+ updatedAt: timestamp("updated_at"),
166
+ policyVersion: integer("policy_version").default(1),
167
+ metadata: jsonb("metadata"),
168
+ });
169
+
170
+ export const oauthClientResource = pgTable(
171
+ "oauth_client_resource",
172
+ {
173
+ id: text("id").primaryKey(),
174
+ clientId: text("client_id")
175
+ .notNull()
176
+ .references(() => oauthClient.clientId, { onDelete: "cascade" }),
177
+ resourceId: text("resource_id")
178
+ .notNull()
179
+ .references(() => oauthResource.identifier, { onDelete: "cascade" }),
180
+ metadata: jsonb("metadata"),
181
+ createdAt: timestamp("created_at"),
182
+ },
183
+ (table) => [
184
+ uniqueIndex("oauthClientResource_clientId_resourceId_uidx").on(
185
+ table.clientId,
186
+ table.resourceId,
187
+ ),
188
+ index("oauthClientResource_clientId_idx").on(table.clientId),
189
+ index("oauthClientResource_resourceId_idx").on(table.resourceId),
190
+ ],
191
+ );
192
+
193
+ export const oauthRefreshToken = pgTable(
194
+ "oauth_refresh_token",
195
+ {
196
+ id: text("id").primaryKey(),
197
+ token: text("token").notNull().unique(),
198
+ clientId: text("client_id")
199
+ .notNull()
200
+ .references(() => oauthClient.clientId, { onDelete: "cascade" }),
201
+ sessionId: text("session_id").references(() => session.id, {
202
+ onDelete: "set null",
203
+ }),
204
+ userId: text("user_id")
205
+ .notNull()
206
+ .references(() => user.id, { onDelete: "cascade" }),
207
+ referenceId: text("reference_id"),
208
+ authorizationCodeId: text("authorization_code_id"),
209
+ resources: text("resources").array(),
210
+ requestedUserInfoClaims: text("requested_user_info_claims").array(),
211
+ expiresAt: timestamp("expires_at").notNull(),
212
+ createdAt: timestamp("created_at").notNull(),
213
+ revoked: timestamp("revoked"),
214
+ rotatedAt: timestamp("rotated_at"),
215
+ rotationReplayResponse: text("rotation_replay_response"),
216
+ rotationReplayExpiresAt: timestamp("rotation_replay_expires_at"),
217
+ authTime: timestamp("auth_time"),
218
+ confirmation: jsonb("confirmation"),
219
+ scopes: text("scopes").array().notNull(),
220
+ },
221
+ (table) => [
222
+ index("oauthRefreshToken_clientId_idx").on(table.clientId),
223
+ index("oauthRefreshToken_sessionId_idx").on(table.sessionId),
224
+ index("oauthRefreshToken_userId_idx").on(table.userId),
225
+ index("oauthRefreshToken_authorizationCodeId_idx").on(
226
+ table.authorizationCodeId,
227
+ ),
228
+ ],
229
+ );
230
+
231
+ export const oauthAccessToken = pgTable(
232
+ "oauth_access_token",
233
+ {
234
+ id: text("id").primaryKey(),
235
+ token: text("token").notNull().unique(),
236
+ clientId: text("client_id")
237
+ .notNull()
238
+ .references(() => oauthClient.clientId, { onDelete: "cascade" }),
239
+ sessionId: text("session_id").references(() => session.id, {
240
+ onDelete: "set null",
241
+ }),
242
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
243
+ referenceId: text("reference_id"),
244
+ authorizationCodeId: text("authorization_code_id"),
245
+ resources: text("resources").array(),
246
+ requestedUserInfoClaims: text("requested_user_info_claims").array(),
247
+ refreshId: text("refresh_id").references(() => oauthRefreshToken.id, {
248
+ onDelete: "cascade",
249
+ }),
250
+ expiresAt: timestamp("expires_at").notNull(),
251
+ createdAt: timestamp("created_at").notNull(),
252
+ revoked: timestamp("revoked"),
253
+ confirmation: jsonb("confirmation"),
254
+ scopes: text("scopes").array().notNull(),
255
+ },
256
+ (table) => [
257
+ index("oauthAccessToken_clientId_idx").on(table.clientId),
258
+ index("oauthAccessToken_sessionId_idx").on(table.sessionId),
259
+ index("oauthAccessToken_userId_idx").on(table.userId),
260
+ index("oauthAccessToken_authorizationCodeId_idx").on(
261
+ table.authorizationCodeId,
262
+ ),
263
+ index("oauthAccessToken_refreshId_idx").on(table.refreshId),
264
+ ],
265
+ );
266
+
267
+ export const oauthConsent = pgTable(
268
+ "oauth_consent",
269
+ {
270
+ id: text("id").primaryKey(),
271
+ clientId: text("client_id")
272
+ .notNull()
273
+ .references(() => oauthClient.clientId, { onDelete: "cascade" }),
274
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
275
+ referenceId: text("reference_id"),
276
+ resources: text("resources").array(),
277
+ requestedUserInfoClaims: text("requested_user_info_claims").array(),
278
+ scopes: text("scopes").array().notNull(),
279
+ createdAt: timestamp("created_at").notNull(),
280
+ updatedAt: timestamp("updated_at").notNull(),
281
+ },
282
+ (table) => [
283
+ index("oauthConsent_clientId_idx").on(table.clientId),
284
+ index("oauthConsent_userId_idx").on(table.userId),
285
+ ],
286
+ );
287
+
288
+ export const oauthClientAssertion = pgTable("oauth_client_assertion", {
289
+ id: text("id").primaryKey(),
290
+ expiresAt: timestamp("expires_at").notNull(),
291
+ });
292
+
293
+ export const twoFactor = pgTable(
294
+ "two_factor",
295
+ {
296
+ id: text("id").primaryKey(),
297
+ secret: text("secret").notNull(),
298
+ backupCodes: text("backup_codes").notNull(),
299
+ userId: text("user_id")
300
+ .notNull()
301
+ .references(() => user.id, { onDelete: "cascade" }),
302
+ verified: boolean("verified").default(true),
303
+ failedVerificationCount: integer("failed_verification_count").default(0),
304
+ lockedUntil: timestamp("locked_until"),
305
+ },
306
+ (table) => [
307
+ index("twoFactor_secret_idx").on(table.secret),
308
+ index("twoFactor_userId_idx").on(table.userId),
309
+ ],
310
+ );
311
+
312
+ export const passkey = pgTable(
313
+ "passkey",
314
+ {
315
+ id: text("id").primaryKey(),
316
+ name: text("name"),
317
+ publicKey: text("public_key").notNull(),
318
+ userId: text("user_id")
319
+ .notNull()
320
+ .references(() => user.id, { onDelete: "cascade" }),
321
+ credentialID: text("credential_id").notNull(),
322
+ counter: integer("counter").notNull(),
323
+ deviceType: text("device_type").notNull(),
324
+ backedUp: boolean("backed_up").notNull(),
325
+ transports: text("transports"),
326
+ createdAt: timestamp("created_at"),
327
+ aaguid: text("aaguid"),
328
+ },
329
+ (table) => [
330
+ index("passkey_userId_idx").on(table.userId),
331
+ index("passkey_credentialID_idx").on(table.credentialID),
332
+ ],
333
+ );
334
+
335
+ export const userRelations = relations(user, ({ many }) => ({
336
+ sessions: many(session),
337
+ accounts: many(account),
338
+ oauthClients: many(oauthClient),
339
+ oauthRefreshTokens: many(oauthRefreshToken),
340
+ oauthAccessTokens: many(oauthAccessToken),
341
+ oauthConsents: many(oauthConsent),
342
+ twoFactors: many(twoFactor),
343
+ passkeys: many(passkey),
344
+ }));
345
+
346
+ export const sessionRelations = relations(session, ({ one, many }) => ({
347
+ user: one(user, {
348
+ fields: [session.userId],
349
+ references: [user.id],
350
+ }),
351
+ oauthRefreshTokens: many(oauthRefreshToken),
352
+ oauthAccessTokens: many(oauthAccessToken),
353
+ }));
354
+
355
+ export const accountRelations = relations(account, ({ one }) => ({
356
+ user: one(user, {
357
+ fields: [account.userId],
358
+ references: [user.id],
359
+ }),
360
+ }));
361
+
362
+ export const oauthClientRelations = relations(oauthClient, ({ one, many }) => ({
363
+ user: one(user, {
364
+ fields: [oauthClient.userId],
365
+ references: [user.id],
366
+ }),
367
+ oauthClientResources: many(oauthClientResource),
368
+ oauthRefreshTokens: many(oauthRefreshToken),
369
+ oauthAccessTokens: many(oauthAccessToken),
370
+ oauthConsents: many(oauthConsent),
371
+ }));
372
+
373
+ export const oauthResourceRelations = relations(oauthResource, ({ many }) => ({
374
+ oauthClientResources: many(oauthClientResource),
375
+ }));
376
+
377
+ export const oauthClientResourceRelations = relations(
378
+ oauthClientResource,
379
+ ({ one }) => ({
380
+ oauthClient: one(oauthClient, {
381
+ fields: [oauthClientResource.clientId],
382
+ references: [oauthClient.clientId],
383
+ }),
384
+ oauthResource: one(oauthResource, {
385
+ fields: [oauthClientResource.resourceId],
386
+ references: [oauthResource.identifier],
387
+ }),
388
+ }),
389
+ );
390
+
391
+ export const oauthRefreshTokenRelations = relations(
392
+ oauthRefreshToken,
393
+ ({ one, many }) => ({
394
+ oauthClient: one(oauthClient, {
395
+ fields: [oauthRefreshToken.clientId],
396
+ references: [oauthClient.clientId],
397
+ }),
398
+ session: one(session, {
399
+ fields: [oauthRefreshToken.sessionId],
400
+ references: [session.id],
401
+ }),
402
+ user: one(user, {
403
+ fields: [oauthRefreshToken.userId],
404
+ references: [user.id],
405
+ }),
406
+ oauthAccessTokens: many(oauthAccessToken),
407
+ }),
408
+ );
409
+
410
+ export const oauthAccessTokenRelations = relations(
411
+ oauthAccessToken,
412
+ ({ one }) => ({
413
+ oauthClient: one(oauthClient, {
414
+ fields: [oauthAccessToken.clientId],
415
+ references: [oauthClient.clientId],
416
+ }),
417
+ session: one(session, {
418
+ fields: [oauthAccessToken.sessionId],
419
+ references: [session.id],
420
+ }),
421
+ user: one(user, {
422
+ fields: [oauthAccessToken.userId],
423
+ references: [user.id],
424
+ }),
425
+ oauthRefreshToken: one(oauthRefreshToken, {
426
+ fields: [oauthAccessToken.refreshId],
427
+ references: [oauthRefreshToken.id],
428
+ }),
429
+ }),
430
+ );
431
+
432
+ export const oauthConsentRelations = relations(oauthConsent, ({ one }) => ({
433
+ oauthClient: one(oauthClient, {
434
+ fields: [oauthConsent.clientId],
435
+ references: [oauthClient.clientId],
436
+ }),
437
+ user: one(user, {
438
+ fields: [oauthConsent.userId],
439
+ references: [user.id],
440
+ }),
441
+ }));
442
+
443
+ export const twoFactorRelations = relations(twoFactor, ({ one }) => ({
444
+ user: one(user, {
445
+ fields: [twoFactor.userId],
446
+ references: [user.id],
447
+ }),
448
+ }));
449
+
450
+ export const passkeyRelations = relations(passkey, ({ one }) => ({
451
+ user: one(user, {
452
+ fields: [passkey.userId],
453
+ references: [user.id],
454
+ }),
455
+ }));
@@ -0,0 +1,38 @@
1
+ import { sql } from "drizzle-orm";
2
+ import type { Database, DatabaseTx } from ".";
3
+
4
+ export async function setRlsUserId(
5
+ tx: DatabaseTx,
6
+ userId: string,
7
+ ): Promise<void> {
8
+ await tx.execute(sql`SELECT set_config('app.user_id', ${userId}, true)`);
9
+ }
10
+
11
+ // SECURITY: `app.service` is a USERSET GUC that is_admin() and the RLS bypass
12
+ // trust. The app role is NOBYPASSRLS, so a SQL injection that can SET this GUC
13
+ // could escalate. Mitigate with parameterized queries only; a dedicated
14
+ // BYPASSRLS service role is a later hardening step.
15
+ export async function setRlsService(tx: DatabaseTx): Promise<void> {
16
+ await tx.execute(sql`SELECT set_config('app.service', 'true', true)`);
17
+ }
18
+
19
+ export function withRlsUser<T>(
20
+ db: Database,
21
+ userId: string,
22
+ fn: (tx: Database) => T | Promise<T>,
23
+ ): Promise<T> {
24
+ return db.transaction(async (tx) => {
25
+ await setRlsUserId(tx, userId);
26
+ return fn(tx as unknown as Database);
27
+ });
28
+ }
29
+
30
+ export function withRlsService<T>(
31
+ db: Database,
32
+ fn: (tx: Database) => T | Promise<T>,
33
+ ): Promise<T> {
34
+ return db.transaction(async (tx) => {
35
+ await setRlsService(tx);
36
+ return fn(tx as unknown as Database);
37
+ });
38
+ }